0

我有一个绑定到某些数据的中继器。

我绑定到ItemDataBound事件,并尝试以编程方式创建UserControl

简而言之:

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);
    }
}

问题是,虽然绑定有效,但用户控件并未呈现到主页。

4

4 回答 4

1

嗯,想出了一种方法:

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

拥有这样的文件依赖似乎很愚蠢,但也许这就是必须完成 UserControls 的方式。

于 2008-08-26T22:18:34.177 回答
1

你可以考虑把问题倒过来。也就是说,将控件添加到中继器定义中,如果不需要,则将其删除。不知道您的应用程序的详细信息这可能会浪费大量时间,但最终可能会奏效。

于 2008-08-27T00:38:23.060 回答
0

I think that @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);

于 2008-08-27T04:15:45.597 回答
0

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

于 2008-08-27T04:52:59.797 回答