Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

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

Posted on 2006-11-09
5
Medium Priority
?
565 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 2000 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

A while ago, I was working on a Windows Forms application and I needed a special label control with reflection (glass) effect to show some titles in a stylish way. I've always enjoyed working with graphics, but it's never too clever to re-invent …
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.
Integration Management Part 2
Loops Section Overview

783 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