Load user control programmatically in html text

I am trying to make a user control into a string. The application is configured so that the user can use tokens, and user controls are displayed where tokens are found.

StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); HtmlTextWriter writer = new HtmlTextWriter(sw); Control uc = LoadControl("~/includes/HomepageNews.ascx"); uc.RenderControl(writer); return sb.ToString(); 

This code displays the control, but none of the events raised in the Page_Load of the control fires. There should be a repeater in control.

+6
user-controls
source share
3 answers

I used the following code provided by Scott Guthrie on his blog for quite some time:

 public class ViewManager { public static string RenderView(string path, object data) { Page pageHolder = new Page(); UserControl viewControl = (UserControl) pageHolder.LoadControl(path); if (data != null) { Type viewControlType = viewControl.GetType(); FieldInfo field = viewControlType.GetField("Data"); if (field != null) { field.SetValue(viewControl, data); } else { throw new Exception("ViewFile: " + path + "has no data property"); } } pageHolder.Controls.Add(viewControl); StringWriter result = new StringWriter(); HttpContext.Current.Server.Execute(pageHolder, result, false); return result.ToString(); } } 

The object data parameter allows you to dynamically load data into a user control and can be used to enter several elements into the control through an array or something similar.

This code fires all the usual events in the control.

Here you can read more

Relations Jesper Hauge

+13
source share

You will need to attach the control to the page by adding it to the collection of page controls or the control on the page. This will not solve all your problems unless you do something to explicitly disable rendering during the normal page rendering process.

+2
source share

I took the Haug / Scott Guthrie method above and modified it so you don't need to use reflection or change the UserControl to implement any special interface. A key has been added to the strongly typed callback that the RenderView method is above calls, rather than doing reflection.

I posted a help method and use here.

NTN, John

+1
source share

All Articles