如果我在 C# 的文本框中以小数点开始输入,我会得到输入格式异常

If I start input with decimal point in my textbox in C#, I get Input Format Exception

我正在计算十进制的织物重量。

如果我输入 0.071,程序运行正常。 但是如果我输入 .071,我会得到输入格式异常错误,这是愚蠢的。我想消除这个恼人的输入格式异常错误,因为用户忘记输入 0.071.

这是详细信息。

FabricWeight = float.Parse(textBox28.Text);之前你可以添加:

if(textBox28.Text.StartsWith('.')
{
      textBox28.Text = string.Format("{0}{1}", 0, textBox28.Text);
}

正如乔恩所说 - 使用 TryParse 效率更高。

在文本框的事件按键中尝试此代码,更好的方法是:

private void textBox28_KeyPress(object sender, KeyPressEventArgs e)
    {
        if ( System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "[^0-9^+.]") )
            e.Handled = true;
        if (e.KeyChar == '.' && textBox28.Text.Length == 0)
            e.Handled = true;

        int i = 0;
        foreach (char cc in textBox28.Text)
            if (cc == '.')
                i++;
        if (i >= 1 && e.KeyChar == '.')
            e.Handled = true;
    }

我现在测试一下。请检查这个。

感谢@Bruniasty

这有效。

"Below this method" 我将结果存储在织物重量中,您可以将其用于您的程序并在 "Try Parsing".

之后存储到您喜欢的任何变量
    private static void TryToParse(string value)
    {
        double number;
        bool result = double.TryParse(value, out number);

        if (result)
        {

            FabricWeight = number;

        }
        else
        {
            if (value == null) value = "";

        }
    }

Wrote this and worked.

TryToParse(textBox28.Text);

了解更多信息:访问此 link MSDN Library: TryParse