Add controls dynamically in flowlayoutpanel

Karlx Swanovski picture Karlx Swanovski · Jun 3, 2013 · Viewed 67.9k times · Source

In a windows form, I can add control dynamically by doing this:

for (int i = 0; i < 5; i++)
{
    Button button = new Button();
    button.Location = new Point(160, 30 * i + 10);

    button.Tag = i;
    this.Controls.Add(button);
}

How do I add controls dynamically in a FlowLayoutPanel?

Answer

Idle_Mind picture Idle_Mind · Jun 3, 2013

For a FlowLayoutPanel, you don't need to specify a .Location since the controls are arranged for you:

Represents a panel that dynamically lays out its contents horizontally or vertically. ... The FlowLayoutPanel control arranges its contents in a horizontal or vertical flow direction. Its contents can be wrapped from one row to the next, or from one column to the next.

Just change "flowLayoutPanel1" to the name of your FlowLayoutPanel:

for (int i = 0; i < 5; i++)
{
    Button button = new Button();
    button.Tag = i;
    flowLayoutPanel1.Controls.Add(button);
}