Reputation:
I have a simple addition program in VB.Net and I am attempting to test if the textbox is only taking in a number and not any letters. I need to use the TryParse method, and I cannot figure out wny I am still receiving this error. Pls Help
Public Class perrySolutionForm
Dim numberOne As Double
Dim numberTwo As Double
Public Function sum(ByRef numberOne As Double, ByRef numberTwo As Double)
sum = Val(numberOne) + Val(numberTwo)
End Function
Public Function difference(ByRef numberOne As Double, numberTwo As Double)
difference = Val(numberOne) - Val(numberTwo)
End Function
Private Sub sumButton_Click(sender As Object, e As EventArgs) Handles sumButton.Click
If numberOneInput.Text = "" Then
MessageBox.Show("Both fields must be filled out.")
If Double.TryParse(numberOneInput.Text, numberOne) Then
MessageBox.Show("Success")
'numberOne has a Double value
Else
MessageBox.Show("Failure")
'numberOne = Nothing
End If
Else
outputLabel.Text = sum(numberOne, numberTwo)
End If
End Sub
Private Sub numberOneInput_TextChanged(sender As Object, e As EventArgs) Handles numberOneInput.TextChanged
numberOne = numberOneInput.Text
End Sub
Private Sub numberTwoInput_TextChanged(sender As Object, e As EventArgs) Handles numberTwoInput.TextChanged
numberTwo = numberTwoInput.Text
End Sub
Upvotes: 0
Views: 5487
Reputation: 9024
This is how you use the TryParse:
If Double.TryParse(numberOneInput.Text, numberOne) Then
'code for a success
'numberOne has a Double value
Else
'code for a failure
'numberOne = Nothing
End If
End the code block if text is empty:
If String.IsNullOrWhiteSpace(numberOneInput.Text) Then
MessageBox.Show("Value is incorrect format")
Exit Sub
End If
Upvotes: 1