troubleshooting Question

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

Avatar of Mr_Fulano
Mr_FulanoFlag for United States of America asked on
10 Comments1 Solution107 ViewsLast Modified:
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();
Freelance programmer / Consultant

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 10 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 10 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros