Link to home
Start Free TrialLog in
Avatar of GivenRandy
GivenRandy

asked on

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.
Avatar of YZlat
YZlat
Flag of United States of America image

if not MyBox.Text="" then
      MyValue = Convert.ToSingle(MyBox.Text)
end if
ASKER CERTIFIED SOLUTION
Avatar of YZlat
YZlat
Flag of United States of America 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
Avatar of GivenRandy
GivenRandy

ASKER

The second post is how I'm doing it, now (with IsNumeric). Probably not any better way.
how much better do you want it to get?
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.