代码及说明如下:
private void InitLayoutDemo()
{
TableLayoutPanel demoLayoutPanel = new TableLayoutPanel();
demoLayoutPanel.Dock = DockStyle.Fill;
this.Controls.Add(demoLayoutPanel);
int row = 3, col = 3;
DynamicLayout(demoLayoutPanel, row, col);
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
Button btn = new Button();
btn.Text = string.Format("({0},{1})", i, j);
btn.Dock = DockStyle.Fill;
demoLayoutPanel.Controls.Add(btn);
demoLayoutPanel.SetRow(btn, i);
demoLayoutPanel.SetColumn(btn, j);
}
}
}
///
/// 动态布局
///
/// 布局面板
/// 行
/// 列
private void DynamicLayout(TableLayoutPanel layoutPanel, int row, int col)
{
layoutPanel.RowCount = row; //设置分成几行
for (int i = 0; i < row; i++)
{
layoutPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 100F));
}
layoutPanel.ColumnCount = col; //设置分成几列
for (int i = 0; i < col; i++)
{
layoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
}
}
控件右上角有个小三角,点击后可以选择编辑行和列的属性,各行高度均等的话就要用百分比来设置了,进去看一下很简单的。