在.net 2.0 中如果使用了masterPage,则不能像以前那样使用 FindControl,则需要使用如下方法

 

先找到ContentPlaceHolder,然后再找在这个ContentPlaceHolder中的你要找的控件


1
2//MasterPage 中的ContentPlaceHolder ID
3string masterPageContentPlaceHolderID = "";
4//在 masterPageContentPlaceHolderID 中所要找到的控件的 ID
5string m_strSetDataToID = "";
6//例如找 TextBox
7TextBox textBoxFind = (TextBox)this.Page.Master.FindControl(masterPageContentPlaceHolderID).FindControl(m_strSetDataToID);


没有使用母版页前,查找控件可以这样使用
TextBox txt1=(TextBox)this.FindControl("TextBox1");
加入母版页后不能这样使用了
打开跟踪 Trace="true"
           _ctl0:MainContent:TextBox1 System.Web.UI.WebControls.TextBox 109 0 0
                 _ctl0:MainContent:_ctl14 System.Web.UI.ResourceBasedLiteralControl 455 0 0
                 _ctl0:MainContent:_ctl3 System.Web.UI.HtmlControls.HtmlTableCell 78 0 0
                 _ctl0:MainContent:_ctl15 System.Web.UI.LiteralControl 83 0 0
                 _ctl0:MainContent:_ctl4 System.Web.UI.HtmlControls.HtmlTableCell 65
可以看到ID为TextBox1 的控件由于使用了母版页,控件前加入了MainContent
可以这样找到TextBox1 控件
TextBox txt1=this.Master.FindControl("MainContent").FindControl("TextBox1") as TextBox1 ;

即先用this.Master.FindControl("MainContent") 定位到TextBox1 的相对位置

加入母版页这里的“this”意义已经不是从前了,this的第一个对象找到的应该是MasterPage中的控件,而不是aspx中的控件。因为Aspx其实是把内容放在其中一个Content上的子控件上,所以aspx页面只能算作是this的一个子控件。


ASP.NET开发人员在使用一些动态导入控件的功能的时候, 常会遇到这样一个问题: 就是明明有这个ControlID, 但使用Page.FindControl(ControlID)得到的结果却是null, 这是bug? 还是某种不明机制?

首先要说的是, 这不是bug. 而为何使用Page.FindControl方法找不到指定控件, 我们可以在该页的页指令中添加 Trace=Ture 指令来跟踪页面输出查看控件树。

其次,得说一下FindControl方法的实现机制,FindControl方法是在当前naming container查找指定ControlID对应的控件,该naming container是一个实现了INamingContainer接口的对象。问题的关键是,Page是指定ControlID的当前naming container么?

一个页面的控件树中,Page对象必然是顶级的naming container,但绝非必然是唯一的naming container。譬如当有GridView存在的话,GridView其实也是一个naming container,要找GridView中的一个ControlID,就不能用Page.FindControl,而得用[GridView对象].FindControl方法。

再譬如最普遍的,在ASP.NET 2.0中,引入了MasterPage的机制,在当前页使用MasterPage的情况下,当前页也产生了类似ContentPlaceholder1这样的naming container,这时查找当前页的控件,也不能使用Page.FindControl方法,而得要用ContentPlaceholder1.FindControl方法。

很多时候,因为是动态控件,明知道是在同一个naming container中,但不知道该naming container是什么对象,一个控件要找到另一个控件,可以用this.Parent.FindControl方法。

posted on 2010-11-30 14:32  露水丛生  阅读(907)  评论(0编辑  收藏  举报