vb.net 文本框没有特殊字符

问题描述:

我想跳过验证的一部分,只做它,这样文本框就不能有我不想要的任何东西.

I would like to skip a part of validation and just make it so the text-box can't have anything I don't want in it.

目的是允许输入退格、空格和字母:d,r,i(上下).

The intention is to allow backspaces, spaces, and letters : d,r,i (upper and lower) be entered.

如何才能不输入特殊字符,例如 {}、!、:;" 等?

How can I make it so that no special characters get entered like {}, !, :;", etc.?

Private Sub txtParty_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtParty.KeyPress
    'allows only numbers, letter, space, and backspace
    If Char.IsControl(e.KeyChar) = False And Char.IsSeparator(e.KeyChar) = False And Char.IsLetterOrDigit(e.KeyChar) = True And e.KeyChar <> "d" And e.KeyChar <> "D" And e.KeyChar <> "r" And e.KeyChar <> "R" And e.KeyChar <> "i" And e.KeyChar <> "I" Then
        e.Handled = True
    End If
End Sub

使用几个 If-Blocks 过滤数据可能更容易.

Probably easier with a couple of If-Blocks to filter the data.

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs)
                              Handles TextBox1.KeyPress
  If e.KeyChar <> ControlChars.Back AndAlso e.KeyChar <> " " Then
    If Not Char.IsLetter(e.KeyChar) OrElse
      Not "DRI".Contains(e.KeyChar.ToString.ToUpper) Then
        e.Handled = True
    End If
  End If
End Sub

当然,您仍然需要拦截 Ctrl-V 并删除 ContextMenuStrip 以防止将文本粘贴到 TextBox 中.

Of course, you would still have to intercept the Ctrl-V and remove the ContextMenuStrip to prevent pasting text into the TextBox.