简体   繁体   中英

Error Formatting textbox in C#

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.

我建议使用TryParse而不是Parse来避免发生异常。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM