开发者

How to add usercontrol into a aspx page loaded by a master page file?

开发者 https://www.devze.com 2023-03-21 07:28 出处:网络
I use master page to define the page layout of default.aspx. In the master page I have included ContentPlaceHolder cph. I want to access cph from default.aspx and load the ascx file into cph. How can

I use master page to define the page layout of default.aspx. In the master page I have included ContentPlaceHolder cph. I want to access cph from default.aspx and load the ascx file into cph. How can I do this? I tried t开发者_开发问答he code below in page load event, but it does not work.

     string controlPath = "~/Usercontrols/webusercontrol.ascx";
     UserControl uc = LoadControl(controlPath) as UserControl;
     ContentPlaceHolder cph = (ContentPlaceHolder)this.Master.FindControl("cphMain");
     if ((cph != null) && (uc != null))
     {
          cph.Controls.Add(uc);
     }


Make sure your Default.aspx has this on the page tag: MasterPageFile="~/MasterPages/Master1.master"

Once you are sure of that, you can use this tag in your Default.aspx

<asp:Content ID="Content1" ContentPlaceHolderID="cphMain" Runat="Server">
   ....
</asp:Content>

You can just put your user in here, or you can add it dynamically. I would recommend against dynamic loading unless it is necessary (dynamic controls adds an extra layer of complexity)


Can you post the relevant parts of your Master Page? Master.FindControl(string) will not find just any control on any level of the Master Page, only the ones that are directly on the root, so if your placeholder is inside, say a Panel, it will not return it.

Also you haven't specified what is the error or behavior that you are seeing.

0

精彩评论

暂无评论...
验证码 换一张
取 消