Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RichTextBox new Text append on top

Tags:

c#

winforms

I have a RichtTextBox in my C# application that shows a log to the user. The problem is that newly inserted text appends below the old text, but I want to append it on top of the old text.

For example, When I append the text "Newtext" it looks like this:

RichtTextBox:

|---------------------
|Oldtext             |
|Newtext             |
|---------------------

But it needs to look like this:

RichTextBox:

|---------------------
|Newtext             |
|Oldtext             |
|---------------------

This is the code I'm using for filling my RichTextBox:

public void DisplayLog(string logtext)
        {
            if (logtext != "")
            {
                if (this.txtLog.InvokeRequired && !txtLog.IsDisposed)
                {
                    Invoke(new MethodInvoker(delegate()
                        {
                            txtLog.AppendText(DateTime.UtcNow + ": " + logtext + "\n");
                        }));
                }
                else if (!txtLog.IsDisposed)
                {
                    txtLog.AppendText(DateTime.UtcNow + ": " + logtext + "\n");
                }
            }
        }

Can somebody help me out please?

Answer:

Inserting at top of richtextbox

like image 786
Max Avatar asked Dec 27 '22 08:12

Max


2 Answers

Use Insert

txtLog.Text =  txtLog.Text.Insert(0,DateTime.UtcNow + ": " + logtext + "\n");
like image 167
Derek Avatar answered Jan 10 '23 03:01

Derek


I think txtlog is the RichTextBox and you should prepend this.

To do this go at start using

txtlog .SelectionStart = 0;
txtlog .SelectionLength = 0;
txtlog .SelectedText = (DateTime.UtcNow + ": " + logtext + "\n");
like image 29
Rajeev Ranjan Avatar answered Jan 10 '23 04:01

Rajeev Ranjan