Dimi Dimi - 11 months ago 51
ASP.NET (C#) Question

How to render UserControl with parameters in ASP.NET

I use following code to render


//render control to string
StringBuilder b = new StringBuilder();
HtmlTextWriter h = new HtmlTextWriter(new StringWriter(b));
string controlAsString = b.ToString();

But I want to pass to
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;


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