1

I've done some research on this and still cannot get my program to work. I simply need to check the text box to see if the user input is a numeric value, or not (with the exception of a "." and or "/")

My code so far,

 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
Sam
  • 7,252
  • 16
  • 46
  • 65
Matt
  • 191
  • 2
  • 4
  • 14

7 Answers7

8

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
Trevor Tubbs
  • 2,097
  • 16
  • 18
  • Thank you Trevor for your response! It's more detailed than AbZy's, I chose his as the answer for this (specific) question, but your solution is more accurate and I appreciate your time to help me solve this problem, for that you deserve many upvotes! – Matt Mar 15 '13 at 04:04
3

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
Abdusalam Ben Haj
  • 5,343
  • 5
  • 31
  • 45
  • That does not seem to work, it only omits the message box for the first "space" in the text box, letter or number and then gives the message box for every input after that be it a number, letter, forward slash or backspace. – Matt Mar 15 '13 at 01:37
  • Your function operates well! One issue I was aware of was the omission of a keypad? Does the keypad fall under a different classification? Because I get the message box when I enter numerical values via the keypad as well. – Matt Mar 15 '13 at 02:03
  • 1
    @Matt I fixed that now. And yeah, they have different key codes. – Abdusalam Ben Haj Mar 15 '13 at 02:21
0
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)
Esselans
  • 1,540
  • 2
  • 24
  • 44
0

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.

DeanOC
  • 7,142
  • 6
  • 42
  • 56
0
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
andrewsi
  • 10,807
  • 132
  • 35
  • 51
0
' 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.

0

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.

Community
  • 1
  • 1
rbassett
  • 383
  • 3
  • 17