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

  • Thread starter Thread starter Brian Lowe
  • Start date Start date
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?
 
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.

--
Gregory A. Beamer
MVP, MCP: +I, SE, SD, DBA

Subscribe to my blog
http://feeds.feedburner.com/GregoryBeamer#

or just read it:
http://feeds.feedburner.com/GregoryBeamer

********************************************
| Think outside the box! |
********************************************
 
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.

--
Gregory A. Beamer
MVP, MCP: +I, SE, SD, DBA

Subscribe to my blog
http://feeds.feedburner.com/GregoryBeamer#

or just read it:
http://feeds.feedburner.com/GregoryBeamer

********************************************
| Think outside the box! |
********************************************
 
Back
Top