Possible Duplicate:
Create a usercontrol instance programmatically in ASP.NET
Dear Friend i have the user control and i what to load the user control on the click of the button?
First create the panel or anything server control
<asp:Panel ID="plnExam" runat="server">
</asp:Panel>
then after on cs page
Control uc = this.LoadControl("~/UserControl/CollegesInExam.ascx");
plnExam.Controls.Add(uc);
Try this. (The google phrase you're looking for is "dynamically loading user control")
The key part is
Control FeaturedProductUserControl = LoadControl("YourControl.ascx")
This is in case you will want to load the UserControls via Ajax. Maybe that can be useful:
public static string GetControlHtml(string controlLocation)
{
Page page = new Page();
UserControl userControl = (UserControl)page.LoadControl(controlLocation);
//Disabled ViewState- If required
//userControl.EnableViewState = false;
HtmlForm form = new HtmlForm();
form.Controls.Add(userControl);
page.Controls.Add(form);
StringWriter textWriter = new StringWriter();
HttpContext.Current.Server.Execute(page, textWriter, false);
return CleanHtml(textWriter.ToString());
}
The controlLocation
is the path from the UserControl (e.g. "~/UserControls/NewUser.ascx").
This method renders the UserControl and returns its HTML ready to be loaded into a contaner (div) via Ajax.
精彩评论