yonan2236
yonan2236

Reputation: 13659

What Causes this NullReferenceException when Accessing a Cell of a DataGridView?

I have a DataGridView control and I'm checking if I'm getting the correct value of column 0

alt text

But when I click my button to echo the value, I always get this error...

alt text

Are there errors in my code? Or what?

Upvotes: 0

Views: 2491

Answers (5)

Hai Bin Sy
Hai Bin Sy

Reputation: 11

When the datagridview initially bind with data, and you didn't click any row or any cell or the datagridview, the CurrentRow.Index property won't set to the "visibly" selected row. But when you run through each row, you will find that dgView.Rows[?].Selected has set to either true or false. you can create a method with try catch to catch the exception when getting the property of CurrentRow.Index. Try the following code.

try
{
    MessageBox.Show(dgView1[0,dgView1.CurrentRow.Index].Value.ToString());
}
catch
{
    for (int i = 0; i < dgView1.Rows.Count; i++)
    {
        if (dgView1.Rows[i].Selected) 
        {
           MessageBox.Show(dgView1[0,dgView1.Rows[i].Index].Value.ToString());
           return;
        }     
    }
}

Upvotes: 1

yonan2236
yonan2236

Reputation: 13659

I just created a new project a and I it worked... strange.

Upvotes: 0

Jude Cooray
Jude Cooray

Reputation: 19862

Try replacing

dgView.CurrentRow.Index with dgView.SelectedRows[0].Index

and set the property Multiselect to False, SelectionMode = FullRowSelect

Did that help? :)

Upvotes: -1

ChrisW
ChrisW

Reputation: 56133

Break up your long/compound statement into several lines/statements:

  • Is dbView1 null?
  • Is dbView1.CurrentRow null?
  • Is dbView1.CurrentRow.Index equal to -1, or greater than the number of rows?
  • Is dbView1[dbView1.CurrentRow.Index] null?

Upvotes: 1

Cheng Chen
Cheng Chen

Reputation: 43531

I think the most possible reason is that when you click the button, the form is focus on the 2nd row (row with *), this row has no reference to it until you click & input something in a cell of the row (if so, another row with * will be generated automatically). If you don't want the row to be generated automatically, just set dataGridView1.AllowUserToAddRows to false.

Upvotes: 0

Related Questions