Link to home
Start Free TrialLog in
Avatar of wally_davis
wally_davisFlag for United States of America

asked on

VB.NET InputBox "InvalidCastException was unhandled" error when clicking on the Cancel button

In VB.NET, when I click on the InputBoxes "Cancel" button, I get an "InvalidCastException was unhandled" error. essentially, this program is just a test whereby the User picks a number, a random number is generated, the two are compared and an Image moves around on the Form depending on whether your guess is higher or lower than the computers (randomGenerator) randomly generated number.
Here is the VB.NET Code: (The user clicks on a Button named "Generate Number", which then presents an InputBox where the User must enter a number from 10 to 100).

Private Sub generateNumberButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles generateNumberButton.Click
        Dim userChoice As String
        Static numberCorrect As Integer
        Static numberIncorrect As Integer

        ' Save the user's Listbox selection
        ' userChoice = pickNumberListBox.SelectedItem.ToString
        userChoice = InputBox("Please pick a number from 10 to 100", "Pick A Number", "10")

        randomNumber = randomGenerator.Next(10, 101)
        cgnDisplayLabel.Text = Convert.ToString(randomNumber)


        If CDbl(userChoice) < randomNumber Then  ' <-- The CastException happens here and possibly in th
                                                                               ' next ElseIf condition
            tryAgainPictureBox.SetBounds(479, 41, 0, 0, BoundsSpecified.Location)
        ElseIf CDbl(userChoice) > randomNumber Then
            tryAgainPictureBox.SetBounds(479, 103, 0, 0, BoundsSpecified.Location)
        Else
            MessageBox.Show("The number you selected matches the computers number", _
            "The numbers match", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub

Any ideas on how to re-write the code  to prevent the InvalidCastException?

Thank you,
Wally
Avatar of JimBrandley
JimBrandley
Flag of United States of America image

Set a breakpoint on this line:
     If CDbl(userChoice) < randomNumber Then  

When you hit it, Quickwatch userChoice to see what you got back.

Jim
ASKER CERTIFIED SOLUTION
Avatar of appari
appari
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial