如何使用 vb.net 防止数据网格视图中出现特殊字符



我有一个使用datagridview的Windows表单 vb.net 程序。我正在尝试找到一种方法来防止用户在我的数据网格视图中输入特殊字符(例如 $,@,!,#,%,^,&)。当用户输入一个特殊字符时,我会出现一个适当的消息框来解释他们的错误,然后我为他们提供一个默认值。除了防止特殊字符或符号的方法外,我什么都有效。我认为这样的事情必须起作用,但我似乎找不到任何方法来阻止这种进入:

 If (columnindex = 0) Then 'checking value for column 1 only
            Dim cellString = DataGridView1.Rows(rowindex).Cells(columnindex).value
            If cellString String.IsSymbol(cellString) = true Then
                    MessageBox.Show("Special Characters Not Allowed")
                End If
                DataGridView1.Rows(rowindex).Cells(columnindex).value = "Default Value"
                Exit Sub
            End If
可以使用

EditingControlShowing 事件为输入框注册KeyPress函数。

Private Sub YourDataGridView_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles YourDataGridView.EditingControlShowing
    Try
        RemoveHandler e.Control.KeyPress, AddressOf YourFunctionToPreventSpecialCharacters
    Catch ex As Exception
    End Try
    If Me.dgvTableViewer.CurrentCell.ColumnIndex = YourDataGridView.Columns("YourColumn").Index Then
        AddHandler e.Control.KeyPress, AddressOf YourFunctionToPreventSpecialCharacters
    End If
End Sub

尝试将其放入 DataGridView 的键下事件中:

Private Sub DataGridView1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles DataGridView1.KeyDown
    Select Case e.KeyCode
        Case Keys.D0 To Keys.D9 And e.Shift
            MsgBox("NOPE.")
            e.SuppressKeyPress = True
    End Select
End Sub

这基本上检查按键是否来自计算机上的 0-9 键,以及您是否持有SHIFT键。如果是,则显示消息框并禁止按键。这会阻止键盘的 0-9 班次!@#$%^&*()上的字符。您可以像这样编辑它

Case Keys.A
    e.Suppress ...
    Msgbox ... etc

最新更新