CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6
  1. #1
    Join Date
    Feb 2011
    Posts
    4

    Angry 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?

  2. #2
    Join Date
    Sep 1999
    Posts
    137

    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?

  3. #3
    Join Date
    Feb 2011
    Posts
    4

    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.

  4. #4
    Join Date
    Dec 2008
    Posts
    144

    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.

  5. #5
    Join Date
    Jun 2008
    Posts
    2,477

    Re: Can't convert String to Double

    double.TryParse is your friend.

  6. #6
    Join Date
    Feb 2011
    Location
    United States
    Posts
    1,016

    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
  •  





Click Here to Expand Forum to Full Width

Featured