I am trying to create a ‘log display’ using the richtextbox control in C#.NET.
public void logLine(string line)
{
rtxtLoginMessage.AppendText(line + "\r\n");
}
Is there a way to display the text in reverse order/upwards? (where the newest log and date will be displayed at the top)
Your help is much appreciated.
Short Answer
You want to set the selection to 0 and then set the
SelectedTextproperty.Long Answer
How did I work this out?
Using Reflector, search for the RichTextBox control and find the
AppendTextmethod (follow the base types toTextBoxBase). Have a look at what it does (below for convenience).You will see that it finds the end position, sets the internal selection, and then sets the
SelectedTextto the new value. To insert text at the very beginning you simply want to find the start position instead of the end position.Now, so you do not have repeat this piece of code for each time you want to prefix text you can create an Extension Method.
Note: I’m only using the
Try/Finallyblock to match the implementation ofAppendText. I’m not certain as why we would want to restore the initial selection if theWidthorHeightis 0 (if you do know why, please leave a comment as I’m interested in finding out).Also, there is some contention to using “Prepend” as the opposite for “Append” as the direct English definition is confusing (do a Google search – there are several posts on the topic). However, if you look at the Barron’s Dictionary of Computer Terms it has become an accepted use.
HTH,
Dennis