Add Control Value before another Control value in C#
Asked Answered
V

4

17

I have a "FlowLayoutPanel" and want to add series of "UserControl" to it:

mainPanel.Controls.Add(fx);

Every new usercontrol added after old one, I want to add new usercontrol before the previous usercontrol that was added how could I do this? I didn't find any functionality like mainPanel.Controls.AddAt(...) or mainPanel.Controls.Add(index i, Control c) or mainPanel.Controls.sort(...) or ... .

Virgel answered 9/5, 2012 at 13:20 Comment(0)
C
30

You can use the SetChildIndex method. Something like (maybe you need to fiddle with the indecies):

var prevIndex = mainPanel.Controls.IndexOf(previouslyAdded)
mainPanel.Controls.Add(fx);
mainPanel.Controls.SetChildIndex(fx, prevIndex); 
Caltanissetta answered 9/5, 2012 at 13:27 Comment(0)
O
4

by the sounds of it you want to change the flowdirection attribute so that newest controls added are added to the top

flowLayoutPanel1.FlowDirection = FlowDirection.BottomUp;

or you could

 Label label1 = new Label();
 flowLayoutPanel1.Controls.Add(label1);
 label1.BringToFront();
Obfuscate answered 9/5, 2012 at 13:23 Comment(3)
If I change flow direction my problem don't solve, it just add from right to left instead of left to right, but still add after old userControlVirgel
But if it is adding from left to right does it not layout like oldest control to far right newest control to far left?Obfuscate
Sorry I had my second option backwards... I had SendToBack should have been BringToFrontObfuscate
U
0

Correcting myself: myPanel.Controls.AddAt(index, myControl)

Urien answered 9/5, 2012 at 13:23 Comment(2)
No, there is not such method, we just have Add().Virgel
Nevermind, I was thinking about ASP.NET WebForms. I think you're dealing with WPF, right? If so, please retag.Urien
K
0

Something like this will add a control in alphabetical order.

                    FlowLayoutPanel flowLayoutPanel = ...; // this is the flow panel
                    Control control = ...; // this is the control you want to add in alpha order.

                    flowLayoutPanel.SuspendLayout();
                    flowLayoutPanel.Controls.Add(control);

                    // sort it alphabetically
                    for (int i = 0; i < flowLayoutPanel.Controls.Count; i++)
                    {
                        var otherControl = flowLayoutPanel.Controls[i];
                        if (otherControl != null && string.Compare(otherControl.Name, control.Name) > 0)
                        {
                            flowLayoutPanel.Controls.SetChildIndex(control, i);
                            break;
                        }
                    }

                    flowLayoutPanel.ResumeLayout();
Kindergartner answered 11/10, 2013 at 0:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.