Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a control before another control

Tags:

asp.net

How do I dynamically insert a control before another control in asp.net. Lets say control1 is some control on the web page and I want to dynamically create and insert a table just before control1.

e.g.

table1 = new Table();
table1.ID = "Table1";

but what comes next? To add a control as a child I would do: control1.Controls.Add(table1); but how on earth do I insert table1 as the previous sibling of control1 ?

like image 477
AJ. Avatar asked Feb 17 '10 14:02

AJ.


1 Answers

If you want the new control (controlB) to be immediately before controlA, you can determine the index of controlA in the Page.Controls collection, and insert controlB at that location. I believe this will bump controlA forward by one index, making them immediate siblings as desired.

if(Page.Controls.IndexOf(controlA) >= 0)
    Page.Controls.AddAt(Page.Controls.IndexOf(controlA), controlB);

Edit:

One further note - the above assumes control A and B are on the root page level. You could also use the Parent property to ensure the sibling insertion works no matter where controlA sits in the page hierarchy:

Control parent = controlA.Parent;

if(parent != null && parent.Controls.IndexOf(controlA) >= 0)
{
    parent.Controls.AddAt(parent.Controls.IndexOf(controlA), controlB);
}

I'd actually prefer this method as it is more flexible and does not rely on the Page.

like image 182
KP. Avatar answered Sep 23 '22 08:09

KP.