I am working on a program for my Visual Basic class and have a quick question. One of the things we were encouraged to do was to check to make sure the quantity entered in a
A more correct way to do that is to use the TryParse
method available in the Int32
or Double
class
If Double.TryParse(txtQuantity.Text, Quantity) Then
If intCount < Quantity Then
lstRecipe.Items.Add(Quantity & " " & lstIngredients.Text)
intCount += 1
End If
Else
MessageBox.Show("The quantity entered is not numeric. Please add a numeric quantity.")
End If
And you could also remove the code that test for the empty textbox.
The TryParse
method wants two parameters, the first one is the string that could be converted, the second parameter is the variable that receives the result of the conversion if it is possible. If the conversion cannot be executed the function returns false.
There are numerous reasons to prefer Double.TryParse instead of IsNumeric
.
The first reason is that with TryParse
you also get the result of the conversion while with IsNumeric
you would have to do the conversion after the check.
The second reason is that you could give to IsNumeric
whatever object you want (also a Button for example) and it accepts it. You would never discover this kind of errors at compile time. Instead, with TryParse
, you could only pass a string as its first parameter.