问题描述
我如何动态地插入在asp.net另一个控制之前的控制。比方说CONTROL1是网页上的一些控制,我想动态创建和刚刚CONTROL1前插入一个表格。
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.
例如。
table1 = new Table();
table1.ID = "Table1";
但下一步怎么走?要添加控件作为一个孩子,我会做: control1.Controls.Add(表1);
但如何在地球上我插入表1为CONTROL1的previous兄弟?
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 ?
推荐答案
如果您希望新的控制( controlB
)立即成为前 controlA
,可以判断指数 controlA
在 Page.Controls
集合,并插入 controlB
在该位置。我相信,根据需要,这将凹凸 controlA
向前一个索引,使它们直接相邻的兄弟。
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);
编辑:
一名注 - 上面的假设控制A和B是根页级。你也可以使用父
属性,以确保同级插入工作无论身在何处 controlA
坐在页面层次结构:
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);
}
其实我preFER这种方法,因为它更灵活,不依赖于页
。
这篇关于另一个控制之前插入控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!