在Visual Basic.NET中禁用字母和特殊字符

时间:2012-10-21 11:15:22

标签: vb.net

我是视觉基础的新手,我不确定如何禁用字母和特殊字符。

我只希望用户能够输入数字。

我正在使用此代码,我知道有一种更简单的方法可以做到这一点,所有的帮助都很受欢迎

输入字母字符和输入数字时,我收到消息框。当我输入数字时,我不想收到消息框。

Private Sub txtCustom_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtCustom.KeyDown

    If (e.KeyCode = Keys.Enter) Then

        e.SuppressKeyPress = True

        If (e.KeyCode = Keys.A Or Keys.B Or Keys.C Or Keys.D Or Keys.E Or Keys.F Or Keys.G Or Keys.H Or Keys.I Or Keys.J Or Keys.K Or Keys.L Or Keys.M Or Keys.N Or Keys.O Or Keys.P Or Keys.Q Or Keys.R Or Keys.S Or Keys.T Or Keys.U Or Keys.V Or Keys.W Or Keys.X Or Keys.Y Or Keys.Z) Then

            Beep()
            MsgBox("Please Input A Numerical Value")
            txtCustom.Text = ""

        Else

            RandNumAllow = txtCustom.Text

        End If

    End If

End Sub

3 个答案:

答案 0 :(得分:8)

请尝试使用KeyPress事件:

Private Sub TextBox1_KeyPress(sender As Object, _
                              e As KeyPressEventArgs) Handles TextBox1.KeyPress
  e.Handled = Not Char.IsNumber(e.KeyChar)
End Sub

但这不会阻止某人使用剪贴板。最好使用MaskedTextBox控件。

答案 1 :(得分:1)

很抱歉,对于迟到的响应,此代码将解决所有问题,从剪贴板复制并转换+特殊字符的数字,因为它使用TextChanged事件试试。

    Dim charactersAllowed As String = "1234567890"
      Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    Dim theText As String = TextBox1.Text
    Dim Letter As String
    Dim SelectionIndex As Integer = TextBox1.SelectionStart
    Dim Change As Integer
    For x As Integer = 0 To TextBox1.Text.Length - 1
        Letter = TextBox1.Text.Substring(x, 1)
        If charactersAllowed.Contains(Letter) = False Then
            SystemSounds.Beep.Play()
            theText = theText.Replace(Letter, String.Empty)
            Change = 1
        End If
    Next
    TextBox1.Text = theText
    TextBox1.Select(SelectionIndex - Change, 0)
End Sub

您可以将charractersAllowed的值替换为您想要允许的任何字符

答案 2 :(得分:0)

我正在寻找的代码看起来像这样。

对于您试图控制输入内容的任何文本或输入框上的按键事件

If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso 'restricts anything but number keys
    e.KeyChar <> ControlChars.Back Then 'allows use of backspace
    e.Handled = True
End If