ElektroStudios ElektroStudios - 3 months ago 36
Vb.net Question

Fastest way to append text to a richtextbox?

I have a application with a RichTextBox control where a procedure is adding text almost all the time:

RichTextBox1.Text += vbNewLine & "Title: " & AlbumName
RichTextBox1.Text += vbNewLine & "Genre: " & AlbumGenre
RichTextBox1.Text += vbNewLine & "Year : " & AlbumYear
RichTextBox1.Text += vbNewLine & "Url : " & AlbumLink

' The slow thing I think is here:
RichTextBox1.SelectionStart = RichTextBox1.Text.Length

RichTextBox1.ScrollToCaret


The problem is when the richtextbox has about more than 50 lines, when has more lines it turns more slowly to append the new text (obvious).

I need to find a better way to accelerate the process, to loose at least a insignificant speed when richtextbox line-count reaches 1.000 (for example).

The reason of this question is because I want to do the the things in the right way, I don't like my app to be slow when my richtextbox has much lines.

Please, I need info, ideas and/or examples (no matter if in C# or VBNET).
Thankyou.

Answer

Use a StringBuilder and assign Text in one go.

Unless you rewrite the RichTextBox control I dont think you'll be able to speed up this function:

' The slow thing I think is here:
RichTextBox1.SelectionStart = RichTextBox1.Text.Length 

For better speed consider these alternatives:

Fast-Colored-TextBox-for-syntax-highlighting

ScintillaNET

Icsharpcode TextEditor


Here is how you do the scrolling to end with Fast-Colored-TextBox-for-syntax-highlighting:

 Editor.ScrollLeft();
 Editor.Navigate(Editor.Lines.Count - 1);

Here is how you do the scrolling to end with Scintella.Net: Vertical scroll Scintilla Textbox during Text Changed event Disclaimer: I dont work for any of these companies.

Update:

StringBuilder sb = new StringBuilder();
sb.Append(Environment.NewLine  + "Title: " + AlbumName);
sb.Append(Environment.NewLine  + "Genre: " + AlbumGenre);
sb.Append(Environment.NewLine  + "Year : " + AlbumYear);
sb.Append(Environment.NewLine  + "Url  : " + AlbumLink);
RichTextBox1.Text = sb.ToString();