sashoalm sashoalm - 4 months ago 33
C# Question

Expandable column using TableLayoutPanel (from code)

I'm trying to make the middle column of a 3-column TableLayoutPanel expandable. I'm doing it everything from code, not the designer, as a learning exercise.

The middle column has a text box and the left and right columns have a button each:

enter image description here

As you can see from the screenshot, the 2nd column is not expandable yet.

I'm following the advice from http://stackoverflow.com/a/22283690/492336 - I set the TextBox control's Dock to Fill, and also the panel's Dock to Fill as well:

var panel = new TableLayoutPanel();
panel.RowCount = 1;
panel.ColumnCount = 3;
panel.Controls.Add(new Button());
panel.Controls.Add(new TextBox());
panel.Controls.Add(new Button());
panel.Controls[0].Text = "Button1";
panel.Controls[2].Text = "Button2";
panel.Controls[1].Dock = DockStyle.Fill;
panel.Dock = DockStyle.Fill;


I also tried the suggestion from http://stackoverflow.com/a/7279996/492336 by setting the columns to
AutoSize
:

panel.ColumnStyles.Clear();
panel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
panel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
panel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));


But that had no effect as well.

What am I doing wrong here?

Answer

If you want to the middle column expand and occupy all remaining space in TableLayoutPanel, perform this settings on your controls:

  • Set the first and the last column style to be AutoSize.
  • Set the middle column style to be Percent with value 100.
  • Set the Dock property of TextBox to be Fill.

This way the middle column will expand to fill remaining space of TableLayoutPanel. Now if you want to TableLayoutPanel occupy all width of Form, you can set it's Dock property to Fill or Top. Also you can make it larger and set suitable Anchor for it to change it's size based in Form size.

var panel = new TableLayoutPanel();
panel.RowCount = 1;
panel.ColumnCount = 3;
panel.Controls.Add(new Button());
panel.Controls.Add(new TextBox());
panel.Controls.Add(new Button());
panel.Controls[0].Text = "Button1";
panel.Controls[2].Text = "Button2";
panel.Controls[1].Dock = DockStyle.Fill;
panel.Dock = DockStyle.Fill;

panel.ColumnStyles.Clear();
panel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); // This is the changed part
panel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));