Question

My content page looks like this:

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Basket.aspx.cs" Inherits="Basket" Title="Untitled Page" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
</asp:Content>

Now, I would like to add some controls dynamically to the content when page loads, so I am trying the following code:

  protected void Page_Load(object sender, EventArgs e)
  {
     Content2. // I want to add controls to it dynamically
  }

The problem is that the Content2 control is not visible by the compiler and I am getting error about missing directive or assembly reference.

Any solution?

Was it helpful?

Solution

The reason you can't get a reference to that asp:Content control is because it does not stay around when the page is combined with the masterpage. Basically ASP takes all the controls from inside these asp:Content sections and makes them children of the ContentPlaceholder controls inside the masterpage.

As MSDN says: A Content control is not added to the control hierarchy at runtime. Instead, the contents within the Content control are directly merged into the corresponding ContentPlaceHolder control.

That means that if you want to add more controls to that section, you will have to get a reference to the ContentPlaceholder control in the masterpage and add them to it. Something like:

ContentPlaceHolder myContent = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
myContent.Controls.Add(??);

Notice you are using the ContentPlaceHolderID value, NOT the ID of the asp:Content section.

OTHER TIPS

I will recommend that you put a placeholder control in content and use it to add controls. For example,

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Basket.aspx.cs" Inherits="Basket" Title="Untitled Page" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
  <asp:Placeholder runat="server" ID="Content1Controls" />
</asp:Content>

..

And

  protected void Page_Load(object sender, EventArgs e)
  {
     Content1Controls.Controls.Add(...
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top