Title: Change control stacking order in C#
A control's stacking order is normally determined by the order in which you add the controls to a form. The first form is at the bottom of the stacking order, the next control is above the first, and so forth.
A control's SendToBack and BringToFront methods move a control to the back or front of the stacking order respectively. This example's Top Top and To Bottom buttons use the following code to move themselves to the front or back of the stacking order.
private void btnToTop_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
btn.BringToFront();
}
private void btnToBottom_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
btn.SendToBack();
}
The To Top buttons simply invoke their BringToFront methods, and the To Bottom buttons invoke their SendToBack methods.
You can also use the Controls collection's SetChildIndex method to change a control's position within the collection. The index 0 represents the front of the stacking order, and the index Controls.Count - 1 represents the back of the stacking order.
The example's Second To Top button uses the following code to make itself have index 1, making it the second-to-top control.
private void btnSecondToTop_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
btn.Parent.Controls.SetChildIndex(btn, 1);
}
Download the example to experiment with it and to see additional details.
|