DataGridView是.net2.0的一个新增数据控件,功能比DataGrid增强了很多,但是并没有CellKeyPress事件来限制文本列的输入。我利用一个新增的事件EditConTrolShowing解决这个问题。
Private EditingControl As DataGridViewTextBoxEditingControl
Private Sub datagridview1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles datagridview1.EditingControlShowing
EditingControl = CType(e.Control, DataGridViewTextBoxEditingControl)
AddHandler EditingControl.KeyPress, AddressOf editingcontrol_Keypress
End Sub
Public Sub editingcontrol_Keypress(ByVal sender As System.Object, ByVal e As KeyPressEventArgs)
‘写上处理语句
End Sub
Private Sub datagridview1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles datagridview1.CellEndEdit
RemoveHandler EditingControl.KeyPress, AddressOf editingcontrol_Keypress
End Sub
这样就可以解决限制输入的问题,以此类推,很多其他问题都可以通过这个方式解决。
Private Sub datagridview1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles datagridview1.EditingControlShowing
EditingControl = CType(e.Control, DataGridViewTextBoxEditingControl)
AddHandler EditingControl.KeyPress, AddressOf editingcontrol_Keypress
End Sub
Public Sub editingcontrol_Keypress(ByVal sender As System.Object, ByVal e As KeyPressEventArgs)
‘写上处理语句
End Sub
Private Sub datagridview1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles datagridview1.CellEndEdit
RemoveHandler EditingControl.KeyPress, AddressOf editingcontrol_Keypress
End Sub