Search code examples
vb.netdatagridvieweditmode

While in edit mode, advance to next cell and stay in edit mode for VB.NET DataGridView?


I have a DataGridView in which one column has data that the user needs to align by adding spaces. For example, the first two rows might contain:

kumbu
kuimbiu

And the user needs to be able to line up the letters that match by adding spaces. Something like this:

ku mb u
kuimbiu

Now in order to do that with the DataGridView, the user must enter edit mode in the top cell, add spaces, hit enter, re-enter edit mode in the bottom cell, and then add spaces. Our users would like to be able to, while in edit mode in the top cell, hit the down arrow and advance to the second cell while staying in edit mode, saving clicks or F2 hits.

Is there a good way to do this? I have tried trapping the down arrow key press, leaving edit mode, advancing a cell, and then entering edit mode with the grid's BeginEdit method, but this does not do what I want.

Any ideas?


Solution

  • When leaving the cell capture the edit status in a class variable. When the user presses down or enter, the next cell will begin edit mode, but only if the previous cell was in edit mode. You can add additional logic if you want it to be based upon columns.

    Private blnEditMode As Boolean = False
    Private Sub dgv_CellEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgv.CellEnter
        If blnEditMode Then
            dgv.BeginEdit(False)
        End If
    End Sub
    
    Private Sub dgv_CellLeave(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgv.CellLeave
        blnEditMode = dgv.IsCurrentCellInEditMode
    End Sub