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: WinForms
Thanks. This saved my life. 🙂
Seems simple, but a killer if you simply don’t know/can’t find the [correct] methods.
Thanks for posting this.
Thanks a lot…….
Argghh, my head hurts, but finding this solution makes me feel alot better…
thanks alot for posting…
I was just thinking about Docking With Run-Time-Created Controls and you’ve really helped out. Thanks!
It is a very useful for me …
Thanks ..
That’s great, I never thought about Peter Ritchie’s MVP Blog like that before.
I was just thinking about Docking With Run-Time-Created Controls and you’ve really helped out. Thanks!
Good post, but have you thought about Peter Ritchie’s MVP Blog before?
Thank you soooo much. I was just trying to find the correct way to reach that goal.
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.
In design-time, parent form simply change order of its children when adding them.
Simple way, but truly magic.