Convert Text to Single -- Convert.ToSingle -- Input string was not in a correct format

I have a textbox "MyBox" that users input text into. In this case, it is numeric (for which I can ignore non-numeric input, but that's not the question). I do something like this:

MyValue = Convert.ToSingle(MyBox.Text)

However, if the text is empty or alphabetic (e.g., "Hello, world."), I get an error "Input string was not in a correct format." Of course, I can pre-test for that, but I was wondering if there was some easy step that I was overlooking, like one that change non-numeric values to zero instead.
LVL 9
GivenRandyAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
YZlatConnect With a Mentor Commented:
If IsNumeric(MyBox.Text) And Not Trim(MyBox.Text) = "" Then
     MyValue = Convert.ToSingle(MyBox.Text)
end if
0
 
YZlatCommented:
if not MyBox.Text="" then
      MyValue = Convert.ToSingle(MyBox.Text)
end if
0
 
GivenRandyAuthor Commented:
The second post is how I'm doing it, now (with IsNumeric). Probably not any better way.
0
 
YZlatCommented:
how much better do you want it to get?
0
 
sodalitasCommented:
Or

Try
   MyValue = Convert.ToSingle(MyBox.Text)
Catch
   MyValue = 0
End Try

That way you don't have to do 2 checks, you just go ahead and do it and treat any failure as a 0.
0
All Courses

From novice to tech pro — start learning today.