【发布时间】:2021-12-02 00:11:49
【问题描述】:
我想将数据网格中的选定行显示到一些文本框中。问题是它在转换为 DataRowView 时在第 4 行变为空。这是为什么呢?
1 private void dataGridView_SelectionChanged(object sender, SelectionChangedEventArgs e)
2 {
3 DataGrid grid = (DataGrid)sender;
4 DataRowView selected_row = grid.SelectedItem as DataRowView;
5
6 if (selected_row != null)
7 {
8 comboBoxCategory.Text = selected_row["Category"].ToString();
9 textBoxBrand.Text = selected_row["Brand"].ToString();
10 textBoxName.Text = selected_row["Name"].ToString();
11 textBoxCount.Text = selected_row["Count"].ToString();
12 textBoxPrice.Text = selected_row["Price"].ToString();
13 }
14 }
【问题讨论】:
-
感谢您在代码中添加了行号:clap
-
你在使用 mvvm,你是如何填充数据网格的?
-
您能否尝试
SelectedRows,然后SelectedRows[index]对应的列 -
我认为它只是一个 DataRow 而不是整个 DataRowView
-
您的 DataGrid 项目不是
DataRowView类型,所以as转换返回null。很可能是某个模型类对象(具有ID、Categorie等属性)。您可以在调试模式下使用GetType方法检查grid.SelectedItem类型:i.ibb.co/KwLb7tJ/1.jpg。然后使用as的正确演员表。
标签: c# wpf visual-studio datagrid