When does x.Controls.Add(y) work?

B

Brian Lowe

I'm trying to add the content of a user control dynamically at run time,
dependent upon some request attribute.

My user control is a simple tell-tall so I'm sure that's not spoiling
anything.
<%@ Control Language="C#" AutoEventWireup="true"
CodeBehind="cpStatus.ascx.cs" Inherits="uc.cpStatus" %>

<p>status indicator for special users</p>

In my master page I have this...
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="plain.master.cs"
Inherits="mp.plain" %>

<asp:ContentPlaceHolder ID="FirstSideBarContainer" runat="server">

<!-- side bar may be empty -->

</asp:ContentPlaceHolder>

and in the master page's code behind I have this...

protected void Page_Load(object sender, EventArgs e)

{

if (true == true)

{

ContentPlaceHolder ph1;

uc.cpStatus uc1;

ph1 = (ContentPlaceHolder)FindControl("FirstSideBarContainer");

uc1 = new uc.cpStatus();

ph1.Controls.Add(uc1);

}

}


I can step through and debug and every line gets executed without error.
When ph1 is initialized its value is null. When it's assigned the value of
the ContentPlaceHolder contol found by name it has a control count of 1
(that must be the HTML comment asa text node). After the
ph1.Controls.Add(uc1) statemment it has a control count of 2, so my user
control would seem to have been added successfully but nothing (other than
the original comment) appears in my placeholder in my page.

What am I doing wrong?
 
C

Cowboy \(Gregory A. Beamer\)

It looks like you are finding the container correctly, but the norm for
loading ASCX controls is like so:

Control uc1= LoadControl("UC1.ascx");

The rest of your code should work fine with this. There are some ways around
doing it this way, but it requires writing a lot of plumbing already in the
..NET libraries.
 
B

Brian Lowe

That does it!

Thanks!

Cowboy (Gregory A. Beamer) said:
It looks like you are finding the container correctly, but the norm for
loading ASCX controls is like so:

Control uc1= LoadControl("UC1.ascx");

The rest of your code should work fine with this. There are some ways
around doing it this way, but it requires writing a lot of plumbing
already in the .NET libraries.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top