如何在DataGrid中检索隐藏字段的值

时间:2016-03-01 06:54:37

标签: c# wpf datagrid

Image     |    ID (Hidden)  |  First Name   | Last Name ......
2231231        1               ABC             DEF 
2122342         2               ADED            SAD

模型类:对于我使用的场景。

 public partial class tbl_User
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Gender { get; set; }
    public string Email { get; set; }
    public string username { get; set; }
    public string password { get; set; }
    public byte[] Image { get; set; }
    public string Country { get; set; }
}

我想得到ID字段值我使用以下代码通过Null Reference Error - >

 private void userdatagrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

        DataRowView rowview = userdatagrid.SelectedItem as DataRowView;
         value = rowview.Row["ID"].ToString();

//第二种方法

 string ID = (userdatagrid.SelectedItem as tbl_User).ID.ToString(); 
    }

//双击事件

private void btnedit_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            DataRowView rowview = userdatagrid.SelectedItem as DataRowView;
            string id = rowview.Row[0].ToString();
            UpdateDetial ud = new UpdateDetial(int.Parse(value));
            ud.ShowDialog();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }

2 个答案:

答案 0 :(得分:0)

string ID = ((DataRowView)userdatagrid.SelectedItem).Row["id"].ToString();

var data = (DataRowView)userdatagrid.SelectedItem;
var userId = data.Row["id"];

答案 1 :(得分:0)

我想你有这样一个模特:

public class Person
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string SurName { get; set; }
}

然后,您可以使用SelectedItem事件中的SelectionChanged属性获取列的隐藏值:

private void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
   if (dataGrid.SelectedItem != null)
   {
      var data = (Person)dataGrid.SelectedItem;
      var userID = data.ID;
   }
}