Reputation: 7421
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 ... .
Upvotes: 17
Views: 12446
Reputation: 1017
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();
Upvotes: 0
Reputation: 3688
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();
Upvotes: 4
Reputation: 139758
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);
Upvotes: 30
Reputation: 5757
Correcting myself: myPanel.Controls.AddAt(index, myControl)
Upvotes: 0