在TextBox中添加数字

Nej*_*the 3 c# null textbox function

我有这个代码,它只有在所有textBox包含值时才有效..但如果文本框为空,我会收到错误..

Int32 Total = Int32.Parse((txtChild1.Text))
            + Int32.Parse(txtChild2.Text)
            + Int32.Parse(txtChild3.Text)
            + Int32.Parse(txtWife1.Text)
            + Int32.Parse(txtWife2.Text)
            + Int32.Parse(txtWife3.Text);
Run Code Online (Sandbox Code Playgroud)

我知道它必须是像IsNull这样的函数,但对于整数值.有谁知道它是什么?

Bra*_*tie 8

您正在寻找Int32.TryParse:

Int32 val;
if (Int32.TryParse(txtChild1.Text, out val)){
  // val is a valid integer.
}
Run Code Online (Sandbox Code Playgroud)

你在每个.Text房产上打电话,然后将它们加在一起.您还可以进行扩展以使其更容易(如果您选择):

public static class NumericParsingExtender
{
    public static Int32 ToInt32(this String input, Int32 defaultValue = 0)
    {
      if (String.IsNullOrEmpty(input)) return defaultValue;
      Int32 val;
      return Int32.TryParse(input, out val) ? val : defaultValue;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,在实践中:

Int32 total = txtChild1.Text.ToInt32() + txtChild2.Text.ToInt32()
            + txtChild3.Text.ToInt32() + /* ... */;
Run Code Online (Sandbox Code Playgroud)

当然还有一个例子