Scroll to bottom of C# TextBox

C#WinformsTextbox

C# Problem Overview


I have a TextBox on a C# Forms Application. I populate the TextBox with information on the Load event of the form. I then call the following:

this.txtLogEntries.SelectionStart = txtLogEntries.Text.Length;
this.txtLogEntries.ScrollToCaret();

However the TextBox does not scroll to the bottom ?

This only applies to the Load event though. I also update this TextBox from other parts of the application once it's running, and as soon as one of these events update's the TextBox, it is scrolled to the bottom.

So, how can I get it to scroll to the bottom when pre populating the TextBox in the Form Load event?

C# Solutions


Solution 1 - C#

Try putting the code in the Form's Shown event:

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

Solution 2 - C#

While the Load event (occurs before the Form is shown) is processed, there is no form to display yet, and thus no visual state has been established. Scrolling a non-visible control therefore very likely doesn't do anything because—hey, there is nothing to scroll as a scrolling viewport is just a view on the control but not part of its state.

You may have more success with moving the scrolling part into the Shown event (occurs after the form is first shown) of the form

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSnAzBaZView Question on Stackoverflow
Solution 1 - C#bernhofView Answer on Stackoverflow
Solution 2 - C#JoeyView Answer on Stackoverflow