手机
当前位置:查字典教程网 >编程开发 >asp.net教程 >ASP.Net PlaceHolder、Panel等控件未实现INamingContainer,导致FindControl无效
ASP.Net PlaceHolder、Panel等控件未实现INamingContainer,导致FindControl无效
摘要:代码如下:复制代码代码如下:PanelspnButtons=newPanel();Buttonbtn=newButton();btn.ID=...

代码如下:

复制代码 代码如下:

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有效了。

【ASP.Net PlaceHolder、Panel等控件未实现INamingContainer,导致FindControl无效】相关文章:

php使用socket编程示例

Http异常eurl.axd出错信息解决方法

浅谈ASP.NET中最简单的自定义控件

ASP.Net下载大文件的实现方法

ASP.NET页面之间传递参数的几种方法

asp.net gridview代码绑定

ASP.Net 分页控件源码

ASP.NET 运行.bat文件的实现方法

Asp.Net如何将多个RadioButton指定在一个组中

asp.net使用jQuery Uploadify上传附件

精品推荐
分类导航