0

I need to change the colors of a data grid view rows according to the data in the rows.

My code is:

foreach (DataGridViewRow Myrow in datagrid1.Rows)
{            
    if (Myrow.Cells[0].Value.Equals("Red"))
    {
        Myrow.DefaultCellStyle.BackColor = Color.Red;
    }
    {
        Myrow.DefaultCellStyle.BackColor = Color.Green;
    }
}

But when I try to run it I get: Object reference not set to an instance of an object

I assume it's because it keeps looping every row until it reaches some which has a null value. How do I stop it from doing that?

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
Martynas
  • 168
  • 2
  • 14
  • 2
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Fabio Sep 23 '16 at 09:52
  • 2
    At the beginning of the loop add `if(row.Cells[0].Value == null || row.Cells[0].Value == DBNull.Value) return;`. Also you can add `if(row.IsNewRow) return;` at the beginning of the loop. – Reza Aghaei Sep 23 '16 at 10:08

1 Answers1

3

I figured out I needed to change the DataGridView AllowUserToAddRows to false and that got rid of the empty row at the bottom which gave me the null value.

I'll leave this here if anybody else gets into the same situation.

Martynas
  • 168
  • 2
  • 14