Reputation: 13659
I have a DataGridView
control and I'm checking if I'm getting the correct value of column 0
But when I click my button to echo the value, I always get this error...
Are there errors in my code? Or what?
Upvotes: 0
Views: 2491
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
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
Reputation: 56133
Break up your long/compound statement into several lines/statements:
Upvotes: 1
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