Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert top docked controls below previewsly top docked controls on a panel

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...

like image 964
saggio09 Avatar asked Oct 07 '11 07:10

saggio09


3 Answers

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);
like image 151
Hans Passant Avatar answered Sep 21 '22 13:09

Hans Passant


You have two ways of doing this.

  1. 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)
    
  2. 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).

like image 31
RVK Avatar answered Sep 19 '22 13:09

RVK


"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:

  1. 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:

  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.)

like image 30
Konrad Morawski Avatar answered Sep 21 '22 13:09

Konrad Morawski