微信号:
当前位置:首页 > 资讯文摘 > 新闻资讯

获取母版页内控件的方法

2015/10/28 10:20:24

MasterPage
<asp:Button ID="Button1" runat="server" Text="顶层" />
<asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
</asp:contentplaceholder>  

MasterPage2是MasterPage的子母版页
<asp:Button ID="Button1" runat="server" Text="第二层" />
<asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
</asp:contentplaceholder>  

test.aspx使用MasterPage2
var masterpage = Master as MasterPage; //第二层MasterPage2
var masterpage2 = masterpage.Master as MasterPage;//顶层MasterPage
var content = masterpage2.FindControl("ContentPlaceHolder1") as ContentPlaceHolder;
           
if (content != null)
{
    //第二层(即上一层)需要通过顶层来查找ContentPlaceHolder1,然后找控件
    Button bt2 = content.FindControl("Button2") as Button;
    if (bt2 != null)
    {
        string test = bt2.Text;
    }

}

//顶层可以直接找到
Button bt = masterpage2.FindControl("Button1") as Button;
if (bt != null)
{
    string test = bt.Text;
}
 

相关新闻: