Search code examples
c#winformsscrollablepanels

dynamic buttons on panel1 - locations


So I have an app with a scrollable panel, which lists folders dynamically on the panel. Below the folder listings, I also have a button. Once a click on the button, it dynamically creates a button next to each folder listing. My Y value for each button increases every time with =+ 26 - this all works fine if my panel is not scrollable yet. Once the panel becomes scrollable and I scroll down and then continue adding more buttons, it jumps a few spaces and then only adds more buttons. I assume it is something to do with the scrolling which changes to Y location? How can I work past this?

C# WinForms

Thanks and regards.

private void button1_Click(object sender, EventArgs e)
{
    Button newButton = new Button();
    newButton.Location = new System.Drawing.Point(0, (y+6));
    buttons.Add(newButton);
    y += 20;
    panel1.Controls.Add(newButton);
}

Solution

  • Just replace your dynamic button lines with the following:

    panel1.AutoScroll = true;
            Button myButton = new Button();
            myButton.Location = new Point(
               panel1.AutoScrollPosition.X,
               panel1.AutoScrollPosition.Y + (y+6));
            y += 20;
            panel1.Controls.Add(myButton);