覆盖keydown在datagridview上输入

时间:2014-04-04 08:02:45

标签: vb.net datagridview keypress override

This question has already been asked several times but none found an answer. 我需要覆盖datagridview上的Enter键,这样它就不会跳转到下一行,而是允许我将输入的文本保存到数据库中。当用户输入文本框时,这需要在textboxcells上完成。

使用:

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

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

将无效,因为输入键不会在文本框单元格中触发。 Keyup可以工作,但是由于程序已经跳到下一个单元格,所以它已经很晚了。 Keypress和Keydown有同样的问题。

我是否知道如何检测Enter键的按键并覆盖它?

更新: 如果选择了一个单元格,我可以检测到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

3 个答案:

答案 0 :(得分:2)

使用PreviewKeyDown事件代替KeyDown,更改代码如下:

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

即使单元格处于编辑模式,也会捕获输入点击。

答案 1 :(得分:0)

像这样更改代码, 它有效。

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

答案 2 :(得分:0)

你写的是 e.KeyCode=Keys.Return。  变成  e.KeyValue = Keys.Return。 它会起作用