这2天在开发中发现,如果在new的Panel中使用FindControl,会出现找不到控件的情况,代码如下:
而如果是下面的代码就可以了:
Button btn = new Button();
btn.ID = "btn1";
spnButtons.Controls.Add(btn);
// 输出False,表示找到了控件
Response.Write(spnButtons.FindControl(btn.ID) == null);
或者使用Repeater也可以:
Button btn = new Button();
btn.ID = "btn1";
spnButtons.Controls.Add(btn);
// 输出False,表示找到了控件
Response.Write(spnButtons.FindControl(btn.ID) == null);
查了一下Panel是继承于WebControl,而WebControl的定义是:
public class WebControl : Control, IAttributeAccessor
{}
Repeater的定义是:
public class Repeater : Control, INamingContainer
{}
难道是因为Repeater实现了INamingContainer的原因吗?
我又自定义了一个类,继承自Panel,并实现了INamingContainer,可以找到控件了:
Button btn = new Button();
btn.ID = "btn1";
spnButtons.Controls.Add(btn);
Response.Write(spnButtons.FindControl(btn.ID) == null);
}
}
public class myPanel : Panel, INamingContainer
{
public myPanel():base()
{
}
}
综上,ASP.Net中,PlaceHolder、Panel等控件未实现INamingContainer,导致FindControl无效
如果把这些控件加入到实现了INamingContainer的父控件中,或者用子类实现INamingContainer,就可以使FindControl有效了。