Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I automatically scroll to the bottom of a multiline text box?

I have a textbox with the .Multiline property set to true. At regular intervals, I am adding new lines of text to it. I would like the textbox to automatically scroll to the bottom-most entry (the newest one) whenever a new line is added. How do I accomplish this?

like image 251
GWLlosa Avatar asked May 22 '09 14:05

GWLlosa


People also ask

How do you create a scrolling text box?

Right-click the control for which you want to set a text-scrolling option, and then click Control Properties on the shortcut menu. Click the Display tab. In the Scrolling list, click the text-scrolling option that you want.

How do I auto scroll to the bottom in HTML?

To auto scroll a page from top to bottom we can use scrollTop() and height() method in jquery. In this method pass the document's height in scrollTop method to scroll.


2 Answers

At regular intervals, I am adding new lines of text to it. I would like the textbox to automatically scroll to the bottom-most entry (the newest one) whenever a new line is added.

If you use TextBox.AppendText(string text), it will automatically scroll to the end of the newly appended text. It avoids the flickering scrollbar if you're calling it in a loop.

It also happens to be an order of magnitude faster than concatenating onto the .Text property. Though that might depend on how often you're calling it; I was testing with a tight loop.


This will not scroll if it is called before the textbox is shown, or if the textbox is otherwise not visible (e.g. in a different tab of a TabPanel). See TextBox.AppendText() not autoscrolling. This may or may not be important, depending on if you require autoscroll when the user can't see the textbox.

It seems that the alternative method from the other answers also don't work in this case. One way around it is to perform additional scrolling on the VisibleChanged event:

textBox.VisibleChanged += (sender, e) => {     if (textBox.Visible)     {         textBox.SelectionStart = textBox.TextLength;         textBox.ScrollToCaret();     } }; 

Internally, AppendText does something like this:

textBox.Select(textBox.TextLength + 1, 0); textBox.SelectedText = textToAppend; 

But there should be no reason to do it manually.

(If you decompile it yourself, you'll see that it uses some possibly more efficient internal methods, and has what seems to be a minor special case.)

like image 152
Bob Avatar answered Sep 16 '22 14:09

Bob


You can use the following code snippet:

myTextBox.SelectionStart = myTextBox.Text.Length; myTextBox.ScrollToCaret(); 

which will automatically scroll to the end.

like image 28
GWLlosa Avatar answered Sep 17 '22 14:09

GWLlosa