Manuel Sarica
Manuel Sarica

Reputation: 45

How can I write on a new Line in a MultiLine Textbox?

I have to make a program, where you're able to type in a minimum value and a maximum value. Then all the numbers from the min. to max. that are even should be showed in a multiline textbox.

But when the even number gets written into the textbox, it always overwrites the number which was written into the textbox before.

I tried Enviroment.NewLine and also this \r\n thing, but I probably used it wrong.

private void cmdstart_Click(object sender, EventArgs e)
{
    for (int i = Convert.ToInt32(textBox1.Text); i <= Convert.ToInt32(textBox2.Text); i++)
    {
        int a = i % 2;
        if (a == 0)
        {
            textBox3.Text = Convert.ToString(i);
        }
    }
}

In the end, its supposed to output all even numbers from the min. to max. in a multiline textbox. Each number should be on a new line.

Upvotes: 1

Views: 642

Answers (3)

SᴇM
SᴇM

Reputation: 7213

You can test it by yourself, if you write multiline text

Input:

1

2

3

4

5

6

7

to your textbox using designer and Text property, you can see that it generates something like this:

txt value:

"1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7"

Code:

string txt = multiLineTextBox.Text;

So if you add \r\n to your existing text, it will append text to new line:

for (int i = Convert.ToInt32(textBox1.Text); i <= Convert.ToInt32(textBox2.Text); i++)
{
    int a = i % 2;
    if (a == 0)
    {
        textBox3.Text = $"{textBox3.Text}{i}\r\n";
        // or using string.Format for older versions
        //textBox3.Text = string.Format("{0}{1}\r\n", textBox3.Text, i);
    }
}

Upvotes: 0

Access Denied
Access Denied

Reputation: 9501

It happens because you overwrite it each time.

Try the following code:

textBox3.Text += i.ToString()+Environment.NewLine; 

Upvotes: 5

Manoj Choudhari
Manoj Choudhari

Reputation: 5634

Make sure that you have set Multiline property to true on the textBox3.

You can set it through properties window after selecting textbox3 or you can write below line in the form constructor after initializeComponents is done.

textBox3.Multiline = true;

Once this is done, Environment.NewLine or \r\n both should work.

Upvotes: 1

Related Questions