Content control not accessbile from content page?

拥有回忆 提交于 2019-12-23 20:31:57

问题


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?


回答1:


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.




回答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(...
  }


来源:https://stackoverflow.com/questions/4142655/content-control-not-accessbile-from-content-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!