我有一个包含8列的datagridview,我希望索引5和6仅接受数字,但是不幸的是,它也会影响其他列。这段代码有什么问题吗?
Private Sub GridJournal_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles GridJournal.EditingControlShowing
If GridJournal.CurrentCell.ColumnIndex = 5 Then
AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress
ElseIf GridJournal.CurrentCell.ColumnIndex = 6 Then
AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress
End If
End Sub
Private Sub TextBox_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
If Not (Char.IsDigit(e.KeyChar) Or e.KeyChar = "." Or Asc(e.KeyChar) = 8) Then
e.Handled = True
End If
End Sub
答案 0 :(得分:0)
您只需要一个else条件即可删除处理程序。
If GridJournal.CurrentCell.ColumnIndex = 5 Or GridJournal.CurrentCell.ColumnIndex = 6 Then
RemoveHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress
AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress
Else
RemoveHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress
End If