总结两个文本框的数值,并在第三个文本框中实时显示

时间:2018-09-19 06:44:17

标签: c#

我正在尝试创建一种方法,该方法将放入textchangedkeypress事件中。在该方法中,我将文本框中的值解析为int,然后将其提供给该方法,以便它将这些值相加并以字符串形式返回。 但是,当我在运行文本框时删除该文本框的内容时,可以使用不同的值,它的作用类似于字符串而不是值,并抛出System.Format exeption该方法具有不同的数据类型。

这是引发错误的方法的调用:

vys = Addup(Convert.ToInt32(textBox3.Text), 
            Convert.ToInt32(textBox2.Text), 
            Convert.ToInt32(numericUpDown1.Value)).ToString();

label1.Text = vys;

1 个答案:

答案 0 :(得分:0)

使用用户输入时,我们应该验证。例如。如果用户只是清除 textBox12怎么办?是的,因为空文本不是不是,所以有效整数 Convert.ToInt32(textBox2.Text)将抛出System.Format exeption

让我们借助TryParse进行验证:

  if (int.TryParse(textBox3.Text, out var v3) &&
      int.TryParse(textBox2.Text, out var v2) &&
      numericUpDown1.Value >= int.MinValue && numericUpDown1.Value <= int.MaxValue) {
    // All three values are valid integers
    // The result will be Decimal, that's why we can skip 
    // IntegerOverflowException prevention.
    // Order matters: 0m + 2_000_000_000 + 2_000_000_000 = 4_000_000_000m
    //                2_000_000_000 + 2_000_000_000 + 0m - Exception (overflow)
    label1.Text = (numericUpDown1.Value + v3 + v2).ToString();  
  }
  else {
    // At least one value is not a valid Int32
    label1.Text = "???";
  }