Reputation: 2207
I have a datagridview
that no matter what cell I click on returns an out of index error.
When I debug the following code I get a -1
value for e.ColumnIndex
. As for e.RowIndex
, I get the correct row that I have clicked on.
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
form2.value = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
}
I have tried to replace the e.ColumnIndex
with a static int just to see if it works. When I add the int it doesn't do anything when I click on a particular row or column.
Anyone any ideas how I can change the ColumnIndex
or how I can work around this issue.
Upvotes: 1
Views: 2814
Reputation: 7082
try this one
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1) return;
if (e.ColumnIndex == -1) return;
Console.WriteLine(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
}
Upvotes: 0
Reputation: 8347
-1 for e.ColumnIndex
indicates that the RowHeader
is being selected. Are you sure you don't have the RowSelected
event bound to this event as well?
In any case, it is good practice to have checks of e.ColumnIndex
and e.RowIndex
that both are 0 or greater in any CellClick
event- the RowHeader
and ColumnHeader
cells will also fire this event when clicked, and would not contain data, which would be somewhat confusing for users.
Upvotes: 2