Add Control Value before another Control value in C#

Am1rr3zA picture Am1rr3zA · May 9, 2012 · Viewed 10.2k times · Source

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

Answer

nemesv picture nemesv · May 9, 2012

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