无法转换为 wpf 中的数据行视图
unable to cast to datarowview in wpf
ITs Xaml DataGrid 代码
<DataGrid AutoGenerateColumns="True" HorizontalAlignment="Left" Margin="10,30,0,0" ItemsSource="{Binding}" VerticalAlignment="Top" Height="149" Width="356" Name="orderGrid" SelectionMode="Single" SelectionUnit="FullRow" SelectionChanged="orderGrid_SelectionChanged" />
这是我的查询和项目来源
var orders = (from ss in db.electronics_orders
select new { ss.id,Date = ss.orderdate,Product_Title=ss.Electronic.Name, Quantity = ss.qty, TPrice = ss.qty * ss.unitprice}).ToList();
orderGrid.ItemsSource = orders;
现在我正在尝试将所选项目投射到数据行视图
try
{
DataRowView grid = (DataRowView)orderGrid.CurrentItem;
}
catch (Exception e1) {
MessageBox.Show(e1.Message);
}
但是显示错误
Unable to cast object of type
'<>f__AnonymousType05[System.Int32,System.Nullable
1[System.DateTime],System.String,System.Nullable1[System.Int32],System.Nullable
1[System.Int32]]'
to type 'System.Data.DataRow'.
当您在 linq (select new {ss.id,...}
) 中选择时,您基本上会得到一个新的内部匿名 class,它不是 DataRow
,就像它期望的那样。
您必须强制转换它,或者使用您要绑定的对象类型,这样它们将是 "compatible".
ITs Xaml DataGrid 代码
<DataGrid AutoGenerateColumns="True" HorizontalAlignment="Left" Margin="10,30,0,0" ItemsSource="{Binding}" VerticalAlignment="Top" Height="149" Width="356" Name="orderGrid" SelectionMode="Single" SelectionUnit="FullRow" SelectionChanged="orderGrid_SelectionChanged" />
这是我的查询和项目来源
var orders = (from ss in db.electronics_orders
select new { ss.id,Date = ss.orderdate,Product_Title=ss.Electronic.Name, Quantity = ss.qty, TPrice = ss.qty * ss.unitprice}).ToList();
orderGrid.ItemsSource = orders;
现在我正在尝试将所选项目投射到数据行视图
try
{
DataRowView grid = (DataRowView)orderGrid.CurrentItem;
}
catch (Exception e1) {
MessageBox.Show(e1.Message);
}
但是显示错误
Unable to cast object of type '<>f__AnonymousType0
5[System.Int32,System.Nullable
1[System.DateTime],System.String,System.Nullable1[System.Int32],System.Nullable
1[System.Int32]]' to type 'System.Data.DataRow'.
当您在 linq (select new {ss.id,...}
) 中选择时,您基本上会得到一个新的内部匿名 class,它不是 DataRow
,就像它期望的那样。
您必须强制转换它,或者使用您要绑定的对象类型,这样它们将是 "compatible".