我用这段代码用条件改变行的颜色,但代码不起作用!我不知道为什么,我有一个错误:
未处理的类型异常 System.NullReferenceException'发生在db(项目名称).exe
中
当我到达“color = dataGridView1.Rows ....”
时我该怎么办?
while (true)
{
color = dataGridView1[2, rowindex].Value.ToString();
if (color == "IDLE")
{
dataGridView1.Rows[rowindex].DefaultCellStyle.BackColor = Color.Orange;
}
if (color == "ACTIVE")
{ dataGridView1.Rows[rowindex].DefaultCellStyle.BackColor = Color.Green; }
if (color == "MAINTENANCE")
{ dataGridView1.Rows[rowindex].DefaultCellStyle.BackColor = Color.Purple; }
if (color == "DISMISSED")
{ dataGridView1.Rows[rowindex].DefaultCellStyle.BackColor = Color.Red; }
if (color == null)
{ break; }
rowindex++;
}
答案 0 :(得分:0)
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells["color"] == "IDLE")
{
row.DefaultCellStyle.BackColor = Color.Orange;
}
else
if (row.Cells["color"] == "ACTIVE")
{
row.DefaultCellStyle.BackColor = Color.Green;
}
else
if (row.Cells["color"] == "MAINTENANCE")
{
row.DefaultCellStyle.BackColor = Color.Purple;
}
else
if (row.Cells["color"] == "DISMISSED")
{
row.DefaultCellStyle.BackColor = Color.Red;
}
//else
//{
// break; //probably don't need this since the foreach will know when it's done looping through all the Rows
//}
}