Docking With Run-Time-Created Controls

I was throwing together some demo code that involved creating a control at runtime, that I wanted docked in a certain way on the parent Form.  I could have pre-created the control in the designer and hidden it–to be made visible instead of creating it–but, that’s not the situation I was in.  Simply creating the control and setting the Dock property (in this case to DockStyle.Fill) isn’t enough to dock it properly if there are any existing docked controls.


If you’ve ever created a control and runtime and attempted to change the Dock property, you’ve probably noticed it doesn’t dock the way you want.  Control docking depends on order of the control in the Controls collection of the parent Form.  If you have a Form with a control whose Dock property is DockStyle.top, and you create a new control and set it’s dock to DockStyle.Fill, it fills to the entire form client area, not the the area left over by the other docked controls.


In order to create a control and add it to the form with Dock set to DockStyle.Fill you need to push it to the top of the Controls collection.  This can be accomplished with the SetChildIndex() method on the Collections property.  For example:

PictureBox pictureBox = new PictureBox();
pictureBox.Image = pictureBox.ErrorImage;
pictureBox.SizeMode =
PictureBoxSizeMode.StretchImage;
pictureBox.Dock =
DockStyle.Fill;
this.Controls.Add(pictureBox);
// the magic line:
this.Controls.SetChildIndex(pictureBox, 0);

Technorati Tags:

12 thoughts on “Docking With Run-Time-Created Controls”

  1. Thank you for this. I’ve been trying to find a solution for years.

    The help says:

    The control with an index value of zero is at the top of the z-order, and higher numbers are closer to the bottom.

    But it appears to be the other way around.

  2. In design-time, parent form simply change order of its children when adding them.
    Simple way, but truly magic.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>