Inserting a control before another control
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 d开发者_如何学Co: 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 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
.
Did you try control1.Controls.AddAt(0, table1)
? Kind of odd they didn't call the method Insert like most other collection types.
精彩评论