title: Automatically resize a form with a TableLayoutPanel that is populated dynamically with controls in its cells
body: <p>I've a form with a TableLayoutPanel inside it, it have 1 row and 1 column. I populate this TableLayoutPanel dinamically with controls. </p>
  
  <p>First i create the table with: </p>
  
  <pre><code> 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 &lt; columnCount; x++)
              {
                  //First add a column
                  tblLayout.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
  
                  for (int y = 0; y &lt; 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));
                      }
                  }
              }
          }
  </code></pre>
  
  <p>then add controls in its cells:</p>
  
  <pre><code>tblLayout.Controls.Add(my_control, column, row);
  </code></pre>
  
  <p>i've also create this function to resize the form on the basis of the number of row and column of the TableLayoutPanel.</p>
  
  <pre><code>private void forceSizeLocationRecalc()
          {
  
              this.Height = 0;
              this.Width = 0;
  
              int col = this.tblLayout.ColumnCount;
              int row = this.tblLayout.RowCount;
  
              for (int i = 0; i &lt; row; i++)
              {
                  this.Height += this.tblLayout.GetControlFromPosition(0, i).Height;
              }
  
              for (int i = 0; i &lt; col; i++)
              {
                  this.Width += this.tblLayout.GetControlFromPosition(i, 0).Width;
              }
          }
  </code></pre>
  
  <p>and call it at the end of the setup of the form. </p>
  
  <p>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. </p>
  
  <p>Any idea?</p>
  
  <p>thanks</p>