Search code examples
c#xamlwindows-8

I get a FormatException when I'm trying to parse a Double


I am working on a Windows 8 Application. I have a listbox that shows specific things for an item that is clicked on(SelectedIndex).

Based on the text that is shown in the different textboxes I create a new instance for a class that takes the information and puts them in an object. From that object I put the different objectinformation into double variables that I can output in the screen with the "toString()" method. Each time I want to "add" something to the list I want the numbers to multiply instead of that the text strings just adds to each other for example:

 totalWeight += double.Parse(tbx_TotalVikt.Text);

Here I want the totalWeight (which is a double) to be a parsed version of the text that is in the tbx_TotalVikt.Text. But I keep getting this error message:

An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code

Additional information: Input string was not in a correct format.


Solution

  • I fixed it.

    double item = 0;
    if(double.TryParse(tbx_TotalVikt.Text, out item))
                {
                    totalWeight += item;
                }
    tbx_TotalVikt.Text = totalWeight.ToString();
    

    Used TryParse to look if the text is a double.