.net – override navigation of datagridview using enter key

.netvb.net

How do you override the enter key in a datagridview so that it will set focus to the next column instead to the next row?

Best Solution

All you need to do is handle the KeyDown event of the DataGridView and in the handler, check if the current key pressed is an Enter key. If so, just set the CurrentCell of the DataGridView to the next cell (also check if this is the last cell in the row, in that case, move to the first cell of the next Row.)

Private Sub DataGridView1_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) Handles DataGridView1.KeyDown
  If e.KeyCode = Keys.Enter Then
    Dim numCols As Integer = DataGridView1.ColumnCount
    Dim numRows As Integer = DataGridView1.RowCount
    Dim currCell As DataGridViewCell = DataGridView1.CurrentCell
    If currCell.ColumnIndex = numCols - 1 Then
      If currCell.RowIndex < numRows - 1 Then
        DataGridView1.CurrentCell = DataGridView1.Item(0, currCell.RowIndex + 1)
      End If
    Else
      DataGridView1.CurrentCell = DataGridView1.Item(currCell.ColumnIndex + 1, currCell.RowIndex)
    End If
    e.Handled = True
  End If
End Sub