I have a datagridview with 8 columns and I want the index 5 and 6 to accept numbers only, but unfortunately it also affects the other columns. is there something wrong with this code?
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
you just need an else condition to remove your handler.
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