Unable to cast object of type 'System.Data.DataRowView' to type 'System.Data.DataRow'
When databinding to a DataTable, the databinding engine will call the DataTable's IListSource
implementation and bind to its DataView
.
Since DataViews hold DataRowView objects and not DataRows, you cannot cast the bound objects directly to DataRow.
Instead, you need to cast to DataRowView
, then get the Row
property.
For a more detailed explanation of why this happens, see my blog.
Admin
Updated on June 05, 2022Comments
-
Admin almost 2 years
I will post an answer to an error I had since I found the solution.
I received the error in asp.net: Unable to cast object of type 'System.Data.DataRowView' to type 'System.Data.DataRow'
// Old line // rpOutils.DataSource = ds.Tables[0].Select("rnco_lang = '" + ddlLang.SelectedValue + "'"); // rpOutils.DataSource = ds; // New line that caused the error. I just wanted to pass a DataSet rpOutils.DataSource = ds.Tables[0].Select(); // New line with the solution. rpOutils.DataBind(); protected void rpOutils_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { DataRow row = (DataRow)e.Item.DataItem; // I received the System.InvalidCastException
...
The Dataset returned a DataRowView and the line that caused the problem expected a DataRow.
I searched for the solution and didn't find, so I found it and posted my solution. Thanks.