问题
I'm working on a Form that contains a datagridview and textbox, I need the datagridview detect any letter of the alphabet or numbers, then select the input and send the key pressed to input.
I can not find any solution for this, thanks in advance.
回答1:
You will need to attach an event handler to the cell editing control that is receiving the data that will respond to the KeyPress event. This can be done by handling the EditingControlShowing event.
Here is some basic code that does this:
Public Class Form1
Private Sub DataGridView1_EditingControlShowing(sender As System.Object, e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
Dim c As Control
c = e.Control
AddHandler c.KeyPress, AddressOf Handle_KeyPress
End Sub
Protected Sub Handle_KeyPress(sender As Object, e As KeyPressEventArgs)
If Char.IsLetterOrDigit(e.KeyChar) Then
TextBox1.Text += e.KeyChar
e.Handled = True
End If
End Sub
End Class
There are other events that you can respond to such as KeyDown but KeyPress is generally preferred since it gives you a Char with the event args. With events like KeyDown you will have KeyCodes instead, which don't allow you to easily tell if the input was upper or lower case.
来源:https://stackoverflow.com/questions/9163644/detect-alphabetic-or-numeric-key-in-a-datagridview-control-and-send-handled-key