c# – How to make all cells in tableLayoutPanel the same size?

Question:

Hello. My goal is to make all the cells of the tableLayout same size, and so that they remain the same even when adding / removing a column or row. Tried doing AutoSize = true but it didn't help.

Actually the goal: during the execution of the program, the user enters the number of rows and columns, I create a corresponding tableLayout, with cells that are completely identical in size.

Answer:

The WinForms designer automatically sets values ​​for some of the TableLayoutPanel properties that get in the way. Therefore, to simplify the solution, I propose to create it manually with code. For example, in the form constructor (but you can in the Form.Load event):

TableLayoutPanel tableLayoutPanel;

public Form1()
{
    InitializeComponent();

    tableLayoutPanel = new TableLayoutPanel
    {
        Parent = this,
        CellBorderStyle = TableLayoutPanelCellBorderStyle.Inset,
        AutoSize = true,
        AutoSizeMode = AutoSizeMode.GrowAndShrink
    };
}

Instead of the form ( this ), you can specify any other container as a parent. I set the CellBorderStyle just for clarity, so that the cells are visible.

Next, somewhere in the code, we set the number of columns and rows:

tableLayoutPanel.ColumnCount = 5;
tableLayoutPanel.RowCount = 3;

After that, we assign styles to the columns and rows with the required sizes:

for (int i = 0; i < 5; i++)
    tableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 30));

for (int i = 0; i < 3; i++)
    tableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 30));

SizeType.Absolute means the dimensions are in pixels.

Accordingly, as the number of cells increases, you need to add styles for new columns and rows. And you can initially set them with a margin.


Alternatively, instead of specifying styles, you can place a control of a given size in each cell, for example, a panel. She will expand the cell to its size:

for (int i = 0; i < 5 * 3; i++)
    tableLayoutPanel.Controls.Add(new Panel { Size = new Size(30, 30) });
Scroll to Top