当textbox1.text为空时获取错误消息框

时间:2018-06-08 18:18:03

标签: c#

我有错误消息ibb.co/dmKd2o的屏幕截图。它基本上是说“输入字符串的格式不正确”,并且每次我清除textbox1.text时都会出现该错误消息。

代码如下:

/*This is located inside public partial class Form1 : Form*/
        double aantalgroep = 0;
        double number = 0;

 /*This is located inside private void Calculate()*/       

        aantalgroep = double.Parse(textBox1.Text);

        /* Wat er gebeurd bij RadioButton1 Checked */
        if (radioButton1.Checked)
        {
            number = aantalgroep * 8;

            textBox2.Text = number.ToString();

      /* I tried this but this doesn't work? */
            if (textBox1.Text == "")
            { aantalgroep = 0;
            } else
            {
                aantalgroep = double.Parse(textBox1.Text);
            }
/* From here everything is oke( i think ) */


            if (aantalgroep < 10)
            {
                textBox2.Text = number.ToString();
            }

}

5 个答案:

答案 0 :(得分:2)

一种解决方案是使用TryParse()代替Parse()

double.TryParse(textBox1.Text, out aantalgroep);

这会将aantalgroep设置为您在成功解析时所期望的值,并将aantalgroep设置为0(真正default(double)为0)以获取无效字符串。

答案 1 :(得分:1)

在此行中,当文本框为空时,您会收到该错误

aantalgroep = double.Parse(textBox1.Text);

您需要使用

进行更改
if(!double.TryParse(textBox1.Text, out aantalgroep))
   aantalgroep = 0;

或者只是在没有if的情况下调用TryParse,因为aantalgroep已被初始化为0

double.TryParse(textBox1.Text, out aantalgroep);

答案 2 :(得分:0)

aantalgroep = double.Parse(textBox1.Text);
如果textBox1.Text不是有效的数字字符串,

将失败。 要么捕获异常,要么使用double.TryParse返回一个bool来告诉你它是否成功

答案 3 :(得分:0)

使用此代码:

if (string.IsNullOrEmpty(textBox1.Text))
        { aantalgroep = 0;
        }

答案 4 :(得分:0)

我想我也在另一个问题的评论中提到了这一点。

两种方法double.Parse()double.TryParse()做两件略有不同的事情。

double.Parse(string s)

此方法将string转换为double,并返回该值。 如果 string不代表可转换为double的有效值,则会引发FormatException

因此,例如,如果你的字符串类似于“abc”,或者它是一个空字符串,它将抛出所述异常。

double.TryParse(string s, out double result)

尝试string转换为double。如果成功转换,则返回trueresult将包含转换后的值。但是,如果不成功,它将 NOT 抛出异常,但会返回false,而失败情况下result的值将为零。

见下文:

当此方法返回时,如果转换成功,则包含等效于s参数的双精度浮点数,如果转换失败,则包含零。如果s参数为null或String.Empty,不是有效格式的数字,或者表示小于MinValue或大于MaxValue的数字,则转换失败。此参数未初始化传递;结果中最初提供的任何值都将被覆盖。

现在,查看您的代码,在我看来,您希望查看TextBox的值是否可以转换为double,如果成功,请执行值和否则,在TextBox中显示“0”。

所以,试着在脑海中制定你需要做的事情。它将是这样的:

  1. 获取文本框的值,然后尝试将其转换为double。使用double.TryParse()
  2. 查看上述转换是否成功。您可以使用上述方法的返回值和if语句。
  3. 如果成功,请使用转换后的double值执行您想要的操作。 aantalgroep变量将包含此值。
  4. 如果不成功,只需将“0”打印到TextBox
  5. 即可

    看起来应该是这样的:

    double aantalgroep = 0;
    double number = 0;
    
    if (radioButton1.Checked)
    {
        if (double.TryParse(textBox1.Text, out aantalgroep))
        {
            // Stuff you do when successful.
            number = aantalgroep * 8;
            textBox2.Text = number.ToString();
        }
        else
        {
            // Stuff you do when unsuccessful.
            // Something like textBox2.Text = "0"; ?
        }
    }
    
相关问题