how to add controls to the masterpage's content placeholder programmatically

萝らか妹 提交于 2019-12-22 01:14:31

问题


On the base.master:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Base.master.cs" Inherits="WebApplicationControlTest.Base" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>The title</title>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        There is a content here: <br />
        <asp:ContentPlaceHolder ID="body" runat="server">
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>

On the nested master

<%@ Master Language="C#" MasterPageFile="~/MasterPages/Base.Master" AutoEventWireup="true" CodeBehind="NestedMasterPageTest2.master.cs" Inherits="WebApplicationControlTest.MasterPages.NestedMasterPageTest2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>

<asp:Content ID="PlaceHolder" ContentPlaceHolderID="body" runat="server">
    This is inside the NestedPage<br />
    <asp:ContentPlaceHolder ID="PlaceHolderLeft" runat="server">
    </asp:ContentPlaceHolder>
    <asp:ContentPlaceHolder ID="PlaceHolderRight" runat="server">
    </asp:ContentPlaceHolder>
</asp:Content>

and on the default.aspx

<asp:Content ID="PlaceHolder" ContentPlaceHolderID="PlaceHolderLeft" runat="server">
    This is a test!
</asp:Content>

on the default.aspx.cs

protected override void OnPreInit(EventArgs e){
    Control control = LoadControl("TheUrlOfTheControl.ascx");
    if (Page.Master.FindControl("body") != null) {
        Page.Master.FindControl("body").Controls.Add(control);
    }
}

I need to add the control to the last part of the body content Placeholder but FindControl does return null... how can we add controls to the masterpage's content placeholder programmatically?

Thanks


回答1:


Answered for future reference

protected override void OnPreInit(EventArgs e){
    Control control = LoadControl("TheUrlOfTheControl.ascx");
    Control placeHolderControl = Page.FindControl("body");
    if (placeHolderControl != null) {
        placeHolderControl.Controls.Add(control);
    } else {
        MasterPage theMaster = Page.Master;
        while (theMaster != null) {
            placeHolderControl = theMaster.FindControl("body");
            if (placeHolderControl != null) {
                placeHolderControl.Controls.Add(control);
                break;
            }
            theMaster = theMaster.Master;
        }
    }
}


来源:https://stackoverflow.com/questions/1905145/how-to-add-controls-to-the-masterpages-content-placeholder-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!