如何:读取所选DataGrid行的内容

时间:2014-05-30 13:36:20

标签: c# wpf string binding datagrid

如何:阅读所选DataGrid行的内容

我有一个DataGrid,它由一个类(MyClass)填充到Binding。这很完美。现在,我想从所选行中获取字段的内容。

示例:Doe John CEO 2002 现在,当我选择这一行时,我想保存(第一)内容" Doe"变成一个字符串。

DataRowView row = (DataRowView)dataGrid_Test.SelectedItems[0];
string s = row["LastName"].ToString();

但这样做,我只是收到一条错误消息:

System.InvalidCastException was unhandled.
Unable to cast object of type "MyClass" to type "System.Data.DataRowView".

4 个答案:

答案 0 :(得分:3)

SelectedItem属性绑定到您的MyClass对象。以这种方式检索属性:

MyClass obj = (MyClass)dataGrid_Test.SelectedItems[0];
string s = myClass.LastName;

答案 1 :(得分:1)

您可以使用以下代码选择数据网格的选定行:

String info = dataGrid_Test.CurrentRow.Cells["someColumnName"].ToString();

您可以将字符串替换为您需要的任何内容,并使用循环从网格中获取更多信息。

答案 2 :(得分:0)

我喜欢将数据表从datagridview中取出并进行操作。但我认为你的主要问题是你没有访问"值"属性。

DataRowView row = (DataRowView)dataGrid_Test.SelectedItems[0];
string s = row["LastName"].Value.ToString();

但是,就使用数据表而言,您可以获取数据源并获取数据行。这是在vb.net中:

   Dim DT as Datatable = Datagridview.datasource 
   Dim datarow As DataRow = DT.Rows(0)
   Dim strItem As String = datarow.Item("ColumnName")

答案 3 :(得分:0)

CurrentItem工作得很好(得益于DotN3TDev&#39的线索得到答案)

基本上,SelectedItem似乎是一个不一致的因为我设置了一个断点并进行了调试,有时会成功转换到DataRowView并且只发生了一些强制转换异常!所以另一种方法是:

var row = (DataRowView) dataGrid_Test.CurrentItem;
var s = row["LastName"].ToString();

更新:它仍然不一致,因为它实际上是一个被选中的新行。所以一种方法是

  • 检查dataGrid_Test.SelectedIndex的值是否超过当前行数。
  • 或者,使用 确保其现有行,否则假设其为新行

    if (dataGrid_Test.CurrentItem is DataRowView)
    {
        var row = (DataRowView) dataGrid_Test.CurrentItem;
        var s = row["LastName"].ToString();
    
        // do stuff - selected existing row
    }
    else
    {
        // selected the new (last) row
        // do other stuff - 
    }
    

如果要禁用此行为,可以在DataGrid上设置一个标志:

CanUserAddRows="False" 

或者,如果您不希望任何内容既不添加也不可编辑,但只能选择....

IsReadOnly="True"