Steven Ackerman
Steven Ackerman

Reputation: 11

What can I use instead of isnumeric in vb.net

I am writing a simple Random Number guessing game and am using the statement isnumeric. This is a Visual Basic program being done in Visual Studio 2013.

Here is my code:

Private Sub btnTry_Click(sender As Object, e As EventArgs) Handles btnTry.Click
    Dim intTry As Integer
    Dim strInputBox As String
    strInputBox = InputBox("Enter Your Number to Guess.", "Input Needed")

    If IsNumeric(strInputBox) Then
        intTry = CInt(strInputBox)
        lstTried.Items.Add(intTry)
    Else
        MessageBox.Show("Please Type Only Numbers")
    End If

    If intTry = intRandomNumber Then
        MessageBox.Show("You Got It!", "Correct Guess")

    Else
        MessageBox.Show("Incorrect. Please try again.", "Incorrect Guess")

    End If

I'd like to use something in place of "IsNumeric" in my If statement. I'm not sure at all how to do that. Can someone help me. I tried to use integer.tryparse but could not make it work. Specific help would be appreciated. This works right now, I'm tempted to leave it alone, but I was told it's old style code and there is another way to do it.

Thanks,

Steve

Upvotes: 1

Views: 1315

Answers (1)

Trevor
Trevor

Reputation: 8004

You can try this, I also made some suggestive corrections to your code.

Private Sub btnTry_Click(sender As Object, e As EventArgs) Handles btnTry.Click
 Dim intTry As Integer = 0

 'This wont throw an exception if it's not an integer, it will come back false...
 If Integer.TryParse(InputBox("Enter your number to guess.", "Input Needed"), intTry) Then
    lstTried.Items.Add(intTry)
 Else
    MessageBox.Show("Please Type Only Numbers")
    Exit Sub
 End If 

 If intTry = intRandomNumber Then
    MessageBox.Show("You Got It!", "Correct Guess")
 Else
    MessageBox.Show("Incorrect. Please try again.", "Incorrect Guess")
 End If

End Sub

Upvotes: 2

Related Questions