繁体   English   中英

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

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

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

如果输入0.071,则程序运行正常。 但是,如果输入.071,我会得到愚蠢的输入格式异常错误。 我想删除此令人讨厌的输入格式异常错误,因为用户忘记输入0.071。

这是详细信息。

我的“织物重量”文本框的屏幕截图,其中有小数点

  • 我的“织物重量”文本框的屏幕截图,其中有小数点

我得到了例外。

  • 我得到了例外。

      try { if (System.Text.RegularExpressions.Regex.IsMatch(textBox28.Text, "[^0-9^+]")) { MessageBox.Show("Please enter only numbers."); textBox28.Clear(); textBox28.Focus(); } } catch (ArgumentOutOfRangeException err){ MessageBox.Show(err.ToString()); } try { // Input format error 702 FabricWeight = float.Parse(textBox28.Text); } catch (FormatException err) { MessageBox.Show(err.ToString()); 

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

这可行。

“在此方法下面”我将结果存储在“织物权重”中,您可以将其用于程序,并在“尝试解析”之后存储到所需的任何变量中。

    private static void TryToParse(string value)
    {
        double number;
        bool result = double.TryParse(value, out number);

        if (result)
        {

            FabricWeight = number;

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

        }
    }

写下并工作。

TryToParse(textBox28.Text);

有关更多信息:请访问此链接MSDN库:TryParse

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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