简体   繁体   中英

Can't add a control dynamically to the <asp:placeHolder>

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM