65.9K
CodeProject is changing. Read more.
Home

Windows Form: Limit Number of Lines in RichTextBox Control C#

Feb 9, 2019

CPOL
viewsIcon

16250

downloadIcon

212

Limit number of lines in a RichTextBox

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";

        /*max line check*/
        if (maxLine != null && maxLine > 0)
        {
            if (box.Lines.Count() >= maxLine)
            {
                List<string> lines = box.Lines.ToList();
                lines.RemoveAt(0);
                box.Lines = lines.ToArray();
            }                
        }

        /*add text*/
        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.