I use panel.controls.add to add controls to the panel. But... they insert at the very top of it.
I tried the BringToFront and SendToBack methods, but does'nt seem to be working.
Any ideas? Thanks
EDIT:
what i want, is that they dock at the top of the container, but if there is another docked control there, the new one is displayed below that one...
The docking order is based on the index of the control in the Controls collection. The last one goes on top. Which is why your added control goes on top and pushes an existing docked control down. Use the SetChildIndex() method to move the control to index 0:
var btn = new Button();
btn.Dock = DockStyle.Top;
panel1.Controls.Add(btn);
panel1.Controls.SetChildIndex(btn, 0);
You have two ways of doing this.
Add the controls in the order that you want them to be displayed in a panel, dock the controls to the bottom as you create them.
Example:
Panel.Controls.Add(Label1)
Panel.Controls.Add(Label2)
Panel.Controls.Add(Label3)
Reverse the order of the controls being added to the panel, dock the controls to the top as you create them.
Example
Panel.Controls.Add(Label3)
Panel.Controls.Add(Label2)
Panel.Controls.Add(Label1)
If this is not what you want, you will want to reverse either the order of what is being added (which does not seem likely) or docking (up vs down).
"what i want, is that they dock at the top of the container, but if there is another docked control there, the new one is displayed below that one..."
OK I understand. I see two solutions:
Use Anchor
property (set to Top
) instead of Dock
property - then these controls will be placed at the top side by side, however they won't stretch horizontally, they won't automatically occupy all available horizontal space (you can still control their Width
programmatically of course). If this limitation is a problem for you, try option 2:
Use another container control - it could be a TableLayoutPanel
- dock it at the top of the first panel, and then put the remaining controls in that TableLayoutPanel. Use its Columns
collection to provide space for multiple controls next to eachother. (Embedding container controls in other container controls is not unusual and often necessary when designing complex layouts.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With