简体   繁体   中英

vb.net DataGridView how to stay in current cell when I press enter or tab key?

Now I'm making code that after I change a text in a cell and then, when I press enter key or tab key, then the currente cell stay in the same cell which I modified. I searched in here about that ( Link ) But it dosen' work for me. What did I make a mistake in that?

Public row1, col1 As Integer
Public selectedPart1 As String
Private Sub DataGridView1_KeyDown(sender As Object, e As KeyEventArgs) Handles DataGridView1.KeyDown

    row1 = DataGridView1.CurrentCell.RowIndex
    col1 = DataGridView1.CurrentCell.ColumnIndex    
    
    selectedPart1 = DataGridView1(0, row1).Value.ToString

    If e.KeyCode = Keys.Enter Or e.KeyCode = Keys.Tab Then
        MsgBox("ok")
        DataGridView1.CurrentCell = DataGridView1(col1, row1)
        e.SuppressKeyPress = True
    End If

End Sub

to disable Tab Key you can set StandardTab property to True:

DataGridView1.StandardTab = True

to disable Enter key after edit use events CellEndEdit and SelectionChanged

Private currentRow, currentCell As Integer
Private resetRow As Boolean = False

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

Private Sub DataGridView1_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
    resetRow = True
    currentRow = e.RowIndex
    currentCell = e.ColumnIndex
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM