使用MasterPage后FindControl的使用

没有使用母版页前,查找控件可以这样使用
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的一个子控件。
原文地址:https://www.cnblogs.com/ilahsa/p/1190747.html