3

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?

Wodzu
  • 6,932
  • 10
  • 65
  • 105

2 Answers2

7

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.

patmortech
  • 10,139
  • 5
  • 38
  • 50
  • Thanks, I mark it as an answer. I can understand that it dissapears at runtime, but why I cant access it in designtime like other controls. If I see that control in WYSIWYG editor, than I should be able to acces that control in C# file also. From my point of view it is a bug in design commited by Microsoft. – Wodzu Nov 10 '10 at 12:53
2

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(...
  }
VinayC
  • 47,395
  • 5
  • 59
  • 72
  • +1 For the nice idea how to overcome the problem, thanks:) But why the content control itself is not accessible, this really intrigue me. – Wodzu Nov 10 '10 at 09:21
  • @Wodzu, thats because Content control does not get added to page. See more detailed response by patmortech. – VinayC Nov 10 '10 at 11:22