C# – Dynamically loaded control

asp.netc

I've got a page that uses a master page. The master page has 2 contentplaceholders on it. The page has content controls on it that correspond to the placeholders on the master page. I need to dynamically insert a usercontrosl into those content areas. I can't seem to get a reference to the content controls at run time so that I can insert the controls into them. See code below:

Master Page:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs"      Inherits="Agile.Portal.Site1" %>

<!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></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
    <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">

    </asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>

WebPage:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true"      CodeBehind="WebForm1.aspx.cs" Inherits="Agile.Portal.WebForm1" %>
<asp:Content ID="head" ContentPlaceHolderID="head" runat="server">
</asp:Content>
 <asp:Content ID="ContentPlaceHolder1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
 </asp:Content>

Code:

    protected override void OnInit(EventArgs e)
    {
        //  YOU SUCK, you're always null!!!
        System.Web.UI.WebControls.Content cnt = (System.Web.UI.WebControls.Content)this.FindControl("ContentPlaceHolder1");
        Agile.Portal.Framework.BaseModule mod = (Agile.Portal.Framework.BaseModule)LoadControl("~/modules/HTMLModule/HtmlModule.ascx");
        cnt.Controls.Add(mod);
        base.OnInit(e);
    }

Best Answer

Try use:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true"      CodeBehind="WebForm1.aspx.cs" Inherits="Agile.Portal.WebForm1" %>
<asp:Content ID="head" ContentPlaceHolderID="head" runat="server">
</asp:Content>
 <asp:Content ID="ContentPlaceHolder1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
   <asp:PlaceHolder ID="MyPlaceHolder1" runat="server"/>
 </asp:Content>

and in code:

protected override void OnInit(EventArgs e) {
    System.Web.UI.WebControls.PlaceHolder cnt = (System.Web.UI.WebControls.PlaceHolder)this.FindControl("MyPlaceHolder1");
    Agile.Portal.Framework.BaseModule mod = (Agile.Portal.Framework.BaseModule)LoadControl("~/modules/HTMLModule/HtmlModule.ascx");
    cnt.Controls.Add(mod);
    base.OnInit(e);
}
Related Topic