Coding, WinForms

Handling KeyPress and KeyDown Events for Datagridview

For a datagrid view control the KeyPress and KeyDown Events get fired only for non printable characters where for other controls e.g textbox etc the event gets fired for each and every key pressed. Also for the “Tab” key ,the events does not get fired for the first time. If you need these events to get fired for every single key on the keyboard for datagrid view then read further how to do it.

Add the EditingControlShowing event and type cast the cell control (is input argument for the event) to the textbox and add handlers for the textbox key events.
The Code below validates the first column values for space character.

Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
If Me.DataGridView1.CurrentCell.ColumnIndex = 0 And Not e.Control Is Nothing Then
    Dim tb As TextBox = CType(e.Control, TextBox)
    AddHandler tb.KeyDown, AddressOf TextBox_KeyDown
    AddHandler tb.KeyPress, AddressOf TextBox_KeyPress
End If
End Sub
Private Sub TextBox_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
 If  e.KeyCode = Keys.Space Then
     flag = True
 End If
End Sub
Private Sub TextBox_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
 e.Handled = flag
 flag = False
End Sub