0

I have an error message when I type a number in a textbox to give it a format. when I'm typing with this code :

private void textBoxX1_TextChanged(object sender, EventArgs e)
    {
        textBoxX1.Text = string.Format("{0:F}",double.Parse(textBoxX1.Text));
        string txtval = textBoxX1.Text;

      }

I only want two decimals for formatting so if I type 100 the textbox format it to 100.00. and then passes that value to the variable txtval but give me this error:

Input string was not in a correct format.

Martin
  • 22,212
  • 11
  • 70
  • 132
stone edge
  • 62
  • 7
  • Possible duplicate of [how to resolve "Input string was not in a correct format." error?](http://stackoverflow.com/questions/12269254/how-to-resolve-input-string-was-not-in-a-correct-format-error) – Eric Burdo Mar 16 '17 at 19:59

2 Answers2

0

I recommend using TryParse instead of Parse to avoid the Exception.

Mario Levesque
  • 1,017
  • 13
  • 13
0

You should use TryParse to first verify if you can parse what's in the textbox. You're getting this exception because the value in the textbox can't be parsed to a double. You should modify your code to look like this :

private void textBoxX1_TextChanged(object sender, TextChangedEventArgs e)
{
    double value = 0.00;

    if (double.TryParse(textBoxX1.Text, out value))
    {
        textBoxX1.Text = string.Format("{0:F}", value);
        string txtval = value.ToString();
    }       
}

What this does is first verify that the value in the textbox can be parsed to a double and then format it and add it to the textbox.

I.B
  • 2,925
  • 1
  • 9
  • 22