Dimi Dimi - 1 year ago 146
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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download