【问题标题】:Code is not working if textbox is left empty如果文本框为空,代码将不起作用
【发布时间】:2014-08-27 20:18:48
【问题描述】:

我在 Windows 窗体中插入了一个数字文本框,用于我的数据输入。在少数情况下,如果我故意将其中一些留空,代码将不起作用。它说“输入字符串的格式不正确。”我可以禁用已链接到变量的文本框以使代码不会中断吗?

    private void button1_Click(object sender, EventArgs e)
    {

        String FloorNumber = textBox1.Text;
        int RebarCover = Convert.ToInt32(textBox2.Text);
        int LongitudinalRebarDiameter = Convert.ToInt32(textBox3.Text);
        int StirupDiameter = Convert.ToInt32(textBox4.Text);
        int CountOfEdgeBarsNorth = Convert.ToInt32(textBox5.Text);
        int CountOfEdgeBarsEast = Convert.ToInt32(textBox6.Text);                   
        textBox14.Text = RebarCover.ToString();                 

    } 

【问题讨论】:

  • 因为您无法将""string.Empty 转换为整数.. 它正盯着您.. 为什么不写一些条件检查,如果它为空或空白,则默认文本框到 0

标签: c# winforms


【解决方案1】:

您确实需要使用Int32.TryParse 以避免在这种情况下失败

    int tempValue;
    String FloorNumber = textBox1.Text;
    if(!Int32.TryParse(textBox2.Text, out tempValue)
    {
         MessageBox.Show("Need a valid number for RebarCover");
         return;
    }
    int RebarCover = tempValue;

    // and same code for the other textboxes that you need to convert to a Int32
    ....                   

Int32.TryParse 尝试将您的字符串转换为整数,如果失败,它会返回 false 而不会引发异常。如果文本可以转换,out tempValue 变量接收转换后的值,TryParse 返回 true。

【讨论】:

    猜你喜欢
    • 2018-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    • 2017-05-11
    • 2023-04-11
    相关资源
    最近更新 更多