1
votes

I have used DataGridView feature in a form having 4 columns: Item Code, Description, Quantity, Price. I want when an item code is being inserted into the cell, the focus should move onto the 3rd cell of the same row i.e 3rd column(Quantity). Till here its working fine because I referred to this link.

DataGridView SetFocus after CellEndEdit

Now the Problem is that it's stuck on the 3rd cell, it's not moving to the next row first column(Item Code) when I press enter. My Code is

Private flag_cell_edited As Boolean
Private currentRow As Integer
Private currentColumn As Integer 


Private Sub DataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
        flag_cell_edited = True
        currentColumn = e.ColumnIndex
        currentRow = e.RowIndex
        MsgBox(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value)

End Sub


Private Sub DataGridView1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.SelectionChanged
        If flag_cell_edited Then
                DataGridView1.CurrentCell = DataGridView1.Rows(currentRow).Cells(2)
                flag_cell_edited = False
        End If
End Sub

I have used MsgBox to view the data inserted into cell, so that later I can store it into database.

1
Start removing that MsgBox. That line interfers with the normal flow of focus between controls. Use a simple Console.WriteLine to observe the resul in your debug window.Steve
I removed that line but still it's not working. When first time focus moves onto the 3rd cell(i.e quantity) and i insert some value and HIT enter so nothing happens and the focus remains in the same cell but when I HIT enter 2nd time it moves to the next row 3rd column(i.e quantity)Ali Muhammad

1 Answers

0
votes

When you press enter on the third cell you get the CellEndEdit event like when you end the editing in the first cell. You need to trigger the movement on the third cell only when you are on the first one

Private Sub DataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit

    if e.ColumnIndex = 0 Then
        flag_cell_edited = True
        currentColumn = e.ColumnIndex
        currentRow = e.RowIndex
    Else
        flag_cell_edited = False
    End If
End Sub


Private Sub DataGridView1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.SelectionChanged
    If flag_cell_edited Then
        DataGridView1.CurrentCell = DataGridView1.Rows(currentRow).Cells(0)
        flag_cell_edited = False
    End If
End Sub