Joe Busby
Joe Busby

Reputation: 97

C# Multiplication Table - Only 1 multiplication is showing

I am creating a multiplication table, when you input a number and click the calculate button it should display. I have tried watching a few tutorials on YouTube and have checked out some coding forums however I can only find people using the Console Application however I am using the Windows Form Application

1 * 1 = 1 
2 * 1 = 2 
3 * 1 = 3
4 * 1 = 4
5 * 1 = 5
6 * 1 = 6
7 * 1 = 7
8 * 1 = 8
9 * 1 = 9
10 * 1 = 10

However, when I run the program it only displays

1 * 10 = 10

Here is my code;

private void btnCalc_Click(object sender, EventArgs e)
{
    int n, i;
    n = Int32.Parse(txtNum.Text);
    for (i = 1; i <= 10; ++i)
        txtCalc.Text = Convert.ToString(n + " * " + i + " = " + n * i);
}

Upvotes: 0

Views: 141

Answers (3)

Felix
Felix

Reputation: 10078

your txtCalc.Text... overwrites the field in every iteration. You probably want something like this:

txtCalc.Text = "";
for (i = 1; i <= 10; ++i)
{
    txtCalc.Text += Convert.ToString(n + " * " + i + " = " + n * i);
}

Upvotes: 1

itsme86
itsme86

Reputation: 19496

You're overwriting the text over and over again. What you want to do is append new text every time through the loop. Try something like:

txtCalc.Text = "";

for (i = 1; i <= 10; ++i)
{
    txtCalc.Text += Convert.ToString(n + " * " + i + " = " + n * i) + Environment.NewLine;
}

Upvotes: 1

Eric J.
Eric J.

Reputation: 150108

This loop keeps setting the control's text to a different value over and over, leaving you to see only the final value.

for (i = 1; i <= 10; ++i)
{
    txtCalc.Text = Convert.ToString(n + " * " + i + " = " + n * i);
}

A straightforward solution is:

string text = "";
for (i = 1; i <= 10; ++i)
{
    text += Convert.ToString(n + " * " + i + " = " + n * i);
}
txtCalc.Text = text;

You will still run into some formatting issues you'll need to solve, but you'll get the fundamental info in there.

Upvotes: 2

Related Questions