|
-
February 3rd, 2011, 04:19 AM
#1
Can't convert String to Double
Hello,Everybody!
I'm writing:
double l = Convert.ToDouble(textbox1.Text);
double l2 = Convert.ToDouble(textbox2.Text);
and getting FormatException in the second line.
There are numbers in both textboxes.
Can anyone help me?
-
February 3rd, 2011, 05:20 AM
#2
Re: Can't convert String to Double
Some details would help.
What is the text that fails to be converted?
Does the exception provide an error message?
-
February 3rd, 2011, 06:31 AM
#3
Re: Can't convert String to Double
I found an error!
While the programm was working,textbox2's text was changing by values from database.
But as it turned out,there was nothing in database that matched to my query,so,textbox2 was empty 
Thank you very mach!
Last edited by Ilia2k; February 3rd, 2011 at 07:21 AM.
-
February 3rd, 2011, 08:17 AM
#4
Re: Can't convert String to Double
I'd highly suggest a check to see if the text in the textbox is a number before performing the convert.
-
February 3rd, 2011, 12:55 PM
#5
Re: Can't convert String to Double
double.TryParse is your friend.
-
February 4th, 2011, 02:29 AM
#6
Re: Can't convert String to Double
Hello,
Try using the Double.Parse(string s) method:
Code:
double l = Double.Parse(textbox1.Text);
This will parse the string in textbox1.Text into a double. If this fails, it will throw an exception.
Here is the MSDN page: http://msdn.microsoft.com/en-us/library/fd84bdyt.aspx
--If that's all you need, you can stop here... more detail follows--
If you want to handle the case of failed parsing without using exceptions, you can use Double.TryParse(string s, out double d) method, like this:
Code:
double d = 0;
bool succeeded = Double.TryParse(textbox1.Text, out d);
if( !succeeded )
{
//Handle the conversion error
}
Note that the out keyword here is telling TryParse to store the result of the conversion in d while actually returning a bool specifying whether or not the conversion succeeded.
If you're using trusted inputs, no need to use TryParse. If the inputs are untrusted, you should consider implementing error handling!
Hope that helps! Let me know if you have problems.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|