Keytrap
Keytrap

Reputation: 340

Add controls to a form to fill it

Let's say I have X number of buttons to add to my Form programmatically;

What I would like is that all the controls have the same size and that they fill the form completely depending on the form size, for example with 4 buttons :

enter image description here

9 buttons :

enter image description here

Upvotes: 0

Views: 959

Answers (1)

Stefano d'Antonio
Stefano d'Antonio

Reputation: 6152

To layout controls you can use a TableLayoutPanel

var tableLayoutPanel = new TableLayoutPanel
{
    Dock = DockStyle.Fill,
    RowCount = 2,
    ColumnCount = 2
};

tableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 50));
tableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 50));
tableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50));
tableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50));

tableLayoutPanel.Controls.Add(new Button { Dock = DockStyle.Fill });
tableLayoutPanel.Controls.Add(new Button { Dock = DockStyle.Fill });
tableLayoutPanel.Controls.Add(new Button { Dock = DockStyle.Fill });
tableLayoutPanel.Controls.Add(new Button { Dock = DockStyle.Fill });

yourForm.Controls.Add(tableLayoutPanel);

It will also keep the aspect if you resize the form.

Upvotes: 4

Related Questions