Reputation: 407
I've a form with a TableLayoutPanel inside it, it have 1 row and 1 column. I populate this TableLayoutPanel dinamically with controls.
First i create the table with:
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));
}
}
}
}
then add controls in its cells:
tblLayout.Controls.Add(my_control, column, row);
i've also create this function to resize the form on the basis of the number of row and column of the 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;
}
}
and call it at the end of the setup of the form.
The problem is, if for example, i've first a tableLayout (col=2, row=3), and the i pass to a case in which table layout is (col = 3, row = 1) the dimension of the form is the same of the previous, so i've to resize the form manually. I would like that my form resizing automatically on the basis of columns number and rows number.
Any idea?
thanks
Upvotes: 2
Views: 4302
Reputation: 15
Set the TableLayoutPanel and Form AutoSize properties to true. This means the TableLayoutPanel is auto resized based on the size of it's contents (the controls being added) and the Form is auto resized based on it's contents (the TableLayoutPanel).
If the resizing does not get done automatically or looks jumpy you can use the SuspendLayout, ResumeLayout and PerformLayout methods to control when the resizing occurs.
Upvotes: 1
Reputation: 3698
Assuming I've understood you correctly, ensure tblLayout
has it's auto size properties set, and then replace the function forceSizeLocationRecalc
with this:
private void forceSizeLocationRecalc()
{
this.Width = this.tblLayout.Width;
this.Height = this.tblLayout.Height;
}
This will then force the form to take on the size of the table layout panel. Obviously you'll still need to call this manually when the table is changed.
You could add this where you construct the table layout panel to prevent having to do that:
this.tblLayout.SizeChanged += delegate { this.forceSizeLocationRecalc(); };
Hope that helps!
Upvotes: 2