tags:

views:

213

answers:

3

Basically I want to create a user control in code behind, DataBind() it and then insert the control into current page

I'm currently trying this:

var comment = new IncidentHistoryGroupComment();
comment.LoadControl("~/Controls/IncidentHistoryGroupComment.ascx");
comment.LoadTemplate("~/Controls/IncidentHistoryGroupComment.ascx");
comment.InitializeAsUserControl(this);
comment.AttachmentActions = group.HastAttachmentActions ? group.AttachmentActions : null;
comment.Comment = group.Comment;
comment.NextStep = group.NextStep;
comment.IsInitiationStep = group.InitializationEntry != null;
comment.DataBind();

But still all controls inside it are null. For example i have a pane with id pnlComments and when I try to access it in IncidentHistoryGroupComment.DataBind() method I get null. I also checked Controls property to see if there is something there but Controls.Count == 0

So the question is how to correctly initialize a user control from code behind so that all controls would be assigned to their instances in IncidentHistoryGroupComment.designer.cs so I could access them easily.

+1  A: 

Should be something like this:

 var comment = (IncidentHistoryGroupComment)Page.LoadControl("~/Controls/IncidentHistoryGroupComment.ascx");

Then you just insert into the control tree

Lars Mæhlum
A: 
MyControl myControl = (MyControl)LoadControL("~/MyControl.ascx");

I changed the name of your control for readability.

Andrew Robinson
A: 

I think your problem is not about instantiating the user control.

In your DataBind event put this code at first line :

this.EnsureChildControls();

It instantiates all child controls if they're not istantiated. I mean it checks child controls and calls createChildControl if it's necessary.

Canavar