Newlines in TextBox

T

Todd Brown

I'm trying to programatically add new lines to the content of a
(System.Windows.Forms.)TextBox and, while I have found a solution, I
feel that it can't be very efficient. There must be a better way.

I first tried:

textBox.AppendText( "\n New line" );

But that didn't work. Nor did variations on the theme, like
textBox.Text += ....

Here's what *did* work:

String[] lines = new String[textBox.Lines.Length+1];
textBox.Lines.CopyTo( lines, 0 );
lines[lines.Length-1] = textBox.Text;
textBox.Lines = lines;

This seems very inefficient since we're copying the *entire* contents of
the text box just to add a single new line.

Am I missing something here?

-- T
 
A

Andrej Tozon

Hi Todd,

try textBox.AppendText( "\r\n New line" );

....or better yet - user Environment.NewLine instead of "\r\n\".

Andrej
 
H

Herfried K. Wagner [MVP]

Todd Brown said:
I'm trying to programatically add new lines to the content of a
(System.Windows.Forms.)TextBox and, while I have found a solution, I feel
that it can't be very efficient. There must be a better way.

I first tried:

textBox.AppendText( "\n New line" );

But that didn't work. Nor did variations on the theme, like textBox.Text
+= ....

Windows uses "\r\n" as newline character sequence. Instead of hardcoding
"\r\n" it's maybe better to use 'Environment.NewLine', which will return a
platform-dependent newline character sequence. In addition make sure the
textbox' 'MultiLine' property is set to 'True'.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top