无法将"System.Data.DataRowView"类型的对象强制转换为"System.Data.DataRow"类型

Tro*_*lon 2 c# asp.net ado.net compiler-errors

我将发布自我找到解决方案后出现的错误的答案.

我在asp.net中收到错误:无法将'System.Data.DataRowView'类型的对象强制转换为'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
Run Code Online (Sandbox Code Playgroud)

...

数据集返回了一个DataRowView,导致问题的行是DataRow.

我搜索了解决方案并没有找到,所以我找到了它并发布了我的解决方案.谢谢.

SLa*_*aks 6

当数据绑定到DataTable时,数据绑定引擎将调用DataTable的IListSource实现并绑定到它DataView.

由于DataViews包含DataRowView对象而不包含DataRows,因此无法将绑定对象直接转换为DataRow.
相反,您需要转换为DataRowView,然后获取Row属性.

有关发生这种情况的更详细说明,请参阅我的博客.