【问题标题】:Multiple textbox value addition using single button click event使用单个按钮单击事件添加多个文本框值
【发布时间】:2014-05-24 13:12:17
【问题描述】:

我的 Windows 应用程序中有 15 个文本框和 1 个按钮。

我想要做的是使用单按钮单击事件添加 15 文本框的值。可以吗??

我尝试声明一个数组,然后在数组上循环,但它显示错误“无法转换为 int”

private void button1_Click(object sender, EventArgs e)      
{
    int i;
    int j = 0;
    while (i <= r15c5)
    {
        j = j + i;
        j--;
    }
}

【问题讨论】:

  • @Soner Gönül 它的 R2D2 的继任者
  • @Uzi 首先,您能否更具体地了解一下什么类型的 Windows 应用程序? Asp.net(因为你标记了它),或 Win Forms,或 WPF ?
  • 有很多方法可以解决这个问题。无法转换为 int,表明您的文本框的内容不是 int。检查一下,你的代码(不管它是什么......)可能会起作用。 PS j 对总而言是非常非常糟糕的名字......

标签: c# winforms


【解决方案1】:

如果你正在使用.Net framework 3.5或更高版本,你可以使用Linq,并且在一行中完成:

首先,你导入:

using System.Linq;

然后:

private void button1_Click(object sender, EventArgs e)
{
   MessageBox.Show(this.Controls.OfType<TextBox>().Sum(t => Int32.Parse(t.Text)).ToString());
}

解释:

//selects all text boxes in your form
this.Controls.OfType<TextBox>()

//gets the sum of all the textboxes according to the selector inside the .Sum() function
.Sum(t => Int32.Parse(t.Text))

//a Lambda expression to select the texts of the text boxes, and parse them as integers
t => Int32.Parse(t.Text)]
  • 更多关于 lambda 表达式的信息可以在Here找到

【讨论】:

    【解决方案2】:

    好吧,我不确定您的意思,但是这段代码创建了一个数组,添加了 2 个文本框(您可以添加任意数量的文本框)并将它们的值相加:

    private void button1_Click(object sender, EventArgs e)
    {
        TextBox[] texts = new TextBox[] { textBox1, textBox2 };
        int sum = 0;
    
        foreach (TextBox textBox in texts)
            sum += int.Parse(textBox.Text);
    
    }
    

    int.Parse 从文本字符串中获取一个 int

    【讨论】:

      猜你喜欢
      • 2017-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多