views:

764

answers:

4

I have a a repeater that is bound to some data.

I bind to the ItemDataBound event, and I am attempting to programmaticly create a UserControl:

In a nutshell:

void rptrTaskList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    CCTask task = (CCTask)e.Item.DataItem;

    if (task is ExecTask)
    {
        ExecTaskControl foo = new ExecTaskControl();
        e.Item.Controls.Add(foo);
    }
}

The problem is that while the binding works, the user control is not rendered to the main page.

Any ideas?

+1  A: 

Eh, figured out one way to do it:

ExecTaskControl foo = (ExecTaskControl)LoadControl("tasks\\ExecTaskControl.ascx");

It seems silly to have a file depedancy like that, but maybe thats how UserControls must be done.

FlySwat
+1  A: 

You could consider inverting the problem. That is add the control to the repeaters definition and the remove it if it is not needed. Not knowing the details of your app this might be a tremendous waste of time but it might just work out in the end.

Craig
Agree, this sounds like a much better solution. But that is not the same as that being applicable in that specific situation.
Pete
A: 

I think @Craig is on the right track depending on the details of the problem you are solving. Add it to the repeater and remove it or set Visible="false" to hide it where needed. Viewstate gets tricky with dynamically created controls/user controls, so google that or check here if you must add dynamically. The article referenced also shows an alternative way to load dynamically:

Control ctrl=this.LoadControl(Request.ApplicationPath +"/Controls/" +ControlName);

JasonS
A: 

If you are going to do it from a place where you don't have an instance of a page then you need to go one step further (e.g. from a webservice to return html or from a task rendering emails)

var myPage = new System.Web.UI.Page();
var myControl = (Controls.MemberRating)myPage.LoadControl("~/Controls/MemberRating.ascx");

I found this technique on Scott Guithrie's site so I assume it's the legit way to do it in .NET

abigblackman