简体   繁体   中英

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 :

在此处输入图片说明

9 buttons :

在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM