Home > Net >  Arranging controls in Winforms TableLayoutPanel
Arranging controls in Winforms TableLayoutPanel

Time:01-28

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?

CodePudding user response:

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

  •  Tags:  
  • Related