1

I want to check if a particular cell of a datagridview has a particular value. So I made a double "for" loop to check through columns and rows. And there is the NullReferenceException thrown while checking using "if". Can someone please help me? What's more, if I put "try & catch" those cells ARE chosen and colored (I want them to be colored). I don't get it.

Here's the code:

 for (int column = 0; column < 7; column++)
 {
  for (int row = 0; row < 6; row++)
         {

  if (dataGridView1.Rows[row].Cells[column].Value.ToString() == data.Day.ToString())// EXCEPTION
       {
        dataGridView1[column, row].Style.BackColor = Color.LightGreen;
       }
   }
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Michal_Drwal
  • 526
  • 1
  • 9
  • 26
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Jun 14 '13 at 02:13

3 Answers3

3
dataGridView1.Rows[row].Cells[column].Value.ToString()   

data.Day.ToString())// EXCEPTION

one of those fields has a null value probably an empty cell when you try to convert to to string a nullreferenceexeption is thrown

check if values are not null before converting to string and comparing

COLD TOLD
  • 13,513
  • 3
  • 35
  • 52
0

The debugger is your friend here. Set a breakpoint on the if and run your app. Hover over the items with your mouse while execution is stopped to see their values. You can also add statements to the watch window to see their value. This will enable you to see what is null. The immediate window works well also. Just type a ? before a statement to execute it and print the value.

You will get a NullReferenceException anytime you attempt to call a method or access a member of an object that is set to null.

Trevor Tubbs
  • 2,097
  • 16
  • 18
0

You can do this also

YourGridData(DataGridView grid)
{
    int numCells = grid.SelectedCells.Count;

        foreach (DataGridViewCell cell in grid.SelectedCells)
        {
            if (cell.Value != null)
                //Do Something
            else
                //try or catch null here    
        }
}
Next Door Engineer
  • 2,818
  • 4
  • 20
  • 33