2

Hi I've written this code to search for cardserial in a gridview. But I get an error :

"Object reference not set to an instance of an object."

foreach (DataGridViewRow row in dataGridView2.Rows)
{
    if (row.Cells["CardSerial"].Value.ToString().Equals(textBox2.Text))
    {
        dataGridView2.Rows[row.Index].DefaultCellStyle.BackColor = Color.Yellow;
    }
}

Could you tell me what's the problem?

Cody Gray
  • 222,280
  • 47
  • 466
  • 543
saadat rahimi
  • 117
  • 2
  • 10
  • possible duplicate of [What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net) – Cody Gray Jul 22 '13 at 05:39
  • Debug and tell which line is giving error. – Ehsan Jul 22 '13 at 05:59

2 Answers2

2

First check if value in the cell is not null (if it is calling ToString on it fails)

foreach (DataGridViewRow row in dataGridView2.Rows)
{
    var serial = row.Cells["CardSerial"].Value;

    if (serial != null && serial.ToString().Equals(textBox2.Text))
    {
        row.DefaultCellStyle.BackColor = Color.Yellow;
    }
}
gzaxx
  • 16,281
  • 2
  • 31
  • 53
1

Most likely, of the following is null, which is causing the exception when you dereference it:

  • dataGridView2
  • row.Cells["CardSerial"]
  • row.Cells["CardSerial"].Value
  • textBox2
  • dataGridView2.Rows[row.Index]
  • dataGridView2.Rows[row.Index].DefaultCellStyle

To find out which one, debug your program, and make use of the watch window, immediate window, or add a number of debug/trace output lines.

Of specific note may be the case where row.Cells["CardSerial"].Value is null.

lc.
  • 105,606
  • 20
  • 147
  • 176
  • *"To find out which one, debug your program"* +1 – Cody Gray Jul 22 '13 at 05:40
  • I think `dataGridView2.Rows[row.Index]` cannot be null if the `row.Index` is not out of range. Otherwise the exception `IndexOutOfRangeException` will be thrown instead. – King King Jul 22 '13 at 10:06
  • @KingKing Yes, I believe that's quite correct, especially since the index comes from the row itself anyway (not sure why the OP doesn't just use `row.DefaultCellStyle`) – lc. Jul 22 '13 at 10:09