2015-03-31 78 views
2

我必須要改變的細胞,當其值爲字符串或空的背景顏色,這是代碼,我寫類似於其他代碼在這裏:檢查datagridview的單元格爲空或空

for (int rowIndex = 0; rowIndex < dataGridView1.RowCount; rowIndex++) 
      { 
      string conte = dataGridView1.Rows[rowIndex].Cells[7].Value.ToString() ; 
       if (string.IsNullOrEmpty(conte)) 
       { 
       // dataGridView1.Rows[rowIndex].Cells[7].Style.BackColor = Color.Orange; 
       } 
       else 
       { dataGridView1.Rows[rowIndex].Cells[7].Style.BackColor = Color.Orange; } 
     } 

數據集是完整的,給我看datagridview填充和顯示我這個錯誤:enter image description here

我該如何解決這個問題?有另一種方式來編寫代碼?

+1

如果DGV是AllowUserToAddRows = True,那麼你迭代一行太多。在NRE回答 – Plutonix 2015-03-31 21:56:24

+0

覆蓋使用調試,如果你有問題後,有問題如何解決NullReferenceException。 – mybirthname 2015-03-31 21:56:26

回答

3

我將通過細胞使用類似下面的迭代..

foreach (DataGridViewRow dgRow in dataGridView1.Rows) 
{ 
    var cell = dgRow.Cells[7]; 
    if (cell.Value != null) //Check for null reference 
    { 
     cell.Style.BackColor = string.IsNullOrEmpty(cell.Value.ToString()) ? 
      Color.LightCyan : 
      Color.Orange;  
    } 
} 
1

你不需要ToString()。見here.

下面的代碼就足夠了。你

string conte = dataGridView1.Rows[rowIndex].Cells[7].Value; 

也可以嘗試類似:

if (string.IsNullOrEmpty(dataGridView1.Rows[0].Cells[7].Value as string))