Vb.net – Change editted cell in datagridview on enter (vb.net)


I have a datagridview table that is populated by using a datatable as a datasource. The datagridview has been set to edittable and I can change the values of cells but of course, the changes do not reflect in the original database table since the grid view is not directly bound. Is it possible to have the datagridview in such a way that when I press enter (when editting a cell), the focus shifts to the cell on the right (rather then selecting the row below)? This would need to keep on going until I reach the right most column, in which case the following edit cell would be the first cell in the following row.

Thanks in advance!

Best Solution

Try this:

  1. define a flag flag_edited that will be raised when an edit occurs (CellEndEdit event)

  2. define a function changeSelectionToNextCell that will undo default behavior's selection change (SelectionChanged event)

Here is a sample:

Private flag_edited As Boolean

Private Sub DataGridView1_CellEndEdit(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
    flag_edited = True
End Sub

Private Sub DataGridView1_SelectionChanged(sender As Object, e As System.EventArgs) Handles DataGridView1.SelectionChanged
End Sub

Private Sub changeSelectionToNextCell()
    If flag_edited Then
        flag_edited = False
        If DataGridView1.CurrentCell IsNot Nothing Then
            Dim row_index As Integer = DataGridView1.CurrentCell.RowIndex - 1
            Dim col_index As Integer = DataGridView1.CurrentCell.ColumnIndex + 1

            If col_index = DataGridView1.ColumnCount Then
                col_index = 0
                row_index += 1
            End If

            DataGridView1.CurrentCell = DataGridView1.Rows(row_index).Cells(col_index)
        End If
    End If
End Sub