Dynamically Generating A TableLayoutPanel

The TableLayoutPanel in .NET is a great control for organizing other controls on a Windows form.  We here at ImageSource use it all of the time.  Most developers just generate all of the rows and columns from designer and never mess with the control again at runtime.   Unlike the ListBox and ListView controls,changing the Rows and Columns at runtime is not immediately obvious in the TableLayoutPanel. The following set of code will demonstrate will demonstrate a way to accomplish this non-intuitive task.

First, we start with a very basic form with a TableLayoutPanel added to it:

Empty TableLayoutPanel

Empty TableLayoutPanel

Next, I add the following code to the form:

private void GenerateTable(int columnCount, int rowCount)
{
   //Clear out the existing controls, we are generating a new table layout
   tableLayoutPanel1.Controls.Clear();

   //Clear out the existing row and column styles
   tableLayoutPanel1.ColumnStyles.Clear();
   tableLayoutPanel1.RowStyles.Clear();

   //Now we will generate the table, setting up the row and column counts first
   tableLayoutPanel1.ColumnCount = columnCount;
   tableLayoutPanel1.RowCount = rowCount;

   for (int x = 0; x < columnCount; x++)
   {
      //First add a column
      tableLayoutPanel1.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)
         {
            tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));
         }

         //Create the control, in this case we will add a button
         Button cmd = new Button();
         cmd.Text = string.Format("({0}, {1})", x, y);         //Finally, add the control to the correct location in the table
         tableLayoutPanel1.Controls.Add(cmd, x, y);
      }
   }
}

This code, when run from our test application, will generate variable numbers of rows and columns withing the TableLayoutPanel.  Each cell will then have button inside, displaying the cell coordinates within the button text.

3 Column, 2 Row TableLayoutPanel

3 Column, 2 Row TableLayoutPanel

4 Column, 8 Row TableLayoutPanel

4 Column, 8 Row TableLayoutPanel

1 Column, 1 Row TableLayoutPanel

1 Column, 1 Row TableLayoutPanel

3 thoughts on “Dynamically Generating A TableLayoutPanel

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s