【问题标题】:How to get the selected Row values in TextBoxes for DataGrid in WPF C#如何在 WPF C# 中的 DataGrid 的 TextBoxes 中获取选定的行值
【发布时间】: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。很可能是某个模型类对象(具有IDCategorie 等属性)。您可以在调试模式下使用GetType 方法检查grid.SelectedItem 类型:i.ibb.co/KwLb7tJ/1.jpg。然后使用 as 的正确演员表。

标签: c# wpf visual-studio datagrid


【解决方案1】:

显然SelectedItem 属性不会返回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();
}

【讨论】:

    猜你喜欢
    • 2017-08-18
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 2011-04-24
    相关资源
    最近更新 更多