我在下面写下了从选定的行特定单元格值中获取值的信息。但这是行不通的。尽管相同的代码正在我的项目的其他页面中运行,但我已经尝试了很多。下面是代码,这是堆栈跟踪:
private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataGrid gd = (DataGrid)sender;
DataRowView rowSelected = gd.SelectedItem as DataRowView;
label16.Content = Convert.ToString(rowSelected["quantity"]);
}
答案 0 :(得分:0)
gd.SelectedItem
不是DataRowView,因为类型转换后的rowSelected
是null
。很有可能是匿名类型对象(例如,如果从实体框架查询结果中设置了ItemsSource)
除非将ItemsSource类型更改为DataView,否则我建议两个选项:
使用dynamic
类型:
private void dg_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataGrid gd = (DataGrid)sender;
dynamic rowSelected = gd.SelectedItem;
label16.Content = rowSelected.quantity;
}
使用绑定:
private void dg_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataGrid gd = (DataGrid)sender;
BindingOperations.SetBinding(label16, Label.ContentProperty, new Binding("quantity") { Source = gd.SelectedItem });
}