Posts Tagged ‘dynamically loading usercontrols in asp.net’

There are many times when you want to retrieve and manipulate the rendered HTML in code before its displayed to the user.Dynamic Loading of ASP.NET User Controls is required before you render the html & it can be done using the LoadControl Method.

Control control = this.LoadControl("~/WebUserControl.ascx") as Control;

If you try to use the LoadControl method of page,the drawback of this is that it has no control over where on the page the user control will actually appear.Say you have a button in user control & you are trying to load the user control with LoadControl method of page,then it will throw exception as below

Control ‘Button1’ of type ‘Button’ must be placed inside a form tag with runat=server.

Hence I suggest,use the LoadControl method of UserControl as below

UserControl userControl = new UserControl();
Control control = userControl.LoadControl("~/WebUserControl.ascx") as Control;

Below method allows to pass control and it will return the rendered HTML as a string

public string ControlRender(Control control)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htw = new HtmlTextWriter(sw);
control.RenderControl(htw);
return sb.ToString();
}

Advertisements