首页 > 解决方案 > 如何在 WPF C# 中的 DataGrid 的 TextBoxes 中获取选定的行值

问题描述

我想将数据网格中的选定行显示到一些文本框中。问题是它在转换为 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    }

在此处输入图像描述

在此处输入图像描述

标签: c#wpfvisual-studiodatagrid

解决方案


显然,该SelectedItem属性不返回 a DataRowView

假设您已定义一个类型,则转换为适当的类型,或使用dynamic关键字:

private void dataGridView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    DataGrid grid = (DataGrid)sender;
    dynamic selected_row = grid.SelectedItem;

    comboBoxCategory.Text = selected_row.Categorie.ToString();
    textBoxBrand.Text = selected_row.Merk.ToString();
    textBoxName.Text = selected_row.Naam.ToString();
    textBoxCount.Text = selected_row.Aantal.ToString();
    textBoxPrice.Text = selected_row.Prijs.ToString();
}

推荐阅读