Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 597
  • Last Modified:

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.
0
GivenRandy
Asked:
GivenRandy
  • 3
1 Solution
 
YZlatCommented:
if not MyBox.Text="" then
      MyValue = Convert.ToSingle(MyBox.Text)
end if
0
 
YZlatCommented:
If IsNumeric(MyBox.Text) And Not Trim(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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now