Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
8 Feb 2019 1  
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here