0

I have a control called PromoArea.ascx. This is the code for the front end

<div class="vh-right-rail-promoarea">
<asp:PlaceHolder ID="DynamicControl1" runat="server"></asp:PlaceHolder>
</div>

I have registered this web part in pages.config and put it on my template

<site:PromoArea ID="PromoArea" runat="server"/>

However, when I am trying to add control to it dynamically, the placeHolder returns null. This is my code behind

PlaceHolder ph = 
    (PlaceHolder)this.Page.FindControl("DynamicControl1");
ph.Controls.Add("controlName");

ph returns null. I read somewhere that if you want to add a control inside a placeHolder, you have to find a place holder on page first, cast it, and then add control to it. So why is my place holder control return null then?

Cœur
  • 37,241
  • 25
  • 195
  • 267
doglin
  • 1,651
  • 4
  • 28
  • 38

2 Answers2

0

I suspect it is null because the reference to it is incorrect.

Are you using master pages? If so try:

PlaceHolder ph = Master.FindControl("DynamicControl1") as PlaceHolder
Paul Zahra
  • 9,522
  • 8
  • 54
  • 76
  • Hi yes, I am using master page. However, we use nested master page in our app. So my template calls Wrapper.Master. Wrapper.Master then calls Site.master, that is on the root level. – doglin Mar 13 '14 at 14:22
  • You could statically call findcontrol to solve this one issue, however it may be of value to you to use a recursive FindControl function such as is in this post http://stackoverflow.com/questions/4955769/better-way-to-find-control-in-asp-net – Paul Zahra Mar 13 '14 at 15:36
0

I just ended up calling "DynamicControl1" directly DynamicControl1.Controls.Add(_imageControl1);

That seems to work. I originally tried to cast the PlaceHoder control first, because I remember a MSDN blog said if you have a control placed in a place holder, you have to find that placeHolder first

doglin
  • 1,651
  • 4
  • 28
  • 38