user2452250
user2452250

Reputation: 797

Override keydown Enter on datagridview

This question has already been asked several times but none found an answer. I need to override the Enter key on a datagridview so it does not jump to the next line but allows me to save the entered text to a database. This needs to be done on textboxcells while the user is typing into them.

Using:

Private Sub DataGridView1_mt_KeyDown(sender As Object, e As KeyEventArgs) Handles DataGridView1_mt.KeyDown

    If e.KeyCode = Keys.Enter Then
    ...

will not work as the enter Key does not fire at textbox cells. Keyup works, but its to late as the program already jumped to the next cell. Keypress has the same problem as Keydown.

Any idea about how I can detect the keypress for the Enter key and override it?

UPDATE: I can detect the Enter key if a cell is selected, but not if i am typing into a textbox. (in fact what i need is to detect when the user finished typing and presses enter.

Private Sub DataGridView1_EditingControlShowing(sender As System.Object, e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1_mt.EditingControlShowing

    Dim tb As TextBox = CType(e.Control, TextBox)
    AddHandler tb.KeyDown, AddressOf TextBox_KeyDown

End Sub

Private Sub TextBox_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
    If e.KeyCode = Keys.Enter Or e.KeyCode = Keys.Return Then

        MessageBox.Show("Success")    '''''DOES NOT WORK
    End If
    If e.KeyCode = Keys.Space Then

        MessageBox.Show("Success")    '''''WORKS
    End If
End Sub

Upvotes: 4

Views: 4955

Answers (3)

Al-3sli
Al-3sli

Reputation: 2181

Use PreviewKeyDown Event instead of KeyDown, Change your code like this :

Private Sub DataGridView1_EditingControlShowing(sender As System.Object, e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1_mt.EditingControlShowing

    Dim tb As TextBox = CType(e.Control, TextBox)
    AddHandler tb.PreviewKeyDown, AddressOf TextBox_PreviewKeyDown

End Sub

Private Sub TextBox_PreviewKeyDown(ByVal sender As Object, ByVal e As PreviewKeyDownEventArgs)
    If e.KeyCode = Keys.Enter Or e.KeyCode = Keys.Return Then

        MessageBox.Show("Success")    '''''WILL WORK
    End If
    If e.KeyCode = Keys.Space Then

        MessageBox.Show("Success")    '''''WORKS
    End If
End Sub

This will catch enter click even if cell in edit mode.

Upvotes: 2

King of kings
King of kings

Reputation: 695

You have written as e.KeyCode=Keys.Return . Change into e.KeyValue = Keys.Return . It will work

Upvotes: 0

King of kings
King of kings

Reputation: 695

Change the code like this, It works.

    If e.KeyCode = Keys.Down Then
        'code
    End If

Upvotes: 0

Related Questions