How to dynamically add user controls within a user control

荒凉一梦 提交于 2019-12-25 16:49:46

问题


I want to create a user control that will again contain a user control that will be dynamically generated and can be repeated N times with respect to data present in data table.

How can i do this.


回答1:


You want to use TemplateControl.LoadControl (which both Page, UserControl and MasterPage inherit from). You need to do this during the Init event for postback stuff to work.

void Page_Init(Object Sender, EventArgs e) {
    var control = LoadControl("Awesome.ascx");
    // ... Magic!
}



回答2:


Place a placeholder control on the parent user control:

<asp:PlaceHolder runat="server" id="phMainHolder" />

In the Page_Load or Page_Init event you simply instantiate the child user controls in a for(each) loop and add them to the placeholder like for example:

for(int i = 0; i < 10; i++) {
    ChildUC child = new ChildIC();
    phMainHolder.Controls.Add(child);
}

This is the bare minimum to do it. You can opt to set properties or whatever on your child controls of course.

The class ChildUC is a fictive class name for this example. Use the class, and if needed use the namespace as extra in which it is defined, of the user control you want to use.



来源:https://stackoverflow.com/questions/3297358/how-to-dynamically-add-user-controls-within-a-user-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!