日期:2014-05-18  浏览次数:20462 次

如何查找母板页中ContentPlaceHolder内的控件?
我在masterPage中定义了两个textBox,一个位于ContentPlaceHolder中,一个位于ContentPlaceHolder外:
代码如下:
<form id="form1" runat="server">
  <div>
  <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
  <asp:TextBox ID="TextBox1" runat="server" >Wether display</asp:TextBox></asp:ContentPlaceHolder>
  </div>
  <asp:Button ID="Button1" runat="server" Text="Button" />
  <asp:TextBox ID="TextBox2" runat="server" Text ="can find"></asp:TextBox>
  </form>  

我在另外包含该母板页的页面中想引用ContentPlaceHolder中的TextBox1,和ContentPlaceHolder之外的TextBox2,我用了如下的几种写法:<script runat="server">
  void Page_Load(object sender, EventArgs e)
  {  
  ContentPlaceHolder c = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
  TextBox t1 = (TextBox)Master.FindControl("TextBox2");
  TextBox t2 = (TextBox)c.FindControl("TextBox1");
  TextBox t3 = (TextBox)c.FindControl("TextBox2");
  TextBox t4 = (TextBox)Master.FindControl("TextBox1");
  }

</script>

经过调试可以得到 c 和t1的引用,但是t2,t3,t4的引用都为空。
我请问一下为什么会出现这样的情况,以及我该如何引用ContentPlaceHolder中定义的控件?

------解决方案--------------------
把TextBox1放在masterpage的ContentPlaceHolder里
在任何引用该模版的页面里TextBox1都会被覆盖,不会显示出来
那又怎么能取得到呢?
既然是模版页,所有通用的控件都应在ContentPlaceHolder之外
------解决方案--------------------
TextBox t1 = (TextBox)Master.FindControl("aaa"); 
这个是找ContentPlaceHolder外边的控件,没问题。

ContentPlaceHolder c = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");
TextBox t2 = (TextBox)c.FindControl("TextBox1"); 
这个是找 ContentPlaceHolder里边的控件,但是注意,并不是MasterPage.master中的ContentPlaceHolder里边的控件,而是嵌套了masterpage的子页里边的ContentPlaceHolder里的控件

------解决方案--------------------
LZ可能犯了一个意识上的错误
msdn上的那段代码是放在MasterPage的后台运行的,而不是在内容页后台运行
------解决方案--------------------
kyouken2007说:“ 但是注意,并不是MasterPage.master中的的控件,而是嵌套了masterpage的子页里边的ContentPlaceHolder里的控件 ”
---------------------------------------------------------
子页中的内容都包含在母板页ContentPlaceHolder里边,如果子页中有个TextBox控件,就可以用这种方法找到

ContentPlaceHolder c = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1"); 
TextBox t2 = (TextBox)c.FindControl("TextBox1");

------解决方案--------------------
刚试了一下 好像也有问题
不知道是msdn没说清楚还是我没理解对
不过事实是不管怎样在模版页ContentPlaceHolder放的控件
在运行时就被覆盖了,没法找到
要想找到就一定是放在内容页ContentPlaceHolder里,我想
msdn应该说的是这个意思吧
------解决方案--------------------
我觉得就是这个意思,
但是实际上如果放在内容也里边,不需要findcontrol,直接通过id就可以访问