RICHTEXTBOX - ADD TEXT TO TOP WITH MULTIPLE COLORS (ONLY LATEST LINE IS SHOWING)

marcel ethan

Total Post:105

Points:735
Posted by  marcel ethan
C# 
C#
 1471  View(s)
Ratings:
Rate this:

I'm trying to replicate a log window, so the most recent log should appear at the top - most visible. Thus, I need to add a text to the top (no problem) but with multiple colors (problem).

First I store the original text. (it's rtf or text - tried both) And then I add the new text, with a username and then a message. The username should be one color and the message another. It's always single lined too.

All I get by my method is that when appending the old text or the old RTF text, the latest "log" only shows.

public void AddLog(Log log)

{

        try

        {

            string oldText = this.richTextBox1.Rtf;

            this.richTextBox1.Text = log.User + ": " + log.Message + "\n";

            this.richTextBox1.Select(0, log.User.Length);

            this.richTextBox1.SelectionColor = Color.GreenYellow;

            this.richTextBox1.Select(log.User.Length + 2, log.Message.Length);

            this.richTextBox1.SelectionColor = Color.White;

            this.richTextBox1.DeselectAll();

            this.richTextBox1.Rtf += oldText;

        }

        catch { }

}

Is this even possible? Because it doesn't save the old RTF text and the old RTF text can't be appended after the new text, which means I probably have to add newest text below which isn't what I want.

If I instead of saving the "RTF" text, the format (colors) will disappear and will only show one color.

  1. Sumit Kesarwani

    Post:378

    Points:2694
    Re: RichTextBox - Add text to top with multiple colors (only latest line is showing)

    Hi Marcel,


    Try this

    public void AddLog(Log log)

    {

        try

        {

            richTextBox1.SelectAll();           

            string oldText = this.richTextBox1.SelectedRtf;

            this.richTextBox1.Text = log.User + ": " + log.Message + "\n";

            this.richTextBox1.Select(0, log.User.Length);

            this.richTextBox1.SelectionColor = Color.GreenYellow;

            this.richTextBox1.Select(log.User.Length + 2, log.Message.Length);

            this.richTextBox1.SelectionColor = Color.White;

            this.richTextBox1.DeselectAll();

            this.richTextBox1.SelectionStart = this.richTextBox1.TextLength;

            this.richTextBox1.SelectedRtf = oldText;

            this.richTextBox1.DeselectAll();

        }

        catch { }

    }


Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!