none
Numeric textbox validation in Visual Basic.net 2010 (Windows 7)

    Question

  • Yes, I'm fairly new to this but I've been searching for solutions and nothing has worked. I simply want to have a user enter a number, e.g., 3.5, into a textbox and then click a button to process it. If nothing or a char or string is entered, I want to inform them to enter the number and clear the box. From a suggestion somewhere it was said to simply use validating.  I thought e.handled was correct by that doesn't show up as an option.  It works if the input is a number. If not, the messagebox shows and closes on OK but I can't do anything else. Any click (even to 'X' the window) anywhere brings up the messagebox. This is basically what I've tried:

    Private Sub txtKidsAnswer_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles txtOddsAnswer.Validating

     

     If IsNumeric(txtKidsAnswer.Text) Then

         Exit Sub

     Else

                MessageBox.Show("Please enter a numeric value between 1.0 and 20.0")

                txtKidsAnswer.text = ””

                 e.Cancel = True

                Exit Sub

     End If

     End Sub

    I know, don't quit your day job. I guess I have two questions: What am I doing wrong? Why isn't e.handled allowed at this point?

    Thursday, July 21, 2011 12:15 PM

Answers

  • Clyde,

    Here's one way that I think will work for you. Please be sure that you include an ErrorProvider.

     


    CODE SNIPPET

      Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    
        Button1.Enabled = False
    
      End Sub
    
    
    
      Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    
        If TextBox1.Text = String.Empty Then
          Button1.Enabled = False
          ErrorProvider1.Clear()
        Else
          Button1.Enabled = True
        End If
    
      End Sub
    
    
    
      Private Sub TextBox1_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
    
        Dim testDouble As Double = 0
    
        If Not Double.TryParse(TextBox1.Text, testDouble) Then
          ErrorProvider1.SetError(TextBox1, "Your entry is not valid.")
          TextBox1.SelectAll()
          e.Cancel = True
        Else
          If testDouble < 1 Or testDouble > 20 Then
            ErrorProvider1.SetError(TextBox1, "The value must be between 1.0 and 20.0")
            TextBox1.SelectAll()
            e.Cancel = True
          Else
            ErrorProvider1.Clear()
          End If
        End If
    
      End Sub
    
    
    
      Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
        MessageBox.Show("Do Something!")
    
      End Sub
    


     

     

     

     

    Even though they CAN click the button even when they see the error, the button's click event won't run.

    I hope that helps. :)

    • Marked as answer by Liliane Teng Thursday, July 28, 2011 2:45 PM
    Sunday, July 24, 2011 6:27 PM
  • Hello clyde12345,

    can handle the Validated event of the textbox control and make the text a number caoversione by TryParse to avoid a runtime exception if you enter a character or something that is not a number, see example below.

     Private Sub TextBox1_Validated(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.Validated
    
     Dim number As Double = 0
    
    
    
     If Double.TryParse(Me.TextBox1.Text, number) Then
    
      'your code
    
     Else
    
      MessageBox.Show("Insert a number")
    
      Me.TextBox1.Clear()
    
     End If
    
     End Sub
    
    
    
    

    Bye


     http://community.visual-basic.it/carmelolamonica/

    • Marked as answer by Liliane Teng Thursday, July 28, 2011 2:50 PM
    Thursday, July 21, 2011 12:29 PM
  • Hi
    
    and what about the event keypress?
    
    Private Sub txtKidsAnswer_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtKidsAnswer.KeyPress
    
        If (Not Char.IsLetter(e.KeyChar) And e.KeyChar <> " " And e.KeyChar <> Microsoft.VisualBasic.Chr(Keys.Back)) Then
    
          e.Handled = True
    else
    ' put ur treatment
        End If
    
    
      End Sub
    

    Hope it helps
    Best Regards...Please mark as answer if my post is helpful
    Thursday, July 21, 2011 12:27 PM
  • Hello clyde12345,

    Thanks to both of you. I'm going to put the same reply because I appreciate both quick responses and both were helpful. When I did the TryParse, a couple of other issues popped up but I know they're because of other stuff in my code. I didn't get to the keypress until today. However, when I went to bed the other night, I had a thought as soon as I hit the pillow: "why not just put a holder string in the click event of my answer button?" So I got up and tried that. Something like (pseudo code):

     

    btnANswer Click event

    dim holder as string

    holder = textbox.text

    If isNumeric(holder)

    check to see if answer is correct

    else

    clear the textbox

    messagebox(" not a number")

    ...

    It worked. It might not be elegant.

     

    However, I just tried the keypress method on a little code snippet at my girlfriend's house and it worked great. So I'm going to add that to my code as well. I have some ideas on using the tryParse too in my code.

     

    Thanks very much. I learned a lot from these ideas.


    kg

    your system already operates a possible exception at runtime, so if you let this solution does not need TryParse, and if what you mean, but please excuse me if I misunderstood your answer.

     

     Private Sub TextBox1_Validated(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.Validated
    
      Dim holder As String = Me.TextBox1.Text
    
      If IsNumeric(holder) Then
       'yourcode
      Else
       MessageBox.Show(" not a number")
       Me.TextBox1.Clear()
      End If
     End Sub
    

    Bye

     

     


     http://community.visual-basic.it/carmelolamonica/


    • Marked as answer by Liliane Teng Thursday, July 28, 2011 2:55 PM
    Sunday, July 24, 2011 4:58 PM
  • Clyde,

    Be aware that the IsNumeric and the TryParse both check if a number is entered. However, they don't check if there are only numbers are entered.

    A Hex number or a decimal number with an Exponent and many more will be accepted, just because those are valid number formats.

    If you want only numbers entered (plus minus, comma seperator and thousand seperator) than you can do something like

      Private Sub txtKidsAnswer_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles KidsAnswer.KeyPress
        If (Not Char.IsNumber(e.KeyChar) AndAlso Not ".,-".Contains(e.KeyChar) AndAlso Not e.KeyChar = Microsoft.VisualBasic.Chr(Keys.Back)) Then
          e.Handled = True
        End If
      End Sub
    



    Success
    Cor
    • Marked as answer by Liliane Teng Thursday, July 28, 2011 2:55 PM
    Sunday, July 24, 2011 6:04 PM

All replies

  • Hi
    
    and what about the event keypress?
    
    Private Sub txtKidsAnswer_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtKidsAnswer.KeyPress
    
        If (Not Char.IsLetter(e.KeyChar) And e.KeyChar <> " " And e.KeyChar <> Microsoft.VisualBasic.Chr(Keys.Back)) Then
    
          e.Handled = True
    else
    ' put ur treatment
        End If
    
    
      End Sub
    

    Hope it helps
    Best Regards...Please mark as answer if my post is helpful
    Thursday, July 21, 2011 12:27 PM
  • Hello clyde12345,

    can handle the Validated event of the textbox control and make the text a number caoversione by TryParse to avoid a runtime exception if you enter a character or something that is not a number, see example below.

     Private Sub TextBox1_Validated(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.Validated
    
     Dim number As Double = 0
    
    
    
     If Double.TryParse(Me.TextBox1.Text, number) Then
    
      'your code
    
     Else
    
      MessageBox.Show("Insert a number")
    
      Me.TextBox1.Clear()
    
     End If
    
     End Sub
    
    
    
    

    Bye


     http://community.visual-basic.it/carmelolamonica/

    • Marked as answer by Liliane Teng Thursday, July 28, 2011 2:50 PM
    Thursday, July 21, 2011 12:29 PM
  • Hello clyde12345,

    I know, don't quit your day job. I guess I have two questions: What am I doing wrong? Why isn't e.handled allowed at this point?


    e.handled find it only if you use the keypress event, up, down, to prevent the user to enter in your case something other than a number, see example of YosrJ.

    Bye


     http://community.visual-basic.it/carmelolamonica/
    Thursday, July 21, 2011 12:33 PM
  • Thanks to both of you. I'm going to put the same reply because I appreciate both quick responses and both were helpful. When I did the TryParse, a couple of other issues popped up but I know they're because of other stuff in my code. I didn't get to the keypress until today. However, when I went to bed the other night, I had a thought as soon as I hit the pillow: "why not just put a holder string in the click event of my answer button?"  So I got up and tried that. Something like (pseudo code):

     

    btnANswer Click event

    dim holder as string

    holder = textbox.text

    If isNumeric(holder)

    check to see if answer is correct

    else

    clear the textbox

    messagebox(" not a number")

    ...

    It worked. It might not be elegant.

     

    However, I just tried the keypress method on a little code snippet at my girlfriend's house and it worked great. So I'm going to add that to my code as well. I have some ideas on using the tryParse too in my code.

     

    Thanks very much. I learned a lot from these ideas.

     


    kg
    Sunday, July 24, 2011 4:25 PM
  • Thanks to both of you. I'm going to put the same reply because I appreciate both quick responses and both were helpful. When I did the TryParse, a couple of other issues popped up but I know they're because of other stuff in my code. I didn't get to the keypress until today. However, when I went to bed the other night, I had a thought as soon as I hit the pillow: "why not just put a holder string in the click event of my answer button?" So I got up and tried that. Something like (pseudo code):

     

    btnANswer Click event

    dim holder as string

    holder = textbox.text

    If isNumeric(holder)

    check to see if answer is correct

    else

    clear the textbox

    messagebox(" not a number")

    ...

    It worked. It might not be elegant.

     

    However, I just tried the keypress method on a little code snippet at my girlfriend's house and it worked great. So I'm going to add that to my code as well. I have some ideas on using the tryParse too in my code.

     

    Thanks very much. I learned a lot from these ideas.


    kg
    Sunday, July 24, 2011 4:25 PM
  • Hello clyde12345,

    Thanks to both of you. I'm going to put the same reply because I appreciate both quick responses and both were helpful. When I did the TryParse, a couple of other issues popped up but I know they're because of other stuff in my code. I didn't get to the keypress until today. However, when I went to bed the other night, I had a thought as soon as I hit the pillow: "why not just put a holder string in the click event of my answer button?" So I got up and tried that. Something like (pseudo code):

     

    btnANswer Click event

    dim holder as string

    holder = textbox.text

    If isNumeric(holder)

    check to see if answer is correct

    else

    clear the textbox

    messagebox(" not a number")

    ...

    It worked. It might not be elegant.

     

    However, I just tried the keypress method on a little code snippet at my girlfriend's house and it worked great. So I'm going to add that to my code as well. I have some ideas on using the tryParse too in my code.

     

    Thanks very much. I learned a lot from these ideas.


    kg

    your system already operates a possible exception at runtime, so if you let this solution does not need TryParse, and if what you mean, but please excuse me if I misunderstood your answer.

     

     Private Sub TextBox1_Validated(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.Validated
    
      Dim holder As String = Me.TextBox1.Text
    
      If IsNumeric(holder) Then
       'yourcode
      Else
       MessageBox.Show(" not a number")
       Me.TextBox1.Clear()
      End If
     End Sub
    

    Bye

     

     


     http://community.visual-basic.it/carmelolamonica/


    • Marked as answer by Liliane Teng Thursday, July 28, 2011 2:55 PM
    Sunday, July 24, 2011 4:58 PM
  • Clyde,

    Be aware that the IsNumeric and the TryParse both check if a number is entered. However, they don't check if there are only numbers are entered.

    A Hex number or a decimal number with an Exponent and many more will be accepted, just because those are valid number formats.

    If you want only numbers entered (plus minus, comma seperator and thousand seperator) than you can do something like

      Private Sub txtKidsAnswer_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles KidsAnswer.KeyPress
        If (Not Char.IsNumber(e.KeyChar) AndAlso Not ".,-".Contains(e.KeyChar) AndAlso Not e.KeyChar = Microsoft.VisualBasic.Chr(Keys.Back)) Then
          e.Handled = True
        End If
      End Sub
    



    Success
    Cor
    • Marked as answer by Liliane Teng Thursday, July 28, 2011 2:55 PM
    Sunday, July 24, 2011 6:04 PM
  • Clyde,

    Here's one way that I think will work for you. Please be sure that you include an ErrorProvider.

     


    CODE SNIPPET

      Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    
        Button1.Enabled = False
    
      End Sub
    
    
    
      Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    
        If TextBox1.Text = String.Empty Then
          Button1.Enabled = False
          ErrorProvider1.Clear()
        Else
          Button1.Enabled = True
        End If
    
      End Sub
    
    
    
      Private Sub TextBox1_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
    
        Dim testDouble As Double = 0
    
        If Not Double.TryParse(TextBox1.Text, testDouble) Then
          ErrorProvider1.SetError(TextBox1, "Your entry is not valid.")
          TextBox1.SelectAll()
          e.Cancel = True
        Else
          If testDouble < 1 Or testDouble > 20 Then
            ErrorProvider1.SetError(TextBox1, "The value must be between 1.0 and 20.0")
            TextBox1.SelectAll()
            e.Cancel = True
          Else
            ErrorProvider1.Clear()
          End If
        End If
    
      End Sub
    
    
    
      Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
        MessageBox.Show("Do Something!")
    
      End Sub
    


     

     

     

     

    Even though they CAN click the button even when they see the error, the button's click event won't run.

    I hope that helps. :)

    • Marked as answer by Liliane Teng Thursday, July 28, 2011 2:45 PM
    Sunday, July 24, 2011 6:27 PM
  • Thanks, works perfect. I did:

     

    If IsNumeric(num1.Text) And IsNumeric(num2.Text) Then
           num1 = num1.Text
           num2 = num2.Text
    Else
           MessageBox.Show("Please, Enter Numbers!!!")
    End If
    


    Thanks again

    Great domain to check out Webface.com

     

    • Proposed as answer by Anand N Shah Tuesday, February 12, 2013 9:43 AM
    • Unproposed as answer by Anand N Shah Tuesday, February 12, 2013 9:43 AM
    • Proposed as answer by Sameer Bhagwat Monday, May 06, 2013 7:31 PM
    • Unproposed as answer by Sameer Bhagwat Monday, May 06, 2013 7:31 PM
    Thursday, October 13, 2011 4:26 AM