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 ?
If you want the new control (
controlB) to be immediately beforecontrolA, you can determine the index ofcontrolAin thePage.Controlscollection, and insertcontrolBat that location. I believe this will bumpcontrolAforward by one index, making them immediate siblings as desired.Edit:
One further note – the above assumes control A and B are on the root page level. You could also use the
Parentproperty to ensure the sibling insertion works no matter wherecontrolAsits in the page hierarchy:I’d actually prefer this method as it is more flexible and does not rely on the
Page.