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?
I will recommend that you put a placeholder control in content and use it to add controls. For example,
And
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 theseasp:Content
sections and makes them children of theContentPlaceholder
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:Notice you are using the
ContentPlaceHolderID
value, NOT theID
of theasp:Content
section.