Dynamically load user control?

G

Green

Hi, All
I need to dynamically load a user control and change some properties on
the user control, and display in the aspx page. Unfortunately I failed,
nothing appears.

Please help me look at, thanks.

Comment c = (Comment) Page.LoadControl("Comment.ascx");

Label time = new Label();

time.Text = "5/11/2005";

Label comment = new Label();

comment.Text = "Test ;)";

LinkButton lb = new LinkButton();

lb.Text = "test button";


c.DateTime = time;

c.Comments = comment;

c.Who = lb;

CommentHolder.Controls.Add(c);
 
K

Karl Seguin

I'd love to see how comments.aspx.cs is written...

sounds like you have:

public class Comment : UserControl{

public Label DateTime;
void page_load(){}
}

and in the ascx part you have
<asp:Label id="DateTime" runat="server" />




you need to understand control instantiation. <asp:label id="dateTime"
runat="server" /> creates a new instance...

when you do:

c.DateTime = new Label(); you are creating a new instance, which overwrites
the ascx one and never gets rendered.

instead you should be doing osmethin glike:


public class Comment : UserControl{

protected Label dt;
public string DateTime{
get { return dt.Text;}
set { dt.Text = value;}
}
void page_load(){}
}
....
<asp:Label id="dt" runat="server" />

and simply do

c.DateTime = "5/11/2005"; //should be a DateTime instead of a string??

Karl
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top