0

I'm adding controls to Winforms TableLayoutPanel using panel.Controls.Add(control) at runtime.

I need to arrange the controls in two columns with variable number of rows by first filling the first and then the second column to achieve the following layout:

C1 C4
C2 C5
C3 C6

No matter how I configure the panel it is always populated in the following order:

C1 C2
C3 C4
C5 C6

How can I change the order of control insertion?

jackhab
  • 17,128
  • 37
  • 99
  • 136
  • Take a look at [this post](https://stackoverflow.com/a/33969228/3110834) or [the other one](https://stackoverflow.com/a/34426939/3110834) to learn how you can arrange controls in a grid layout at run-time. – Reza Aghaei Jan 25 '22 at 13:35
  • And of course consider using DataGridView if possible. – Reza Aghaei Jan 25 '22 at 20:52

1 Answers1

0

Use the second overload of tableLayoutPanel1.Controls.Add() in order to pass the row and column index: public virtual void Add(Control control, int column, int row);

EXAMPLE:

private void SetTableLayoutPanel()
{
    tableLayoutPanel1.RowStyles.Clear();
    tableLayoutPanel1.ColumnCount = 2;
    tableLayoutPanel1.RowCount = 3;
    tableLayoutPanel1.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;

    var counter = 1;
    for (int i = 0; i < tableLayoutPanel1.ColumnCount; i++)
    {
        for (int j = 0; j < tableLayoutPanel1.RowCount; j++)
        {
            Button b = new Button();
            b.Text = "C" + counter;
            tableLayoutPanel1.Controls.Add(b, i, j);

            counter++;
        }               
    }
}

OUTPUT:

enter image description here

Jonathan Applebaum
  • 5,738
  • 4
  • 33
  • 52