为什么我的for循环只显示最后的结果?

时间:2018-03-17 13:13:40

标签: c#

我希望我的label2.Text显示乘法表的每个连续结果,但只显示最后一个结果。 我做了每个复选框只等于一个数学表。 checkbox1 =乘法表1,checkbox2 =乘法表2等等...... 为什么我的Windows窗体中的label2.Text属性中只显示最后一个结果? 附:我正在学习C#的入门课程。

int multiplyWith;
int multiplyNumber;
for (multiplyNumber = 1; multiplyNumber <= 12; multiplyNumber++)
{
    if (checkBox1.Checked == true)
    {
        multiplyWith = 1;
        int sum = multiplyNumber * multiplyWith;
        label2.Visible = true;
        label2.Text = sum + "\n";

    }
    else if (checkBox2.Checked == true)
    {
        multiplyWith = 2;
        int sum = multiplyNumber * multiplyWith;
        label2.Visible = true;
        label2.Text = sum + "\n";
    }
}

3 个答案:

答案 0 :(得分:2)

您没有连接结果,只是设置当前值。

这可行,但不是最干净/最有效的方法:

label2.Text += sum + "\n";

首先尝试使用StringBuilder生成结果,最后为文本框指定StringBuilder值。

StringBuilder sum = new StringBuilder();
int multiplyWith = checkBox1.Checked ? 1 : 2;

for (int multiplyNumber = 1; multiplyNumber <= 12; multiplyNumber++)
{
    sum.AppendLine(multiplyNumber * multiplyWith);
}    

label2.Visible = true;
label2.Text = sum.ToString();

答案 1 :(得分:0)

如果您愿意,可以将其更改为:

int multiplyWith;
int multiplyNumber;
var results = string.Empty;
for (multiplyNumber = 1; multiplyNumber <= 12; multiplyNumber++)
{
    if (checkBox1.Checked == true)
    {
        multiplyWith = 1;
        int sum = multiplyNumber * multiplyWith;
        label2.Visible = true;
        results += sum + "\n"
    }
    else if (checkBox2.Checked == true)
    {
        multiplyWith = 2;
        int sum = multiplyNumber * multiplyWith;
        label2.Visible = true;
        results += sum + "\n"
    } 
}

循环退出后

label2.Text = results;

答案 2 :(得分:0)

你可以从

编辑这一行
label2.Text = sum + "\n";

label2.Text += sum + "\n";