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:
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With