Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

This question already has an answer here:

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;
       }
   }
}
share|improve this question

marked as duplicate by John Saunders, nvoigt, Florian Peschka, Ionică Bizău, K3N Jun 14 '13 at 6:35

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
Almost all cases of NullReferenceException are the same. Please see "What is a NullReferenceException in .NET?" for some hints. –  John Saunders Jun 14 '13 at 2:13

3 Answers 3

up vote 1 down vote accepted
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

share|improve this answer
    
Thanks, you're right. Works great now! :) –  Michal_Drwal Jun 14 '13 at 2:24

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.

share|improve this answer
    
That's true, thanks. I solved it. –  Michal_Drwal Jun 14 '13 at 2:25

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    
        }
}
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.