2014-10-18 20 views
0

我有一個數據表。我向該數據表添加一行。我想獲取datagridview的選定行的值到數據表綁定到的某個文本框中。在我的datagridview選擇更改方法我調用datatable行集合的查找方法。但它給了我NullReferenceException。C#Winforms DataTable找不到具有指定標識的行

 private void dgvRecipeMaterial_SelectionChanged(object sender, EventArgs e) 
     { 
      if(dgvRecipeMaterial.SelectedRows.Count > 0 && isDgvRecipeMaterialReady) 
      { 
       int rowIndex = dgvRecipeMaterial.SelectedRows[0].Index; 
       int id = Convert.ToInt32(dgvRecipeMaterial.SelectedRows[0].Cells[0].Value); 
       object[] data = dtrecetemalzemejoin.Rows[0].ItemArray; 
       object[] items = dtrecetemalzemejoin.Rows.Find(id).ItemArray; 
       . 
       . 
       . 
       . 

我看着我的ID通過調試器。它的值是1166.而當我調試時,我發現數據數組中有一個ID爲1166的項目。但是找到方法找不到id 1166.如果數據表中有多個記錄,則沒有問題。問題是什麼。數據數組有id,但find方法無法找到它。

+0

哪行代碼給你'NullReferenceException'? – Fabio 2014-10-18 19:38:27

+0

'object [] items = dtrecetemalzemejoin.Rows.Find(id).ItemArray;' – MOD 2014-10-19 08:04:07

+0

顯示代碼如何獲取數據到'dtrecetemalzemejoin' – Fabio 2014-10-19 11:21:49

回答

0

DataTable.Rows.Find方法從DataTable.PrimaryKey屬性搜索列的行。
檢查您的數據表主鍵是否包含您的ID值所在的列。如果PrimaryKey列沒有設置,然後使用Find方法之前,將其設置是這樣的:

dtrecetemalzemejoin.PrimaryKey = {dtrecetemalzemejoin.Columns[0]}; 
//or may be better will be using a name of column 
dtrecetemalzemejoin.PrimaryKey = {dtrecetemalzemejoin.Columns["IDColumn"]}; 
+0

我已經設置了主鍵值 – MOD 2014-10-18 19:00:31

+0

如果'PrimaryKey'包含'id'值爲,那麼你的代碼對我來說工作得很好 – Fabio 2014-10-18 19:41:44

+0

是的,它包含但不工作 – MOD 2014-10-19 08:04:40

0

可以嘗試下面的代碼我也收到同樣的錯誤

private void dgvRecipeMaterial_SelectionChanged(object sender, EventArgs e) 
     { 
      if(dgvRecipeMaterial.SelectedRows.Count > 0 && isDgvRecipeMaterialReady) 
      { 
       int rowIndex = dgvRecipeMaterial.SelectedRows[0].Index; 
       string id = Convert.ToString(dgvRecipeMaterial.SelectedRows[0].Cells[0].Value); 
       object[] data = dtrecetemalzemejoin.Rows[0].ItemArray; 
       object[] items = dtrecetemalzemejoin.Rows.Find(id).ItemArray; 
       . 
       . 
相關問題