vb.net textbox no special characters

2019-09-06 10:41发布

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.

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

1条回答
放荡不羁爱自由
2楼-- · 2019-09-06 10:57

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

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

查看更多
登录 后发表回答