Dimi Dimi - 1 year ago 65
ASP.NET (C#) Question

How to render UserControl with parameters in ASP.NET

I use following code to render

UserControl
.

//render control to string
StringBuilder b = new StringBuilder();
HtmlTextWriter h = new HtmlTextWriter(new StringWriter(b));
this.LoadControl("~/path_to_control.ascx").RenderControl(h);
string controlAsString = b.ToString();


But I want to pass to
UserControl
some parameters so it should get data and update its properties just before rendering.

How it could be done?
Thank you!

Answer Source

As answered here:

Just load the control using the path of the .ascx file, cast to proper type and set the properties one by one:

MyControl myControl = (MyControl )Page.LoadControl("~/path_to_control.ascx");
myControl.Param1= 1;
myControl.Param2= 2;
myControl.RenderControl(h)

OR:

Page.LoadControl(typeof(MyControl), new object[] {1, 2}).RenderControl(h);