Advanced 12 min read Control #25

TableLayoutPanel Control

TableLayoutPanel arranges controls in a grid of rows and columns. Perfect for creating complex, responsive layouts.

What is a TableLayoutPanel?

TableLayoutPanel organizes controls in a grid. You can add rows and columns, and controls will be placed in cells. It's perfect for forms, dashboards, and any UI that needs a structured layout.

Code Example

// Configure TableLayoutPanel
tableLayoutPanel1.Dock = DockStyle.Fill;
tableLayoutPanel1.ColumnCount = 3;
tableLayoutPanel1.RowCount = 3;

// Set column styles
tableLayoutPanel1.ColumnStyles[0] = 
    new ColumnStyle(SizeType.Percent, 30);
tableLayoutPanel1.ColumnStyles[1] = 
    new ColumnStyle(SizeType.Percent, 40);
tableLayoutPanel1.ColumnStyles[2] = 
    new ColumnStyle(SizeType.Percent, 30);

// Add controls to cells
Label lbl = new Label();
lbl.Text = "Name:";
tableLayoutPanel1.Controls.Add(lbl, 0, 0); // Column 0, Row 0

TextBox txt = new TextBox();
txt.Dock = DockStyle.Fill;
tableLayoutPanel1.Controls.Add(txt, 1, 0); // Column 1, Row 0

// Span multiple columns
tableLayoutPanel1.SetColumnSpan(txt, 2);

Exercise

Task: Create a registration form with TableLayoutPanel.

  1. Add a TableLayoutPanel with 2 columns and 5 rows.
  2. Column 1: Labels (First Name, Last Name, Email, Phone).
  3. Column 2: TextBoxes for user input.
  4. Row 4: Buttons (Submit, Cancel) spanning both columns.
  5. Make the form resize gracefully.
  6. Add a GroupBox in one cell.
Key Takeaway

TableLayoutPanel creates grid-based layouts. Use it for forms, dashboards, and complex UI arrangements that need to resize properly.