2

我正在开发 Windows 应用程序。我有一个表单,我正在尝试验证该表单上的文本框。

我想对文本框进行一些验证,例如文本框应该只接受 Alphabates、Didgits 和逗号。(没有其他字符,如特殊符号。)同样,当光标在该文本框中时,它应该接受 Enter 键。

我正在尝试编写代码,但有些代码无法正常工作。但它仍然采用特殊字符,如 <>/;' 我必须做出哪些改变?

这是代码...

按键按下事件

 Private Sub txtOLDBuildingName_KeyDown(sender As Object, e As KeyEventArgs) Handles txtOLDBuildingName.KeyDown

        ' Initialize the flag to false.
        nonNumberEntered = False

        ' Determine whether the keystroke is a number from the top of the keyboard. 
        If (e.KeyCode < Keys.D0 And e.KeyCode > Keys.D9) And (e.KeyCode > Keys.A And e.KeyCode < Keys.Z) Then
            nonNumberEntered = True
        End If
        'If shift key was pressed, it's not a number. 
        If Control.ModifierKeys = Keys.Shift Then
            nonNumberEntered = True
        End If


    End Sub

按键事件

  Private Sub txtOLDBuildingName_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtOLDBuildingName.KeyPress
           If nonNumberEntered = True Then
               e.Handled = True
        End If

   End Sub
4

1 回答 1

7

删除正在处理事件的子程序并将正在处理KeyDown事件的子程序替换为该子程序KeyPress

ReadOnly ValidChars As String = _
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,"

Private Sub txtOLDBuildingName_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) _
Handles txtOLDBuildingName.KeyPress

    e.Handled = Not (ValidChars.IndexOf(e.KeyChar) > -1 _
                OrElse e.KeyChar = Convert.ToChar(Keys.Back))

End Sub

更新:

这种修改更精确,它在粘贴之前比较剪贴板内容。

ReadOnly AllowedKeys As String = _
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,"

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles TextBox1.KeyPress

    Select Case e.KeyChar

        Case Convert.ToChar(Keys.Enter) ' Enter is pressed
            ' Call method here...

        Case Convert.ToChar(Keys.Back) ' Backspace is pressed
            e.Handled = False ' Delete the character

        Case Convert.ToChar(Keys.Capital Or Keys.RButton) ' CTRL+V is pressed
            ' Paste clipboard content only if contains allowed keys
            e.Handled = Not Clipboard.GetText().All(Function(c) AllowedKeys.Contains(c))

        Case Else ' Other key is pressed
            e.Handled = Not AllowedKeys.Contains(e.KeyChar)

    End Select

End Sub
于 2013-10-21T04:39:43.707 回答