2013-07-22 225 views
2

您好我已經編寫了此代碼以在gridview中搜索cardserial。但是出現錯誤:NullReferenceException當在DataGridView中搜索數據時

「對象引用未設置爲對象的實例」。

foreach (DataGridViewRow row in dataGridView2.Rows) 
{ 
    if (row.Cells["CardSerial"].Value.ToString().Equals(textBox2.Text)) 
    { 
     dataGridView2.Rows[row.Index].DefaultCellStyle.BackColor = Color.Yellow; 
    } 
} 

你能告訴我出了什麼問題?

+0

可能重複(HTTP [什麼是.NET一個NullReferenceException?]://計算器。 com/questions/4660142/what-is-null-reference-in-net) –

+0

調試並確定哪一行發生錯誤。 – Ehsan

回答

1

首先檢查是否在單元格的值不爲空(如果它調用ToString上失敗)的

foreach (DataGridViewRow row in dataGridView2.Rows) 
{ 
    var serial = row.Cells["CardSerial"].Value; 

    if (serial != null && serial.ToString().Equals(textBox2.Text)) 
    { 
     row.DefaultCellStyle.BackColor = Color.Yellow; 
    } 
} 
2

最有可能的,下面是空,這是造成異常,當你取消對它的引用:

  • dataGridView2
  • row.Cells["CardSerial"]
  • row.Cells["CardSerial"].Value
  • textBox2
  • dataGridView2.Rows[row.Index]
  • dataGridView2.Rows[row.Index].DefaultCellStyle

要找出哪一個,調試程序,並利用監視窗口,立即窗口,或添加一些調試/跟蹤輸出線。

具體說明可能是row.Cells["CardSerial"].Value爲空的情況。

+0

*「找出哪一個,調試你的程序」* +1 –

+0

我認爲'dataGridView2.Rows [row.Index]'不能爲null,如果'row.Index'沒有超出範圍。否則,將拋出異常'IndexOutOfRangeException'。 –

+0

@KingKing是的,我相信這是非常正確的,特別是因爲索引本身來自行本身(不知道爲什麼OP不只是使用'row.DefaultCellStyle') –