Checking to see if text box input is numeric

大憨熊 提交于 2019-12-01 12:46:35

I think you better be using TextBox.KeyUp event, it passes the KeyEventArgs. Try this :

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

I recommend handling TextChanged and checking the whole number instead of a single character.

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
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 means an invalid char.

On keypress you need to do:

e.handled = onlyNumbers(e.keychar)

I find that this sort of validation is much easier to do either in the textBox's LostFocus eventHandler, or at the Form level, e.g. when the user clicks the OK button.

Then you can do your validation as follows

a) Does the textbox contain any chars outside of "0123456789./" If so then non-numeric

b) Split the text wherever the "/" character appears (if any), and then use the IsNumeric() function on each substring. If any of them are not numeric, then the text is not numeric.

This does assume that you are allowing 1/2/2, .i.e. 1/4. If not then you also have to check that there is a max of 1 "/" chars in your string.

Cesar Alpendre
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
' 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

Keep in mind that you still need to check if the textbox contains a value in case they delete the contents of the textbox. This routine ensures it is always numeric and so there is no longer a need to check.

rbassett

On a slight tangent, according to the top answer to the question checking for numeric value entered in text box in visual basic, there is also the method .TryParse which is considered a better solution than 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!