关于vb.net:检查文本框输入是否为数字

Checking to see if text box input is numeric

我已经对此进行了一些研究,但仍然无法使我的程序正常工作。我只需要检查文本框以查看用户输入的值是否为数字值("。"和或" / "除外)

到目前为止,我的代码,

1
2
3
4
5
6
 Private Sub Num1_KeyPress(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Num1.KeyPress
    Dim UserEntry As Boolean
    If UserEntry = IsNumeric(False) Then
        MessageBox.Show("That's not numeric!")
    End If
End Sub


我建议处理TextChanged并检查整数而不是单个字符。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Private Sub Num1_TextChanged(sender As Object, e As TextChangedEventArgs) Handles Num1.TextChanged
        If IsInputNumeric(Num1.Text) Then
            'handle numeric input
        Else
            'handle not a number
        End If
    End Sub

    Private Function IsInputNumeric(input As String) As Boolean
        If String.IsNullOrWhiteSpace(input) Then Return False
        If IsNumeric(input) Then Return True
        Dim parts() As String = input.Split("/"c)
        If parts.Length <> 2 Then Return False
        Return IsNumeric(parts(0)) AndAlso IsNumeric(parts(1))
    End Function


我认为您最好使用TextBox.KeyUp事件,它通过KeyEventArgs。试试这个:

1
2
3
4
5
6
7
8
9
10
11
Private Sub Num1_KeyUp(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles Num1.KeyUp

    Dim isDigit As Boolean = Char.IsDigit(ChrW(e.KeyValue))
    Dim isKeypadNum As Boolean = e.KeyCode >= Keys.NumPad0 And e.KeyCode <= Keys.NumPad9
    Dim isBackOrSlashOrPeriod As Boolean = (e.KeyCode = Keys.Decimal Or e.KeyCode = Keys.Oem2 Or e.KeyCode = Keys.Back Or e.KeyCode = Keys.OemPeriod)

    If Not (isDigit Or isKeypadNum Or isBackOrSlashOrPeriod) Then
        MessageBox.Show("That's not numeric!")
    End If

End Sub


在稍微切线的情况下,根据在Visual Basic中检查文本框中输入的数值的问题的最高答案,还有.TryParse方法,它被认为是比IsNumeric更好的解决方案:

The first reason is that with TryParse you also get the result of the conversion while with IsNumeric you would have to do the conversion after the check.

The second reason is that you could give to IsNumeric whatever object you want (also a Button for example) and it accepts it. You would never discover this kind of errors at compile time. Instead, with TryParse, you could only pass a string as its first parameter.


1
2
3
4
5
6
7
8
9
' Validates textboxes for numeric only keystrokes.  Hook this up to the
' PreviewTextInput of the desired textbox
Private Sub SetTextboxNumericOnly(sender As Object,
                                  e As TextCompositionEventArgs)

    Dim regex As New System.Text.RegularExpressions.Regex("[^0-9]+")
    e.Handled = regex.IsMatch(e.Text)

End Sub

请记住,您仍然需要检查文本框是否包含一个值,以防它们删除文本框的内容。此例程确保它始终是数字,因此不再需要检查。


1
2
3
4
5
Private Sub tbYear_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tbYear.KeyPress
    If e.KeyChar < Chr(48) Or e.KeyChar > Chr(57) Then
        e.KeyChar = Nothing
    End If
End Sub

我发现在textBox的LostFocus eventHandler或Form级别(例如,当用户单击"确定"按钮时。

然后您可以按照以下步骤进行验证

a)文本框是否包含"0123456789./"以外的任何字符,如果是,则为非数字

b)在出现"/"字符的地方(如果有的话)拆分文本,然后在每个子字符串上使用IsNumeric()函数。如果它们中的任何一个都不是数字,则文本也不是数字。

这确实假设您允许1/2/2,即1/4。如果不是,那么您还必须检查字符串中最多有1个" /"字符。


1
2
3
4
5
6
7
8
9
10
11
Public Function onlyNumbers(ByVal KeyChar As Char) As Boolean
    Dim allowedChars As String

    allowedChars ="0123456789./"

    If allowedChars.IndexOf(KeyChar) = -1 And (Asc(KeyChar)) <> 8 Then
        Return True
    End If

    Return False
End Function

true表示无效的字符。

在按键上您需要执行以下操作:

1
e.handled = onlyNumbers(e.keychar)