Introduction
Earlier today, I had a requirement to only show 10 lines (as needed) in a RichTextBox
, removing the oldest as new lines were been added, and maintaining proper line formats. I made a simple solution for that, and today, I am going to talk about that.
Example
Here, we can see the differences between the new custom append and regular default append.

Using the Code
The helper class with a new extension method:
public static class ControlHelper
{
public static void AddLine(this RichTextBox box, string text, uint? maxLine = null)
{
string newLineIndicator = "\n";
if (maxLine != null && maxLine > 0)
{
if (box.Lines.Count() >= maxLine)
{
List<string> lines = box.Lines.ToList();
lines.RemoveAt(0);
box.Lines = lines.ToArray();
}
}
string line = String.IsNullOrEmpty(box.Text) ? text : newLineIndicator + text;
box.AppendText(line);
}
}
New Line Append With Max Limit
Using this extension method to append a new line in the control with line limit:
this.Invoke((MethodInvoker)delegate
{
richTextBox1.AddLine("Hello!", 10);
richTextBox1.ScrollToCaret();
});
New Line Append
Using this extension method to append a new line in the control without any limit:
this.Invoke((MethodInvoker)delegate
{
richTextBox2.AddLine("Hello!");
richTextBox2.ScrollToCaret();
});
Default Text Append
This is how default RichTextBox
works:
this.Invoke((MethodInvoker)delegate
{
richTextBox3.AppendText("Hello!");
richTextBox3.ScrollToCaret();
});
Please find the sample desktop project (VS2017) as an attachment.