发布于 2016-05-28 09:36:04 | 86 次阅读 | 评论: 1 | 来源: 网友投递

这里有新鲜出炉的精品教程,程序狗速度看过来!

ASP.NET

ASP.NET 是.NET FrameWork的一部分,是一项微软公司的技术,是一种使嵌入网页中的脚本可由因特网服务器执行的服务器端脚本技术,它可以在通过HTTP请求文档时再在Web服务器上动态创建它们。 指 Active Server Pages(动态服务器页面) ,运行于 IIS(Internet Information Server 服务,是Windows开发的Web服务器)之中的程序 。


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

最新网友评论  共有(1)条评论 发布评论 返回顶部
yxu 发布于2016-08-04 03:49:35
为啥我的不行啊
支持(0)  反对(0)  回复

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务