C# – Adding a row after adding columns using TableLayoutPanel

cnetwinforms

I'm attempting to dynamically add both columns and rows to a TableLayoutPanel. I have the following code so far:

 l = new Label();
 l.Text = "" + headers[headers.Count-1];
 ColumnStyle cStyle = new ColumnStyle(SizeType.AutoSize);
 theTable.ColumnStyles.Add(cStyle);
 theTable.Controls.Add(l, colCount, 0);
 colCount++;

Which is adds all the columns I need. I then try to switch to adding rows by using:

theTable.GrowStyle = TableLayoutPanelGrowStyle.AddRows;

But this doesn't work. It instead takes the columns I added and makes them into rows. Is there a way to dynamically create Columns and then dynamically create rows?

Thanks

Best Answer

I couldn't reproduce your problem:

private void AddTLP()
{
  List<string> headers = new List<string>();
  headers.Add("Column 1");
  headers.Add("Column 2");
  headers.Add("Column 3");

  TableLayoutPanel tlp = new TableLayoutPanel();
  tlp.Size = new Size(356, 120);
  tlp.BackColor = Color.Gray;

  for (int i = 0; i < headers.Count; i++)
  {
    Label l = new Label();
    l.Text = headers[i].ToString();

    ColumnStyle cStyle = new ColumnStyle(SizeType.AutoSize);
    tlp.ColumnStyles.Add(cStyle);
    tlp.Controls.Add(l, i, 0);
  }

  tlp.GrowStyle = TableLayoutPanelGrowStyle.AddRows;

  // Add controls to test growth:
  tlp.Controls.Add(new Button(), 0, 1);
  tlp.Controls.Add(new TextBox(), 1, 2);

  this.Controls.Add(tlp);
}

There must be some code you aren't showing that is causing the problem.