Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll a panel to the bottom in c#?

Tags:

I have a panel MessagesPanel that contains messages which are retrieved from a database. I go over the messages using a foreach loop. In the loop, I call a function AddMessageToPanel which dynamically adds a GroupBox to the panel, with the message information and content. The messages are retrieved oldest to newest, top to down (Like in WhatsApp). The panel is set to AutoScroll=true, and I want it to scroll to the very bottom to the newest message. I tried those solutions:

  1. autoscroll panel to bottom
  2. How to Programmatically Scroll a Panel
  3. How to scroll a panel manually?

None of them worked for me. The panel just looks the same, with the scroll bar at the top.

In particular, I have tried the following codes:

private void MessagePanel_ControlAdded(object sender, ControlEventArgs e)
{
    MessagesPanel.ScrollControlIntoView(e.Control);
}

and I subscribe to it with the event ControlAdded.

And also:

MessagesPanel.VerticalScroll.Value = MessagesPanel.VerticalScroll.Maximum

With and without MessagesPanel.SuspendLayout();

Here is my function:

private void AddMessageToPanel(string sender, string datetime, string content)
{
    GroupBox groupBox = new GroupBox();
    groupBox.Location = new Point(0, 120 * MessagesPanel.Controls.Count);
    groupBox.RightToLeft = RightToLeft.Yes;
    groupBox.Size = new Size(500, 100);
    groupBox.Text = string.Format("{0} ({1})", sender, datetime);

    TextBox textBox = new TextBox();
    textBox.Enabled = false;
    textBox.BackColor = Color.White;
    textBox.BorderStyle = BorderStyle.None;
    textBox.Multiline = true;
    textBox.Size = new Size(495, 95);
    textBox.Location = new Point(0, 20);
    textBox.Text = content;

    groupBox.Controls.Add(textBox);
    MessagesPanel.Controls.Add(groupBox);
}

I want the MessagesPanel to scroll all the way down. How to do this? Thanks!

like image 878
Michael Haddad Avatar asked May 09 '16 13:05

Michael Haddad


1 Answers

As alternative to Beldi's solution, you can call

MessagesPanel.AutoScrollPosition = new Point(0, MessagesPanel.DisplayRectangle.Height);

after all the controls have been added to the panel.

like image 116
Gess Avatar answered Sep 28 '22 04:09

Gess