dcsimg
Results 1 to 12 of 12

Thread: FormatException while reading Integer from TextBox

  1. #1

    Thread Starter
    New Member
    Join Date
    Feb 2015
    Posts
    11

    FormatException while reading Integer from TextBox

    Hey everybody,

    I'm finishing up an assignment and I'm coming across an error. It's a simple math app which reads in two integers in a number range, an operator and an answer entered in by the user, then verifies the answer. I had this working perfectly when I was generating random numbers just to test the verify button, but the user has to enter the integers and be prompted with an error if they are outside the range and that's where I'm getting the exception

    Here's what it looks like: http://imgur.com/qqBvH3P



    Current code:
    Code:
    Public Class Form1
    
        'Creating a random object
        Dim randomObject As New Random()
        'Creating the correct and incorrect counters
        Dim correctCounter, incorrectCounter As Integer
    
        'If the add button is checked, display the addition symbol
        Private Sub addRadioButton_CheckedChanged(sender As Object, e As EventArgs) Handles addRadioButton.CheckedChanged
            operatorBox.Text = "+"
        End Sub
    
        'If the subtract button is checked, display the subtraction symbol
        Private Sub subtractRadioButton_CheckedChanged(sender As Object, e As EventArgs) Handles subtractRadioButton.CheckedChanged
            operatorBox.Text = "-"
        End Sub
    
        'If the multiply button is checked, display the multiplication symbol
        Private Sub multiplyRadioButton_CheckedChanged(sender As Object, e As EventArgs) Handles multiplyRadioButton.CheckedChanged
            operatorBox.Text = "x"
        End Sub
    
        'Checking to make sure the level 1 numbers are in between 1 and 10
        Private Sub level1RadioButton_CheckedChanged(sender As Object, e As EventArgs) Handles level1RadioButton.CheckedChanged
            Dim intNum1 As Integer
            Dim intNum2 As Integer
    
            intNum1 = Integer.Parse(firstBox.Text)
            intNum2 = Integer.Parse(secondBox.Text)
    
            'Creating an error message if the numbers are outside the number range
            If intNum1 < 1 Or intNum1 > 10 Then
                MessageBox.Show("Error! Please enter a number in the range of 1-10!")
            End If
    
            If intNum2 < 1 Or intNum2 > 10 Then
                MessageBox.Show("Error! Please enter a number in the range of 1-10!")
            End If
    
        End Sub
    
        'Checking to make sure the level 2 numbers are in between 1 and 1000
        Private Sub level2RadioButton_CheckedChanged(sender As Object, e As EventArgs) Handles level2RadioButton.CheckedChanged
            Dim intNum1 As Integer
            Dim intNum2 As Integer
    
            intNum1 = Integer.Parse(firstBox.Text)
            intNum2 = Integer.Parse(secondBox.Text)
    
            If intNum1 < 1 Or intNum1 > 1000 Then
                MessageBox.Show("Error! Please enter anumber in the range of 1-1000!")
            End If
    
            If intNum2 < 1 Or intNum2 > 1000 Then
                MessageBox.Show("Error! Please enter a number in the range of 1-1000!")
            End If
    
        End Sub
    
        'Clear both textBoxes when the user clicks the Clear button
        Private Sub clearButton_Click(sender As Object, e As EventArgs) Handles clearButton.Click
            firstBox.Text = ""
            secondBox.Text = ""
            answerBox.Text = ""
        End Sub
    
        'Checking the answers and creating the variables to hold into the correct and incorrect text boxes
        Private Sub verifyButton_Click(sender As Object, e As EventArgs) Handles verifyButton.Click
            Dim intNum1 As Integer
            Dim intNum2 As Integer
    
            intNum1 = Integer.Parse(firstBox.Text)
            intNum2 = Integer.Parse(secondBox.Text)
    
            If operatorBox.Text = "+" Then
                If answerBox.Text = intNum1 + intNum2 Then
                    correctCounter += 1
                    correctTextBox.Text = correctCounter
    
                Else
                    incorrectCounter += 1
                    incorrectTextBox.Text = incorrectCounter
                End If
            End If
    
            If operatorBox.Text = "-" Then
                If answerBox.Text = intNum1 - intNum2 Then
                    correctCounter += 1
                    correctTextBox.Text = correctCounter
    
                Else
                    incorrectCounter += 1
                    incorrectTextBox.Text = incorrectCounter
                End If
            End If
    
            If operatorBox.Text = "x" Then
                If answerBox.Text = intNum1 * intNum2 Then
                    correctCounter += 1
                    correctTextBox.Text = correctCounter
    
                Else
                    incorrectCounter += 1
                    incorrectTextBox.Text = incorrectCounter
                End If
            End If
    
        End Sub
    
        'If the user hits the Exit button, the program closes
        Private Sub exitButton_Click(sender As Object, e As EventArgs) Handles exitButton.Click
            Me.Close()
        End Sub
    End Class
    My exception is coming from these subclasses:
    Code:
    Private Sub level1RadioButton_CheckedChanged(sender As Object, e As EventArgs) Handles level1RadioButton.CheckedChanged
            Dim intNum1 As Integer
            Dim intNum2 As Integer
    
            intNum1 = Integer.Parse(firstBox.Text)
            intNum2 = Integer.Parse(secondBox.Text)
    
            'Creating an error message if the numbers are outside the number range
            If intNum1 < 1 Or intNum1 > 10 Then
                MessageBox.Show("Error! Please enter a number in the range of 1-10!")
            End If
    
            If intNum2 < 1 Or intNum2 > 10 Then
                MessageBox.Show("Error! Please enter a number in the range of 1-10!")
            End If
    
        End Sub
    
        'Checking to make sure the level 2 numbers are in between 1 and 1000
        Private Sub level2RadioButton_CheckedChanged(sender As Object, e As EventArgs) Handles level2RadioButton.CheckedChanged
            Dim intNum1 As Integer
            Dim intNum2 As Integer
    
            intNum1 = Integer.Parse(firstBox.Text)
            intNum2 = Integer.Parse(secondBox.Text)
    
            If intNum1 < 1 Or intNum1 > 1000 Then
                MessageBox.Show("Error! Please enter anumber in the range of 1-1000!")
            End If
    
            If intNum2 < 1 Or intNum2 > 1000 Then
                MessageBox.Show("Error! Please enter a number in the range of 1-1000!")
            End If
    
        End Sub
    I'm trying to parse the textBoxes to check if they are integers, then to prompt an error message to the user if they are outside the number range. I thought I was doing this correctly but apparently not, any guidance here would be great!

  2. #2
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    9,569

    Re: FormatException while reading Integer from TextBox

    You're using the wrong control. The TextBox control is used to take in String data where as the NumericUpDown, aka - nud, control is used to take in Numeric data. The nud has a Minimum and a Maximum property to allow for a range of accepted numbers.

  3. #3
    Hyperactive Member
    Join Date
    Mar 2012
    Posts
    311

    Re: FormatException while reading Integer from TextBox

    Although I agree with dday9 about using the NUD control, I'm not sure whether those are allowed for this assignment, in which case you'll need to know why your code is throwing that exception. For this particular exception, it is saying that one of the TextBoxes had some String that was not in the format of an integer... What did you actually type in? Were you trying to enter in an Integer > 1000 and added commas (eg "1,234")? Because those commas would cause that type of exception to be thrown...

  4. #4
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    34,902

    Re: FormatException while reading Integer from TextBox

    Leaving the textbox empty would also cause the exception to be thrown. Even a space would cause the exception.

    You should always use .TryParse rather than .Parse when converting strings that are entered by the user, because you can never trust the user. .TryParse works differently than .Parse, though, because it returns True or False to indicate whether or not the conversion was successful. Therefore, one of your coversions looks like this:
    Code:
    If Integer.TryParse(firstBox.Text, intNum1)
     'It worked, and intNum1 holds the converted value.
    Else
     'If failed, and intNum1 holds whatever it held before (in this case, zero).
    End If
    My usual boring signature: Nothing

  5. #5

    Thread Starter
    New Member
    Join Date
    Feb 2015
    Posts
    11

    Re: FormatException while reading Integer from TextBox

    Quote Originally Posted by Pyth007 View Post
    Although I agree with dday9 about using the NUD control, I'm not sure whether those are allowed for this assignment, in which case you'll need to know why your code is throwing that exception. For this particular exception, it is saying that one of the TextBoxes had some String that was not in the format of an integer... What did you actually type in? Were you trying to enter in an Integer > 1000 and added commas (eg "1,234")? Because those commas would cause that type of exception to be thrown...
    I didn't even get the chance to enter anything into either textBox. I'm getting that exception after I click Start and before the window even opens up.

  6. #6
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    34,902

    Re: FormatException while reading Integer from TextBox

    Yeah, if you put a breakpoint in the CheckChanged method, you'll find that the event is being raised when the controls themselves are created. At that point, the textboxes are empty, which will cause the same exception. The reason for this is that controls are just like every other object, and they are set to their intial properties in the InitializeComponents method. Setting the property triggers the event.

    There are several possible solutions. Using TryParse rather than Parse would prevent the exception from happening, but the deeper question is whether or not you really want that work done in CheckChanged. There's nothing to prevent the user from clicking on the radiobuttons and triggering the event before they ever enter any text. The code you have in the check changed events is validation code that makes sure that the user entered reasonable values. That isn't normally found in CheckChanged events, partly because you'd want to be able to check it again if they got it wrong the first time. By having it in CheckChanged, you'd have to keep changing the radiobutton selection to re-validate the information.

    Most likely, there should be buttons that are clicked to perform the validation (maybe only one, maybe two).
    My usual boring signature: Nothing

  7. #7

    Thread Starter
    New Member
    Join Date
    Feb 2015
    Posts
    11

    Re: FormatException while reading Integer from TextBox

    I did think what I was declaring inside the CheckChanged was too much work for that event, so I edited my Verify button click to this:

    Code:
     If operatorBox.Text = "+" Then
    
                If intNum1 < 0 Or intNum1 > 10 Or intNum2 < 0 Or intNum2 > 10 Then
    
                    MessageBox.Show("Error! Enter numbers in the range of 1-10!")
    
                ElseIf intNum1 > -1 Or intNum1 < 11 Or intNum2 > -1 Or intNum2 < 11 Then
    
                    If answerBox.Text = intNum1 + intNum2 Then
                        correctCounter += 1
                        correctTextBox.Text = correctCounter
    
                    Else
                        incorrectCounter += 1
                        incorrectTextBox.Text = incorrectCounter
                    End If
                End If
            End If
    So on and so forth for each separate operator. This works, however I tried to put a 'While level1RadioButton.Checked' loop over all of the operators for level 1 (1-10) it freezes when I hit the Verify button. What's the reason for this? I wanted to do something similar for the level 2 (1-1000) and basically just copy and paste my code from level 1 while editing the parameters of the inputs and wrap that into a 'While level2RadioButton.Checked' loop but apparently I'm mistaken on that too.

  8. #8
    Bad man! ident's Avatar
    Join Date
    Mar 2009
    Location
    Cambridge
    Posts
    5,335

    Re: FormatException while reading Integer from TextBox

    As already mentioned why are you not using a numericupdown control?

  9. #9

    Thread Starter
    New Member
    Join Date
    Feb 2015
    Posts
    11

    Re: FormatException while reading Integer from TextBox

    Quote Originally Posted by ident View Post
    As already mentioned why are you not using a numericupdown control?
    I'm very aware that it would be much easier with one, but we have yet to "learn" about them and they aren't allowed in this project unfortunately

  10. #10
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    34,902

    Re: FormatException while reading Integer from TextBox

    The reason is probably the loop. If it really is, as you say, "While level1RadioButton.Checked" then the loop will never end as long as the radiobutton is checked, and you won't be able to uncheck it while the loop is running. It is right to move the code to the Verify button, but a loop doesn't make any sense to me. Show us the whole method in that verify button if you'd like.
    My usual boring signature: Nothing

  11. #11

    Thread Starter
    New Member
    Join Date
    Feb 2015
    Posts
    11

    Re: FormatException while reading Integer from TextBox

    Here's the source code for my Verify Answer button:

    Code:
    Private Sub verifyButton_Click(sender As Object, e As EventArgs) Handles verifyButton.Click
            Dim intNum1 As Integer
            Dim intNum2 As Integer
    
            intNum1 = Integer.Parse(firstBox.Text)
            intNum2 = Integer.Parse(secondBox.Text)
    
            'Check to see if the level 1 button is pressed
            If level1RadioButton.Checked Then
    
                If operatorBox.Text = "+" Then
    
                    If intNum1 < 0 Or intNum1 > 10 Or intNum2 < 0 Or intNum2 > 10 Then
    
                        MessageBox.Show("Error! Enter numbers in the range of 1-10!")
    
                    ElseIf intNum1 > -1 Or intNum1 < 11 Or intNum2 > -1 Or intNum2 < 11 Then
    
                        If answerBox.Text = intNum1 + intNum2 Then
                            correctCounter += 1
                            correctTextBox.Text = correctCounter
    
                        Else
                            incorrectCounter += 1
                            incorrectTextBox.Text = incorrectCounter
                        End If
                    End If
                End If
    
                If operatorBox.Text = "-" Then
    
                    If intNum1 < 0 Or intNum1 > 10 Or intNum2 < 0 Or intNum2 > 10 Then
    
                        MessageBox.Show("Error! Enter numbers in the range of 1-10!")
    
                    ElseIf intNum1 > -1 Or intNum1 < 11 Or intNum2 > -1 Or intNum2 < 11 Then
    
                        If answerBox.Text = intNum1 - intNum2 Then
                            correctCounter += 1
                            correctTextBox.Text = correctCounter
    
                        Else
                            incorrectCounter += 1
                            incorrectTextBox.Text = incorrectCounter
                        End If
                    End If
                End If
    
                If operatorBox.Text = "x" Then
    
                    If intNum1 < 0 Or intNum1 > 10 Or intNum2 < 0 Or intNum2 > 10 Then
    
                        MessageBox.Show("Error! Enter numbers in the range of 1-10!")
    
                    ElseIf intNum1 > -1 Or intNum1 < 11 Or intNum2 > -1 Or intNum2 < 11 Then
    
                        If answerBox.Text = intNum1 * intNum2 Then
                            correctCounter += 1
                            correctTextBox.Text = correctCounter
    
                        Else
                            incorrectCounter += 1
                            incorrectTextBox.Text = incorrectCounter
    
                        End If
                    End If
                End If
            End If
    
            'Check to see if the level 2 button is checked
            If level2RadioButton.Checked Then
    
                If operatorBox.Text = "+" Then
    
                    If intNum1 < 0 Or intNum1 > 1000 Or intNum2 < 0 Or intNum2 > 1000 Then
    
                        MessageBox.Show("Error! Enter numbers in the range of 1-1000!")
    
                    ElseIf intNum1 > -1 Or intNum1 < 1001 Or intNum2 > -1 Or intNum2 < 1001 Then
    
                        If answerBox.Text = intNum1 + intNum2 Then
                            correctCounter += 1
                            correctTextBox.Text = correctCounter
    
                        Else
                            incorrectCounter += 1
                            incorrectTextBox.Text = incorrectCounter
                        End If
                    End If
                End If
    
                If operatorBox.Text = "-" Then
    
                    If intNum1 < 0 Or intNum1 > 1000 Or intNum2 < 0 Or intNum2 > 1000 Then
    
                        MessageBox.Show("Error! Enter numbers in the range of 1-1000!")
    
                    ElseIf intNum1 > -1 Or intNum1 < 1001 Or intNum2 > -1 Or intNum2 < 1001 Then
    
                        If answerBox.Text = intNum1 - intNum2 Then
                            correctCounter += 1
                            correctTextBox.Text = correctCounter
    
                        Else
                            incorrectCounter += 1
                            incorrectTextBox.Text = incorrectCounter
                        End If
                    End If
                End If
    
                If operatorBox.Text = "x" Then
    
                    If intNum1 < 0 Or intNum1 > 1000 Or intNum2 < 0 Or intNum2 > 1000 Then
    
                        MessageBox.Show("Error! Enter numbers in the range of 1-1000!")
    
                    ElseIf intNum1 > -1 Or intNum1 < 1001 Or intNum2 > -1 Or intNum2 < 1001 Then
    
                        If answerBox.Text = intNum1 * intNum2 Then
                            correctCounter += 1
                            correctTextBox.Text = correctCounter
    
                        Else
                            incorrectCounter += 1
                            incorrectTextBox.Text = incorrectCounter
    
                        End If
                    End If
                End If
            End If
    
        End Sub
    Everything is major working now, just some minor tweaks here and there and I should be all set. Thanks for all the help, it's extremely appreciated.
    Last edited by Jangoon24; Mar 2nd, 2015 at 08:47 PM.

  12. #12
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    34,902

    Re: FormatException while reading Integer from TextBox

    There are still some issues. The code will still crash if the textboxes don't hold numbers or are blank, but perhaps you are testing that elsewhere. However, here are some suggestions about the following code:
    Code:
     If intNum1 < 0 Or intNum1 > 10 Or intNum2 < 0 Or intNum2 > 10 Then
    
                        MessageBox.Show("Error! Enter numbers in the range of 1-10!")
    
                    ElseIf intNum1 > -1 Or intNum1 < 11 Or intNum2 > -1 Or intNum2 < 11 Then
    
                        If answerBox.Text = intNum1 + intNum2 Then
                            correctCounter += 1
                            correctTextBox.Text = correctCounter
    
                        Else
                            incorrectCounter += 1
                            incorrectTextBox.Text = incorrectCounter
                        End If
                    End If
    In the If statements, you are using Or. That's ok, and it is likely that you haven't learned anything else, but you SHOULD be using OrElse. The reason for this is a bit esoteric, but it's a good idea. OrElse and AndAlso were added so that the compiler wouldn't have to evaluate the rest of the statement. Consider this line alone:
    Code:
     If intNum1 < 0 Or intNum1 > 10 Or intNum2 < 0 Or intNum2 > 10 Then
    If intNum1 is less than 0, the rest of the conditions don't really matter, because the whole statement will evaluate to True. By using Or, all those other statements will still be evaluated, depsite the fact that you already know the outcome. Using OrElse, those others will be skipped. This may seem pretty trivial, but it's actually a very useful point in other areas. Therefore, use OrElse and AndAlso rather than Or and And. The normal place that Or and And are used are in bit manipluations.

    Second, consider the ElseIf statement:

    Code:
    ElseIf intNum1 > -1 Or intNum1 < 11 Or intNum2 > -1 Or intNum2 < 11 Then
    The only way this line can be reached is if the first If statement is False. If the first if statment is False, then this statement HAS to evaluate to true, so why even bother checking? This could be a simple If rather than an ElseIf. However, it goes further than that. What value can intNum1 or intNum2 have for which this statement would evaluate to False? A value of -1 or lower for intNum1 would evaluate to False for the first part, but would evaluate to True for the second part. A value of 11 or higher for intNum1 would evaluate to True for the first part and False for the second part. A value of 0 to 10 would evaluate to True for both parts. Therefore, that condition isn't worth checking anyways, because it has to be true for the code to be reached, and the way the statement is written, there is no value that will not evaluate to True anyways.
    My usual boring signature: Nothing

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width