asmith3006 0 Light Poster

Hi.
Is it possible to add new rows and columns to the table layout panel at runtime?

I want to create a table of text boxes, but I don't know how many rows or columns will be needed.

Also, is it possible to add rows and/or columns at the click of a button?

Thanks for any and all help.

Andrew.

Dani AI

Generated

— Yes. If you mean the Windows Forms TableLayoutPanel, you can add rows and columns at runtime by changing RowCount/ColumnCount, adding the appropriate RowStyle/ColumnStyle, and then placing controls with Controls.Add(control, column, row). Rows and columns are zero-based, and using Dock = DockStyle.Fill or Anchor makes textboxes size correctly inside cells.

Example: add a new row and put a TextBox into column 0 of that row.

int newRow = tableLayoutPanel1.RowCount;
tableLayoutPanel1.RowCount = newRow + 1;
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));
var tb = new TextBox();
tb.Dock = DockStyle.Fill;
tableLayoutPanel1.Controls.Add(tb, 0, newRow);

To add a column, do the same for ColumnCount and ColumnStyles. You can also set tableLayoutPanel1.GrowStyle = TableLayoutPanelGrowStyle.AddRows (or AddColumns) so the panel will grow automatically when controls are added without explicit coordinates. Use TableLayoutPanel.SetColumnSpan/SetRowSpan for spanning cells.

Notes and troubleshooting:

  • There is no built-in RemoveRow method. To remove a row you must remove controls in that row, shift controls in lower rows up with SetRow, then decrement RowCount and remove the last RowStyle.
  • Wrap bulk changes in SuspendLayout()/ResumeLayout() and call PerformLayout() to avoid flicker and improve performance.
  • If the layout looks wrong, verify you added a matching RowStyle/ColumnStyle for each new index and check SizeType (AutoSize, Percent, Absolute).

If you are targeting ASP.NET WebForms instead of WinForms, the runtime pattern is different (create TableRow/TableCell and add them to a Table control). See the Microsoft docs for details: TableLayoutPanel (WinForms).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.