Vb.net – How to move to another column in datagridview using Enter in vb.net

datagridviewkeypressvb.net

I have search this one, and most of the answer are in C# and I have try to convert it to VB.NET and do a work around but I cannot find the right code.

What I want is when the user press Enter, it will move to the next column, if the column in that row is last, then it will go down to the second row of the first column.

Thank you.

EDIT:

If e.KeyCode = Keys.Enter Then
        e.Handled = True
        With dvJOBranch
            Dim i As Integer = .CurrentCell.ColumnIndex + 1
            .CurrentCell = .CurrentRow.Cells(i)
        End With
    End If

This code is working but for columns that are not editing, if I am editing in a columns, its not working and this is the error: Current cell cannot be set to an invisible cell.

Best Answer

this should do the trick

Private Sub DataGridView1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles DataGridView1.KeyDown
            If e.KeyCode = Keys.Enter Then
                e.SuppressKeyPress = True
                Dim iCol = DataGridView1.CurrentCell.ColumnIndex
                Dim iRow = DataGridView1.CurrentCell.RowIndex
                If iCol = DataGridView1.Columns.Count - 1 Then
                    If iRow < DataGridView1.Rows.Count - 1 Then
                        DataGridView1.CurrentCell = DataGridView1(0, iRow + 1)
                    End If
                Else
                    DataGridView1.CurrentCell = DataGridView1(iCol + 1, iRow)
                End If
            End If
        End Sub

and this will address the "edit" problem mentioned.

   Private Sub DataGridView1_CellEndEdit(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
        Dim iCol = DataGridView1.CurrentCell.ColumnIndex
        Dim iRow = DataGridView1.CurrentCell.RowIndex
        If iCol = DataGridView1.Columns.Count - 1 Then
            If iRow < DataGridView1.Rows.Count - 1 Then
                DataGridView1.CurrentCell = DataGridView1(0, iRow + 1)
            End If
        Else
            If iRow < DataGridView1.Rows.Count - 1 Then
                SendKeys.Send("{up}")
            End If
            DataGridView1.CurrentCell = DataGridView1(iCol + 1, iRow)
            End If
    End Sub