Thread: NullReferenceException

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    3

    NullReferenceException

    Code:
                        int countRows = dataGridView1.Rows.Count;
    
                        for (int i = 0; i < countRows + 1; i++)
                        {
                            if (int.Parse(dataGridView1.Rows[i].Cells[11].Value.ToString()) == 0)
                            {
                                dataGridView1.Rows[i].DefaultCellStyle.BackColor = Color.Red;
                            }
                        }
    This code will be used to determine wheter a cell value (from a datagridview) is 0, if so it's background color will be red.

    But i get a NullReferenceException at the red marked line.

    So i have two questions:

    1. How can i fix this?
    2. Is it possible to get data from a cell by using it's columnname? Not like dataGridView1.Rows[i].Cells[11].Value.ToString() since the database column places can be changed.

    Thanks in advance.

  2. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    You're trying to access a row that doesn't exist. Remove the "+1" in the loop, then read up on which indices are valid in an array.
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  3. #3
    Registered User
    Join Date
    Apr 2008
    Posts
    3
    I removed the +1 and i went through the loop with a messagebox to check if i would get the values i want and i did.

    So i don't know how to check what's wrong.

  4. #4
    Registered User
    Join Date
    Apr 2008
    Posts
    3
    Fixed it, the +1 had to be -1

  5. #5
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    Quote Originally Posted by Chronik View Post
    Fixed it, the +1 had to be -1
    Then you're not including the last row...
    May I suggest using enumerators to traverse the rows instead? Then you don't need to fiddle with indices.
    Code:
    foreach(System.Web.UI:WebControls.GridViewRow Row in dataGridView1.Rows)
    {
       if (int.Parse(Row.Cells[11].Value.ToString()) == 0)
       {
          Row.DefaultCellStyle.BackColor = Color.Red;
       }
    }
    Last edited by Magos; 05-09-2008 at 12:01 AM.
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

Popular pages Recent additions subscribe to a feed