Solved

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

Posted on 2006-11-09
5
500 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

Question has a verified solution.

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

Suggested Solutions

This tutorial demonstrates one way to create an application that runs without any Forms but still has a GUI presence via an Icon in the System Tray. The magic lies in Inheriting from the ApplicationContext Class and passing that to Application.Ru…
Article by: jpaulino
XML Literals are a great way to handle XML files and the community doesn’t use it as much as it should.  An XML Literal is like a String (http://msdn.microsoft.com/en-us/library/system.string.aspx) Literal, only instead of starting and ending with w…
This video shows how to use Hyena, from SystemTools Software, to update 100 user accounts from an external text file. View in 1080p for best video quality.

710 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