Christoffel Joubert
Christoffel Joubert

Reputation: 15

Why is my for loop only displaying the last result?

I want my label2.Text to display each concecutive result of the multiplication table, but only the last result gets displayed. I made that each checkbox equals only one math table. checkbox1 = multiplication table 1, checkbox2 = multiplication table 2 and so on... Why is only the last result being displayed in my label2.Text property in my Windows Form? P.S. I am working through an introduction course of 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";
    }
}

Upvotes: 1

Views: 148

Answers (3)

John Caprez
John Caprez

Reputation: 393

You are not concatenating the result but only setting the current value.

This would work but is not the most clean/efficient way to do it:

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

Try using a StringBuilder to generate the result first and at the end assign the text box the StringBuilder value.

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

Upvotes: 2

Tendai
Tendai

Reputation: 147

you could just edit this line from

label2.Text = sum + "\n";

to

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

Upvotes: 0

Prasanth Louis
Prasanth Louis

Reputation: 5046

If you want you could change it to something like:

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"
    } 
}

Then after your loop exits:

label2.Text = results;

Upvotes: 0

Related Questions