22

When we add any UI or container in WinForms, the later added component comes over the earlier added components, we can say it is in a higher layer.

How to change that layer order or component order after adding components?

double-beep
  • 5,031
  • 17
  • 33
  • 41
Moon
  • 19,518
  • 56
  • 138
  • 200

4 Answers4

32

When you place more than one control in the same place,one will end up on top,and the other will end up underneath.Usually this is the result of a minor mistake,such as incorrectly using the anchoring and docking features to creare resizable form.In some cases,however,you might want to overlap control for a specific effect.

When control overlap,it's the z-index that determines which control ends up on top.Essentially,every control existy in its own distinct numbered layer.A control that has the z-index layer 1 will appear above a control in z-index layer 2 if they overlap.Usually,the z-index of a group of controls is determined by the order in which you add the controls,so that the last control you add is always in the topmost layer (with a z-index of 0).

However, you can change these options.

To determine or set the z-index of a control , you can use the GetChildIndex() and SetChildIndex() methods of the Controls Collection.Here's an example that moves a control to the third layer in the z-index.

Controls.SetChildIndex(ctrl, 2);

Usually, you won't need this kind of find-grained control.Instead,you'll just want to drop a control to the back of the z-index (the bottom-most layer) or bring it to the top.You can accomplish this feature at design time by right clicking on a control and choosing Bring to Fron or Send to Back.You can also perform the same task programmatically using the Control.BringToFront() or Control.SendToBack() methods.

ctrl.BringToFront(); // This is equivalent to Controls.SetChildIndex(ctrl,0);
Myra
  • 3,646
  • 3
  • 38
  • 47
  • I found it helpful. Also found GetChildIndex to figure out at run time which control is on top. Thanks. – Noam Gal Dec 16 '09 at 10:39
29

Is it when you load components dynamically in code or in the designer? If it is in the designer you can use the Format -> Order -> Send to Back and Format -> Order -> Bring to Front commands. Send to Back and Bring to Front are also available in the context menu when you right-click a control, as well as in the "Layout" toolbar that should appear automatically when you work in the forms designer.

Fredrik Mörk
  • 155,851
  • 29
  • 291
  • 343
19

In the designer view, you can also open up the "Document Outline" panel to view a tree structure of your current form/control, and then drag components around, "up" and "down" to bring to front and back, and also in and out of containers.

Noam Gal
  • 3,315
  • 3
  • 36
  • 53
5

Did you try playing with the Z-Order ?

See Also: Control.SentToBack method - Most Winform controls should thereby support this.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Gishu
  • 134,492
  • 47
  • 225
  • 308