【问题标题】:Get selected Datagrid's row data off of Datagrid从 Datagrid 中获取选定的 Datagrid 的行数据
【发布时间】:2017-11-22 19:51:10
【问题描述】:

我想从连接到实体框架数据库的数据网格中获取每一列的数据。 我想将它们投射到各自的文本框,但我似乎无法从数据网格中绘制数据。

这是我最初使用的代码 (saw it here on SO):

 private void DataGridCamiao_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        DataGrid DataGridCamiao = sender as DataGrid;
        DataRowView row = (DataRowView)DataGridCamiao.SelectedItems[0];
        TextBoxMarca.Text = row["Marca"].ToString();
    }

虽然运行后它给了我一个错误:

System.InvalidCastException:无法将 (我的自定义类型) 关联到 DataRowView

我已经阅读过它并将其更改为我的自定义类型,它说它不能被索引并且不能运行,这基本上让我在尝试其他方法时感到困惑。我想了解一下我在这里做错了什么,也许可以通过不同的方式来实现相同的目标,我非常感谢任何试图帮助我的人。

【问题讨论】:

    标签: c# wpf datagrid textbox


    【解决方案1】:

    您应该将SelectedItem 属性转换为您的实体类型:

    private void DataGridCamiao_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        DataGrid DataGridCamiao = sender as DataGrid;
        if (DataGridCamiao.SelectedItem != null)
        {
            var item = DataGridCamiao.SelectedItem as YourEntityClass;
            if (item != null)
                TextBoxMarca.Text = item.Marca;
        }
    }
    

    YourEntityClass 更改为您的实体类型的名称,即您已设置或绑定到DataGridItemsSource 属性的IEnumerable<T> 的类型T

    【讨论】:

    • 天哪,非常感谢。它现在起作用了,在过去的 72 小时里它一直在杀死我。非常感谢您帮助一个睡眠不足的大学生:p
    【解决方案2】:

    你可以在没有代码隐藏的情况下做同样的事情:

    <DataGrid Name="DataGridCamiao">
        <!--columns, attributes, etc here-->
    </DataGrid>
    
    <TextBox Name="TextBoxMarca" 
             Text="{Binding Path=SelectedItem.Marca, ElementName=DataGridCamiao}"/>
    

    最好切换到 MVVM 方法并绑定 DataGrid.SelectedItem 和 TextBox.Text 以查看模型属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-11
      • 1970-01-01
      • 2014-09-16
      • 2016-10-13
      • 1970-01-01
      • 1970-01-01
      • 2011-07-04
      • 1970-01-01
      相关资源
      最近更新 更多