We help IT Professionals succeed at work.
Get Started

"System.NullReferenceException was unhandled" error after last valid row.

Mr_Fulano asked
Last Modified: 2016-08-19
Hi, I'm using Visual Studio 2010 C#. I have a DataGridView on one of my Forms that is connected to SQL database table. That part works. I'm also using the dataGridView1_RowEnter Event to populate the selected information into different Textboxes as I scroll down the grid. That works until I get past the last row.

As soon as I go beyond the length of the table (past the last row) and enter the first NULL row, I get the following error.  

ERROR: >> System.NullReferenceException was unhandled

Why is the  "if (e.RowIndex >= 0)" logic statement not preventing the error and how do I solve this problem?

private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
            DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
            if (e.RowIndex >= 0)
                textBox1.Text = row.Cells[1].Value.ToString();
                textBox2.Text = row.Cells[2].Value.ToString();
                textBox3.Text = row.Cells[3].Value.ToString();
                textBox4.Text = row.Cells[4].Value.ToString();

Open in new window

Watch Question
Freelance programmer / Consultant
This problem has been solved!
Unlock 1 Answer and 10 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE