Reputation: 147
I want the current row in a DataGridView
. Not by mouse click but by pressing enter...
I know of this:
datagridview.CurrentCell.RowIndex
and
datagridview.CurrentRow.Index
and
datagridview.SelectedRows[0].Index
...
My problem is that generally this works ok except when I get to the last row. Because it always gets the index of the second last row.
Any idea how this could happen?
Upvotes: 2
Views: 25729
Reputation: 2764
If DataGridView is configured to allow row adds, current cell selection is a little confusing.
Let's say there is a DataGridView control with 5 valid rows of data, and user clicks on row 5. Then user clicks on row 6 and the new row is added to the display and the cell on row 6 is highlighted.
But CurrentCell.RowIndex
and CurrentRow.Index
remain set to row 5 (actual value=4), even though the UI no longer shows the focus there.
This has nothing to do with mouse or keyboard.
I detect this case with code like this:
bool lastRowSelected = false;
if (grid.SelectedCells != null)
{
foreach (DataGridViewCell cell in grid.SelectedCells)
{
if (cell.RowIndex >= grid.NewRowIndex)
{
lastRowSelected = true;
break;
}
}
}
Upvotes: 0
Reputation: 54433
Catching the current row in a DataGridView
is really quite simple and you have posted two ways which work just fine:
int currentRow = datagridview.CurrentCell.RowIndex;
or:
int currentRow = datagridview.CurrentRow.Index
The third one is actually rather problematatic as, depending on the SelectionMode
of the DataGridView
the current row may not be selected.
But your problems come from trying to grab the index in response to the user hitting the Enter-key.
This by default will move the current cell one row down, if there is one. So the behaviour will vary between the last and the other rows..
If there isn't a 'next' row, the current cell will either stay where it is or, if AllowUserToAddRows
is true, the DGV will create a new, empty row and move there.
So if you always want to get the current index without moving the current cell you need to prevent the processing of the Enter-key.
Here is one way to do that:
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
// don't pass the enter key on to the DGV:
e.Handled = true;
// now store or proecess the index:
Console.WriteLine(dataGridView1.CurrentRow + "");
}
}
The user will still be able to move around with the cursor keys.
Upvotes: 6