当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > ASP.Net PlaceHolder、Panel等控件未实现INamingContainer,导致FindControl无效

ASP.NET
C# Quoted-Printable编码、解码
asp.net Google的translate工具翻译 API
.NET读取所有目录下文件正则匹配文本电子邮件
asp.net 半角全角转化工具
AjaxControlToolKit 显示浏览者本地语言的方法
asp.net HTML文件上传标签
ASP.NET 绑定DataSet中的多个表
ASP.NET 重定向的几种方法小结
Asp.Net 重定向必须要知道的一些资料
ASP.NET 导出到Excel时保留换行的代码
Asp.Net Cache缓存使用代码
document.getElementsByName和document.getElementById 在IE与FF中不同实现
GridView单元格合并
asp.net 大文件上传控件
asp.net 日期函数 某月的第一天和最后一天的日期
asp.net 时间类 一周的周一和周末的日期
C# javaScript函数的相互调用
asp.net membership 密码重设
"虚拟路径"..."映射到另一个应用程序,这是不允许的!
如何传值在2个页面之间 要求不刷新父页面,并且不能用Querystring传值

ASP.NET 中的 ASP.Net PlaceHolder、Panel等控件未实现INamingContainer,导致FindControl无效


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-13   浏览: 75 ::
收藏到网摘: n/a

这2天在开发中发现,如果在new的Panel中使用FindControl,会出现找不到控件的情况 代码如下:
复制代码 代码如下:

Panel spnButtons = new Panel();
Button btn = new Button();
btn.ID = "btn1";
spnButtons.Controls.Add(btn);
// 输出True,表示没有找到控件
Response.Write(spnButtons.FindControl(btn.ID) == null);

而如果是下面的代码就可以了:
复制代码 代码如下:

Panel spnButtons = new Panel();
Page.Controls.Add(spnButtons);// 创建Panel后把它加入Page
Button btn = new Button();
btn.ID = "btn1";
spnButtons.Controls.Add(btn);
// 输出False,表示找到了控件
Response.Write(spnButtons.FindControl(btn.ID) == null);

或者使用Repeater也可以:
复制代码 代码如下:

Repeater spnButtons = new 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,可以找到控件了:
复制代码 代码如下:

public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
myPanel spnButtons = new myPanel();
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有效了。