I have UserControl that has asp control(<asp:Button runat=”server” ID=”btn” />) and I want to render it.
I tried 1:
Page loader = new Page();
Control ctrl = loader.LoadControl("WebUserControl1.ascx");
loader.Controls.Add(ctrl);
loader.ProcessRequest(context);
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htw = new HtmlTextWriter(sw);
loader.RenderControl(htw);
It doesn’t works because it says that each control that has runat=”server” must be in Form.
I also tried 2:
Because loader.Form is null, I create HtmlForm and added the ctrl to it and then added HtmlForm to loader’s Control, BUT it says that it has 2 HtmlForm. So, instead I “injected” HtmlForm to loader like this
Page loader = new Page();
HtmlForm form = new HtmlForm();
var method = loader.GetType().GetMethod("SetForm", BindingFlags.NonPublic | BindingFlags.Instance);
method.Invoke(loader, new object[] { form });
Control ctrl = loader.LoadControl("WebUserControl1.ascx");
loader.Form.Controls.Add(ctrl);
loader.ProcessRequest(context);
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htw = new HtmlTextWriter(sw);
loader.RenderControl(htw);
Now no error is occurred, BUT StringWriter is empty
Where is my mistake.
Please don’t tell me to add Page to solution and override OnRender. I want to do it as I mentioned above.
Thank you
Dont use Form.Controls.Add,
Add a PlaceHolder control to Form. And add control to PlaceHolder.
PlaceHolder.Controls.Add(ctrl);
Try this.