Solved

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

Posted on 2006-11-09
5
483 Views
Last Modified: 2008-01-09
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
Comment
Question by:GivenRandy
  • 3
5 Comments
 
LVL 35

Expert Comment

by:YZlat
ID: 17908924
if not MyBox.Text="" then
      MyValue = Convert.ToSingle(MyBox.Text)
end if
0
 
LVL 35

Accepted Solution

by:
YZlat earned 500 total points
ID: 17908941
If IsNumeric(MyBox.Text) And Not Trim(MyBox.Text) = "" Then
     MyValue = Convert.ToSingle(MyBox.Text)
end if
0
 
LVL 9

Author Comment

by:GivenRandy
ID: 17909189
The second post is how I'm doing it, now (with IsNumeric). Probably not any better way.
0
 
LVL 35

Expert Comment

by:YZlat
ID: 17909237
how much better do you want it to get?
0
 
LVL 6

Expert Comment

by:sodalitas
ID: 17909239
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

Featured Post

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

If you're writing a .NET application to connect to an Access .mdb database and use pre-existing queries that require parameters, you've come to the right place! Let's say the pre-existing query(qryCust) in Access takes a Date as a parameter and l…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

775 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question