为什么其他列也不接受 datagridview 单元格格式的字母表?

Why other columns also not accepting alphabet in datagridview cell format?

我有一个包含 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

你只需要一个 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