2015-03-31 55 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))