Learn how the Controls collection and the DockStyle of a control are related
When setting the DockStyle property on a control, the last
control added to the parent's Controls collection has the
highest priority of being docked. For example, if ControlA, ControlB, and
ControlC are all added to a Panel in their respective order, and all
three controls have a DockStyle of DockStyle.Top,
then ControlC will be the topmost control. Conversely, if all three
controls have a DockStyle of DockStyle.Bottom,
then ControlC will be the bottommost control.
Consider the following code fragment and sample output:
// The following code fragment creates an outlook style tab control snapshot.
// ( Note that only minimal properties are shown and no events are subscribed to for clarity. )
System.Windows.Forms.Panel parentPanel = new System.Windows.Forms.Panel();
parentPanel.Width = 500;
// First TabButton
System.Windows.Forms.Button button1 = new System.Windows.Forms.Button();
button1.Width = parentPanel.Width;
button1.DockStyle = DockStyle.Top;
// Second TabButton
System.Windows.Forms.Button button2 = new System.Windows.Forms.Button();
button2.Width = parentPanel.Width;
button2.DockStyle = DockStyle.Top;
// Last TabButton
System.Windows.Forms.Button button3 = new System.Windows.Forms.Button();
button3.Width = parentPanel.Width;
button3.DockStyle = DockStyle.Top;
parentPanel.Controls.AddRange(new Control[] { button1, button2, button3 });
Notice that button3 is the topmost control, because it was the last
control added.
Knowing this, you should take care when setting the DockStyle property
of controls at runtime. At design time, Visual Studio .NET automatically takes
this into account, and adjusts the parent's Controls collection
accordingly.
Back to Tips and Tricks