如果文本框保留为空,则代码无效

时间:2014-08-27 20:18:49

标签: c# winforms

我在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();                 

    } 

1 个答案:

答案 0 :(得分:5)

您确实需要使用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尝试将您的字符串转换为Integer,如果失败,则返回false而不引发异常。如果文本可以转换,out tempValue变量将收到转换后的值,TryParse将返回true。

相关问题