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?
Printable View
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?
Some details would help.
What is the text that fails to be converted?
Does the exception provide an error message?
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!
I'd highly suggest a check to see if the text in the textbox is a number before performing the convert.
double.TryParse is your friend.
Hello,
Try using the Double.Parse(string s) method:
This will parse the string in textbox1.Text into a double. If this fails, it will throw an exception.Code:double l = Double.Parse(textbox1.Text);
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:
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.Code:double d = 0;
bool succeeded = Double.TryParse(textbox1.Text, out d);
if( !succeeded )
{
//Handle the conversion error
}
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.