I am writing a UserControl which adds child controls programmatically. Currently I am adding new controls like so:
this.Controls.Add(new Control() { Height = 16, Dock = DockStyle.Top });
The problem I am experiencing is that new controls are added above the existing controls, so where I want the controls to be ordered 1, 2, 3, 4, 5, 6 from top to bottom, it's ordering them as 6, 5, 4, 3, 2, 1 from top to bottom.
I want to know how I ensure a new control is added after all existing controls (in terms of display order).
And also, I want to know if I can insert a control between two other selected controls
I have tried setting the TabIndex but that didn't help!
I know this is years old but what the heck.
You can use the SetChildIndex method to control this as follows
Source: http://tipsntricksbd.blogspot.com/2009/10/c-dynamically-adding-control-with.html
Here's my solution to this. Basically you put the controls in a list as well as the container. Then you use Bring to Front as mentioned is pretty much all posts. This of course also gives you the posibility of insert.
When using Winforms only the sequence in which controls are added determines their docking behaviour.
The last added control will always go nearest to the docking border, i.e. to the top with
DockStyle.Top
. NeitherBringToFront
norSendToBack
or Tab-order will change this.Just add your controls in reverse order, or remove them and add them again.
For what concerns controls insertion... it's not possible as controls position depends on the order they are added to the form. If you have layout space, however, you can insert a control between two controls physically... you calculate ctrl1 and ctrl2 positions and dimensions and you set the location of the new one depending on this.