Select Page

The need for an autoscroll property…

Tons of applications are using the .NET RichTextBox for outputting status information. You have a RichTextBox that you just keep on adding text to. This is all very simple, but when the box is completely filled with text, further text added will no longer be visible, since the RichTextBox does not scroll along with the text. Wouldn’t it be nice if you could make it scroll along with the text automatically.

Well… You can.

Use the TextChanged event

Whenever you add (or change in any way) text to the RichTextBox the TextChanged event will fire immediately after the text has changed. Just double-click on the TextChanged event in the RichTextBox’ event list to add an event handler.
Now modify the code of the event handler to look like this:

private void richTextBox_TextChanged(object sender, EventArgs e)
{
  richTextBox.SelectionStart = richTextBox.Text.Length;
  richTextBox.ScrollToCaret();
}

This code uses the ScrollToCaret function to do the actual scrolling. The function will adjust the scroll of the box, so that the “caret” is visible (think of the caret as the blinking cursor). This of course requires that the caret is placed somewhere meaningfull. This is done by setting the SelectionStart property to the last character in the box. The result is that whenever the text in the RichTextBox changes the box will scroll to the very bottom.

While this method is perfect for your basic status information box, where information is always added to the bottom, it may not always be the proper solution. This method will reset any selection the user has made in the RichTextBox, so if you need to copy text out of the box and the text changes very often this is not really the way to go.

On the other hand it is a very simple and safe way of implementing “autoscroll” and i have used it in a lot of applications without any problems.