1
votes

I'm trying to create an autosizing button grid using a TableLayoutPanel. When I add columns at runtime with the following code they are not being sized evenly:

tableLayoutPanel.ColumnCount += 1;
for (var i = 0; i < tableLayoutPanel.RowCount; i++) {
    var button = new Button {
        Margin = Padding.Empty,
        Padding = Padding.Empty,
        Dock = DockStyle.Fill
    }
    tableLayoutPanel.Controls.Add(button);
}

The initial form with 1 column:

1col

Adding a 2nd column:

2col

Adding a 3rd column:

3col

Is there a way to make the columns autosize evenly without manually calculating the dimensions?

1
You did not configure the column styles correctly. Best way to do it first is with the designer, it makes it obvious that Absolute vs Percent is an option. Look at the auto-generated code in InitializeComponent() to know how to do it. Or keep it. - Hans Passant

1 Answers

0
votes

It's necessary to explicitly reset the column styles:

private void RecalculateColumnStyles()
{
    var cols = tableLayoutPanel.ColumnCount;
    var pct = (float) 100 / cols;
    tableLayoutPanel.SuspendLayout();
    tableLayoutPanel.ColumnStyles.Clear();
    for (var i = 0; i < cols; i++) {
        tableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, pct));
    }
    tableLayoutPanel.ResumeLayout();
}