我有一个包含TableLayoutPanel的表单,它有1行1列。我用控件动态地填充这个TableLayoutPanel。
首先,我使用以下命令创建表:
private void generateTable(int columnCount, int rowCount)
{
//Clear out the existing controls, we are generating a new table layout
tblLayout.Controls.Clear();
//Clear out the existing row and column styles
tblLayout.ColumnStyles.Clear();
tblLayout.RowStyles.Clear();
//Now we will generate the table, setting up the row and column counts first
tblLayout.ColumnCount = columnCount;
tblLayout.RowCount = rowCount;
for (int x = 0; x < columnCount; x++)
{
//First add a column
tblLayout.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
for (int y = 0; y < rowCount; y++)
{
//Next, add a row. Only do this when once, when creating the first column
if (x == 0)
{
tblLayout.RowStyles.Add(new RowStyle(SizeType.AutoSize));
}
}
}
}
然后在其单元格中添加控件:
tblLayout.Controls.Add(my_control, column, row);
我还创建了这个函数,根据TableLayoutPanel的行数和列数调整表单的大小。
private void forceSizeLocationRecalc()
{
this.Height = 0;
this.Width = 0;
int col = this.tblLayout.ColumnCount;
int row = this.tblLayout.RowCount;
for (int i = 0; i < row; i++)
{
this.Height += this.tblLayout.GetControlFromPosition(0, i).Height;
}
for (int i = 0; i < col; i++)
{
this.Width += this.tblLayout.GetControlFromPosition(i, 0).Width;
}
}
并在表单设置结束时调用它。
问题是,例如,如果我首先有一个行( tableLayout,col=2),而i传递给一个表布局是(row=3= 3,row=3= 1)的情况,那么表单的尺寸与前一个相同,所以我必须手动调整表单的大小。我希望我的表单自动调整大小的列数和行数的基础上。
有什么想法吗?
谢谢
发布于 2015-01-13 21:03:54
假设我没有理解错,请确保tblLayout
设置了它的自动大小属性,然后用以下代码替换函数forceSizeLocationRecalc
:
private void forceSizeLocationRecalc()
{
this.Width = this.tblLayout.Width;
this.Height = this.tblLayout.Height;
}
这将强制窗体采用表格布局面板的大小。显然,当表发生变化时,您仍然需要手动调用此函数。
您可以在构建表格布局面板的位置添加以下内容,以避免不得不这样做:
this.tblLayout.SizeChanged += delegate { this.forceSizeLocationRecalc(); };
希望这能有所帮助!
发布于 2018-01-03 00:14:36
将TableLayoutPanel和Form AutoSize属性设置为true。这意味着TableLayoutPanel将根据其内容(添加的控件)的大小自动调整大小,窗体将根据其内容( TableLayoutPanel)自动调整大小。
如果调整大小没有自动完成或看起来不稳定,您可以使用SuspendLayout、ResumeLayout和PerformLayout方法来控制何时调整大小。
https://stackoverflow.com/questions/27919893
复制相似问题