Access asp:content from code behind
Asked Answered
E

2

12

Ok, I am an experienced web developer but sometimes ASP.Net is tricking me. I have a master page in asp.net. Then I have a page based on that master page (home.aspx). Now in home.aspx.cs I want to access the asp:content controls to add controls programmatically.

Aspx looks like this:

<asp:Content ID="leftCol" ContentPlaceHolderID="cphLeftCol" Runat="Server">
  <asp:PlaceHolder ID="phLeftCol" runat="server">
  </asp:PlaceHolder>
</asp:Content>

I would expect that I can reference "leftCol" from my code behind. But it's unknown there. For testing I added my own placeholder "phLeftCol". I can reference that without issues.

Is there something I don't see?

Erechtheus answered 29/9, 2010 at 19:28 Comment(0)
F
19

You can't access the asp:Content control directly from your code behind. A content control is not added to the control heirarchy at runtime so it is not accessible from the code behind to add controls to at runtime. To add controls to it at runtime, you need to add another container control to the content control and add the controls to that (as you did with the placeholder control).

See this MSDN article for more information.

Filip answered 29/9, 2010 at 19:40 Comment(3)
There are other container controls maybe better suited to your situation than a placeholder control (would really have to know more about what your are doing), but the content control is not an option.Filip
Think of each ContentPlaceHolder (on master page) and each matching Content (content page) object simply as opposite endpoints of a link telling the Master/Content rendering system where and what to embed in the master page. Each ContentPlaceHolder on the master page simply indicates where to embed the stuff defined in each corresponding Content object in the content page. Since these objects serve only as a link about where/what to embed, they are like meta-objects for the Master/Content rendering system, so they are never a part of the control hierarchy.Antony
If it helps anyone, you CAN access this on the masterpage code behind however.Mcmann
E
1

You can't access "leftCol" control from home page code-behind because it is holder for content of that page, and code your home page is unaware of his content in the moment of injecting... you can only access controls in that content. Content injecting goes in asp.net from bottom up, so content of your home page, in this case everything between tags <asp:Content ID="leftCol" ...> and </asp:Content>, goes in placeHolder of a Master Page...

cheers

Emmen answered 29/9, 2010 at 19:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.