Often we need to call RenderControl on a UserControl to get the rendered HTML and be able to pass it to a PDF or Report generator. This can be problematic because you will get exceptions saying that the control must be within a FORM tag with runat=server. Also, If there are any AJAX script - related controls such as TextBoxExtenders, you will be warned that a ScriptManager is required. Here is an easy way to avoid these issues and get back "clean" HTML:
public static string RenderUserControl(Control ctrl)
{
Control control = null;
const string STR_BeginRenderControlBlock = "";
const string STR_EndRenderControlBlock = "";
StringWriter tw = new StringWriter();
Page page = new Page();
page.EnableViewState = false;
HtmlForm form = new HtmlForm();
form.ID = "__temporanyForm";
page.Controls.Add(form);
form.Controls.Add(new LiteralControl(STR_BeginRenderControlBlock));
// add a ScriptManager to prevent Ajax Extender control exceptions
ScriptManager m = new ScriptManager();
form.Controls.Add(m);
form.Controls.Add(ctrl);
form.Controls.Add(new LiteralControl(STR_EndRenderControlBlock));
HttpContext.Current.Server.Execute(page, tw, true);
string Html = tw.ToString();
int start = Html.IndexOf("");
int end = Html.Length - start;
Html = Html.Substring(start, end);
// return the rendered HTTML and send it into the PDF generator
return Html;
}