Jonathon Reinhart Jonathon Reinhart - 2 months ago 14
C# Question

Docking multiple controls - one fills remaining space

I'm trying to dock N number of controls in a container. I want them all to fill the entire width, but stack. I want one particular control (currently the last one) to fill the remaining space, while all others have fixed sizes.

This:

Button b1 = new Button() { Text = "Button 1", Dock = DockStyle.Top };
Button b2 = new Button() { Text = "Button 2", Dock = DockStyle.Top };
Button b3 = new Button() { Text = "Button 3", Dock = DockStyle.Fill };

Controls.Add(b1);
Controls.Add(b2);
Controls.Add(b3);


Produces this:

Button 3 filling entire parent

As you can see, Button 3 is doing exactly what I told it to:
Fill
the parent. But that's not what I want it to do. Aside from manually placing, and handling resize events, etc. how can I make Button 3 fill the remaining space?

Note: I am not using the designer.

Answer

While adding b3.BringToFront() (after it has been added to Controls) works, the simplest solution here, is to simply change the order in which the buttons are added to Controls. The following code works perfectly:

Button b1 = new Button() { Text = "Button 1", Dock = DockStyle.Top };
Button b2 = new Button() { Text = "Button 2", Dock = DockStyle.Top };
Button b3 = new Button() { Text = "Button 3", Dock = DockStyle.Fill };

Controls.Add(b3);    // this guy first!
Controls.Add(b1);
Controls.Add(b2);

The result:

enter image description here

If you take a close look at the borders in this little example, this actually seems to work better than BringToFront().

Comments