c# - 在文本框中添加数字

标签 c# function textbox null

我有这样的代码,它只有在所有文本框都包含值时才有效。但是如果文本框是空的,我会得到一个错误。

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);

我知道它必须是一个类似于 IsNull 的函数,但对于整数值.. 有谁知道这是什么吗?

最佳答案

您正在寻找 Int32.TryParse :

Int32 val;
if (Int32.TryParse(txtChild1.Text, out val)){
  // val is a valid integer.
}

您在每个 .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;
    }
}

然后,在实践中:

Int32 total = txtChild1.Text.ToInt32() + txtChild2.Text.ToInt32()
            + txtChild3.Text.ToInt32() + /* ... */;

当然还有 an example

关于c# - 在文本框中添加数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14459945/

相关文章:

asp.net - asp.net 服务器端的 TextBox keydown 事件

文本框透明,就像我的 winform 上的一个洞

c# - 文本框和标签之间的一致空间和对齐方式

c# - 如何使用调试器处理任务中的异常?

c# - 异步 WebApi Thread.CurrentCulture

javascript - 使用参数数组更改 JavaScript 函数的参数值不起作用

javascript - 我可以从 document.formID.submit(); 调用 JS 函数吗?

c++ - 函数模板和私有(private)继承

c# - WPF TextBox 不允许有空格

c# - 从另一个线程更新时,DataGridView 不会重新绘制自身