Reputation: 340
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 :
9 buttons :
Upvotes: 0
Views: 959
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