c# multiple controls - Panel.Dock Fill ignoring other Panel.Dock setting

4 Answers

Right click on the panel with Dock=Fill and click 'Bring to Front'.

This makes this control be created last, which takes into account the Dock settings on other controls in the same container.

vs anchor form

If you create a panel on a form and set it to Dock=Top and drop another panel and set its Dock=Fill, it may fill the entire form, ignoring the first panel. Changing the tab order does nothing.

I've had the same problem and I managed to solve it.
If you have a container with DockStyle.Fill the others should also have DockStyle but Top or whatever you want.
The important thing is to add the control with DockStyle.Fill first in Controls then the others.


ComboBox cb = new ComboBox();
cb.Dock =  DockStyle.Top;

GridView gv = new GridView();
gv.Dock =  DockStyle.Fill;

Controls.Add(gv); // this is okay

but if we put cb first

Controls.Add(gv); // gv will overlap the combo box.

If you don't want to change the order of the elements inside the code, you can use the method Container.Controls.SetChildIndex() with Container being the e.g. Form, Panel etc. you want do add your controls to.


     //Container ------------------------------------
     Panel Container = new Panel();

     //Top-Docked Element ---------------------------
     ButtonArea = new FlowLayoutPanel();
     Container.Controls.SetChildIndex(ButtonArea, 1);
     ButtonArea.Dock = DockStyle.Top;

     //Fill-Docked Element --------------------------
     box = new RichTextBox();
     Container.Controls.SetChildIndex(box, 0); //setting this to 0 does the trick
     box.Dock = DockStyle.Fill;

I ran into the same issue. Mine was with adding new/custom controls below the menu strip during run time. The problem was the controls when docked, decided to dock from the top of the form and completely ignoring the menu strip entirely, very annoying if you ask me. As this had to be done dynamically with code and not during design mode this became extremely frustrating. The simplest way I found is to create a panel during design mode and dock below the menu strip. From there you can just add/remove the controls to the panel and you can dock it during run time. No need to mess with all your controls on your form that do not really need to change, too much work depending on what you really need to do.

object.dock = Fill