i want to test rows color changing in DataGridView, so i wrote that code:
dataGridView1.Rows.Add(new object[] { "Uno", "No" });
dataGridView1.Rows.Add(new object[] { "Due", "No" });
dataGridView1.Rows.Add(new object[] { "Tre", "Yes" });
dataGridView1.Rows.Add(new object[] { "Quattro", "No" });
dataGridView1.Rows.Add(new object[] { "Cinque", "Yes" });
private void button1_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[1].Value.ToString() == "Yes")
row.DefaultCellStyle.ForeColor = Color.Red;
else
row.DefaultCellStyle.ForeColor = Color.Green;
}
}
So, there are five rows and two columns. But when i tried to change color, it gave me a NullReference exception, saying that row.Cells[1] values are null. What’s wrong?
Erase “toString()” in your if and it is working.Value is returning a string 😉
UPDATE:
Use this. It will cast the object into a string