使用单击按钮单击事件添加多个文本框值

时间:2014-05-24 13:12:17

标签: c# winforms

我的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--;
    }
}

2 个答案:

答案 0 :(得分:0)

好吧,我不确定你的意思,但这段代码会创建一个数组,添加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

答案 1 :(得分:0)

如果您正在使用.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
相关问题