Press "Enter" to skip to content

Lesson 19.1 – Scroll to the bottom of a rich text box

When you play the game, you probably noticed the messages RichTextBox scrolls to the top after you add more messages to it. So, the player has to manually scroll to the bottom to see the latest message.

We want to make it easier for the player.

 

How to scroll to the bottom of a RichTextBox

Step 1: Add this new ScrollToBottomOfMessages() function to the code in the SuperAdventure.cs class:

private void ScrollToBottomOfMessages()
{
    rtbMessages.SelectionStart = rtbMessages.Text.Length;
    rtbMessages.ScrollToCaret();
}

 

Step 2: After you add more to rtbMessages.Text, call the ScrollToBottomOfMessages() method.

 

That’s it.

 

Source code for this lesson

Source code on GitHub

Source code on Dropbox

 

Next lesson: Lesson 19.2 – Use a calculated value for a property

Previous lesson: Lesson 18.1 – Future enhancements for the game

All lessons: Learn C# by Building a Simple RPG Index

6 Comments

  1. ZzM
    ZzM January 4, 2015

    Hello,
    I just double-clicked on the rtbMessages RichTextBox and it created the function:
    private void rtbMessages_TextChanged(object sender, EventArgs e)

    I added:
    rtbMessages.SelectionStart = rtbMessages.Text.Length;
    rtbMessages.ScrollToCaret();

    Now i don’t have to insert a function everytime it changes the text

    • Scott Lilly
      Scott Lilly January 6, 2015

      Cool. That’s one nice thing about programming – there’s always another way to do something.

  2. Senpai
    Senpai August 10, 2015

    Hey Scott,

    great tutorial so far, helped me a lot understanding the basics of C#.

    Just want to let you know that next and previous lesson are mixed up :p

    Thanks again.

    Have a nice day!

    • Scott Lilly
      Scott Lilly August 10, 2015

      Thanks for catching that and letting me know. You have a good day too!

  3. Conner
    Conner November 30, 2016

    When checking out this idea, I instead made a DisplayMessage function

    private void DisplayMessage(string msg)
    {
    rtbMessages.Text += msg;
    rtbMessages.SelectionStart = rtbMessages.Text.Length;
    rtbMessages.ScrollToCaret();
    }

    Is that a good idea for potential refactoring?

    I was thinking yes due to how you could constantly change where the messages were displayed

    • Scott Lilly
      Scott Lilly December 1, 2016

      Yes! You found an excellent opportunity for refactoring. When you do something in multiple places, it’s almost always better to call a common function.

Leave a Reply

Your email address will not be published. Required fields are marked *