简体   繁体   中英

How do I apply column and row styles on a TableLayoutPanel programmatically?

In the beginning there is a TableLayoutPanel with only one row and no columns. By the press of a button I want this panel to be transformed with 5 rows and 3 columns .

private void button_Click(object sender, EventArgs e)
    {
        this.tableLayoutPanel1.ColumnCount = 3;
        this.tableLayoutPanel1.RowCount = 5;
    }

The problem is that you get this as a result!

在此处输入图片说明

The boxes that are created with the rows and columns do not contain the same area in the panel, as you can see.

In the case of 3 columns and 5 rows, the columns must share the 100% of the tablelayoutpanel, so 30% per each. In the case of 5 rows, each row must take 20%.

So I append to the button_Click method the next two lines of code.

this.tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30F));
this.tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 20F));

But I get the same result! What I am missing?

Probably you are adding styles to an already defined TableLayoutPanel without resetting the current styles.

tableLayoutPanel1.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;
tableLayoutPanel1.Dock = DockStyle.Fill;

tableLayoutPanel1.Controls.Clear();
tableLayoutPanel1.ColumnStyle.Clear();
tableLayoutPanel1.RowStyle.Clear();

tableLayoutPanel1.RowCount = 5;
for(int x = 0; x < tableLayoutPanel1.RowCount; x++)
    tableLayoutPanel1.RowStyles.Add(new RowStyle() { Height = 20, SizeType = SizeType.Percent });
tableLayoutPanel1.ColumnCount = 3;
for(int x = 0; x < tableLayoutPanel1.ColumnCount; x++)
    tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle() { Width = 33, SizeType = SizeType.Percent });

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