2016-03-01 56 views
0
Image  | ID (Hidden) | First Name | Last Name ...... 
2231231  1    ABC    DEF 
2122342   2    ADED   SAD 

模型類:用於此場景,我使用。如何檢索DataGrid中的隱藏字段的值

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字段的值我用下面的代碼,通過空引用錯誤 - >

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); 
     } 

    } 
+0

'userdatagrid:

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

然後你就可以在SelectionChanged事件通過SelectedItem屬性來獲取欄的隱藏價值.SelectedItem作爲DataRowView','userdatagrid.SelectedItem as tbl_User' ??究竟是什麼類的'userdatagrid'行綁定?你可以發佈嗎? – Sakura

+0

及其與tbl_User類 – Khalid

+0

致盲如果是,'(userdatagrid.SelectedItem爲tbl_User).ID'將返回ID值,除非'的selectedIndex = -1' – Sakura

回答

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

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

這是什麼?問題是關於WPF,而不是ASP.NET – Sakura

+0

oops ..編輯答案爲WPF版本 –

+0

兩種解決方案拋出空引用異常 – Khalid

0

我想你有這樣一個模型:

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

其拋出空引用異常 – Khalid

+0

@Khalid你能告訴你模型類嗎? – StepUp