Click here to Skip to main content
16,005,473 members
Articles / Desktop Programming
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
8 Feb 2019CPOL 16.1K   209   1   3
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.

Image 1

Using the Code

The helper class with a new extension method:

C#
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:

C#
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:

C#
this.Invoke((MethodInvoker)delegate
{
    richTextBox2.AddLine("Hello!");
    richTextBox2.ScrollToCaret();
});

Default Text Append

This is how default RichTextBox works:

C#
this.Invoke((MethodInvoker)delegate
{
    richTextBox3.AppendText("Hello!");
    richTextBox3.ScrollToCaret();
});

Please find the sample desktop project (VS2017) as an attachment.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Bangladesh Bangladesh
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionAdding line when removing previous line Pin
asheimo10-Sep-20 12:03
asheimo10-Sep-20 12:03 
I am using a richtextbox to mimic the output of the commandline window and there are times when the output actually replaces the last line, i.e. CR instead of CRLF. Capturing the output of stdout and stderr does not capture this so I have setup a sub as follows:

Private Sub UpdateTextBox(ByVal Tex As String)
    If Me.InvokeRequired Then
        Dim del As New UpdateTextBoxDelegate(AddressOf UpdateTextBox)
        Dim args As Object() = {Tex}
        Me.Invoke(del, args)
    Else
        If Tex = "Complete" Then
            rtbProgress.AddLine("Job Complete", 200)
            'rtbProgress.Text &= vbCrLf & "Job Complete" & vbCrLf
        ElseIf Tex Is Nothing Then
            rtbProgress.Text &= Tex & vbCrLf
        ElseIf Strings.Left(Tex, 6) = "frame=" Then
            'rtbProgress.Text &= Tex
            Dim lines As String() = rtbProgress.Lines
            lines(rtbProgress.Lines.Count - 1) = Tex
            rtbProgress.Lines = lines
        ElseIf Strings.Left(Tex, 9) = "Progress:" Then
            'rtbProgress.Text &= Tex
            Dim lines As String() = rtbProgress.Lines
            lines(rtbProgress.Lines.Count - 1) = Tex
            rtbProgress.Lines = lines
            If Tex = "Progress: 100%" Then
                rtbProgress.Text &= Environment.NewLine
            End If
        ElseIf Tex.EndsWith("%") Then
            'rtbProgress.Text &= Tex
            Dim lines As String() = rtbProgress.Lines
            lines(rtbProgress.Lines.Count - 1) = Tex
            rtbProgress.Lines = lines
        Else
            rtbProgress.Text &= Tex & vbCrLf
        End If
    End If
End Sub


In places where I can just append I can just use the method as is but in the case of having to subtract the last line then add the new line I'm not sure how I could invoke your method. Would you have any ideas how I could do this?

I need to add limits because after a 1000 lines or so it causes the application to become unstable. If you have other suggestions how to handle this I am open to any options. Thanks.
QuestionWhat if the new lines come from another thread? Pin
Member 147391388-Feb-20 17:59
Member 147391388-Feb-20 17:59 
AnswerRe: What if the new lines come from another thread? Pin
DiponRoy9-May-20 3:31
DiponRoy9-May-20 3:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.