3

I want my form to display 1,2,3,4,5 but all it does is replace the text again and again.

for (int i = 1; i <= 5; i++)
{
    richTextBox1.Text = Convert.ToString(i);
}

I know it's because of the .Text that it always overrides itself. But how can i leave them in the form so it will display:

1
2
3
4
5

5 Answers 5

2

The problem is that in your loop, you're completely replacing the text with each iteration. So the text is left with whatever the last value of i was.

Try putting adding to the current text (with +=) and putting a new line (Environment.NewLine or "\n") between each number:

for (int i = 1; i <= 5; i++)
{
    richTextBox1.Text += Environment.NewLine + Convert.ToString(i);
}

Or alternatively, a little Linq can make your life a lot easier:

richTextBox1.Text = string.Join(Environment.NewLine, Enumerable.Range(1, 5));
Sign up to request clarification or add additional context in comments.

2 Comments

you probably should use Environment.NewLine as a separator. OP had each number on separate line in the answer.
@IlyaIvanov Good catch, thanks for updating the question to highlight OP's original intent.
1

Try this:

for (int i = 1; i <= 5; i++)
{
    richTextBox1.Text += Convert.ToString(i) + Environment.NewLine;
}

Edit:

Just noticed that you want to print one number per line. \n is the NewLine character and will give you a carriage return on the end of the line.

Environment.NewLine is also a good choice, because it will give you the newline character based on the environment the app is running in.

Comments

0

append text, don't just assign it.

richTextBox1.Text += Convert.ToString(i);

this is equivelant of

richTextBox1.Text = richTextBox1.Text + Convert.ToString(i);

Comments

0
richTextBox1.AppendText(i.ToString()+Environment.NewLine);

Comments

0

This will also do:

for (int i = 1; i <= 5; i++)
{
    richTextBox1.AppendText(i + Environment.NewLine);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.