86
votes

I'm looking for a way to control the order in which the items dock to the top of my control.

I've noticed as I add children to my control (in the designer, or through code), the newest child is always at the top. I'd like for the newer children to be on the bottom, and the oldest to be at the top.

Is there a way to do this through code? In the WinForms designer, RightClick->Order->BringToFront / SendToBack is doing something similar to what I want to do, but how can this be done programmatically?

8
Thank you; I needed to programmatically control the docking and I didn't even realize that their order controlled how they docked.Eagle-Eye

8 Answers

152
votes

Go to View → Other windows → document outline.

In that window drag the controls so the docking is as you like it to be.

82
votes

Use these methods:

myControl.SendToBack();
myControl.BringToFront();
13
votes

As you said, the newest control added to the controls collection is the one on top. If you need a newer control to be added at the bottom, I'll suggest to create a list of controls, add the controls to the list, reverse the list and add the list to the controls collection.

List<Control> controls = new List<Control();
controls.Add(new myFirstControl());
controls.Add(new mySecondControl());
controls.Reverse();
this.Controls.AddRange(controls.ToArray());
6
votes

A control has two methods to achieve what you are looking for: BringToFront and SendToBack.

4
votes

The order in which the controls are being added to the Controls collection determines the docking order.

3
votes

(For the sake matter of showing another option): In Visual Studio 2012 (and later):

  1. Select the Control you want to Move to the Front (or back);
  2. Click in the below marked buttons (Bring to Front / Send to Back); enter image description here

This will give you the possibility to rearrange the Controls to your desired order.

3
votes

Note that when doing this programmatically, then there's a very easy way to achieve this, namely:

containerPanel.Controls.SetChildIndex(Element, 0); //sends element to the bottom of the list
-4
votes

Use the FlowLayoutPanel it does exactly what you want.