Monday, October 30, 2006

Getting HTML generated by any control in ASP.NET

Sometimes situation arises in ASP.NET where you want to get the HTML that will be generated by the control without actually rendering the page. For e.g.: When getting the result from an AJAX call, you want to get the HTML generated by say Datagrid, so that you can directly replace the contents of the caller page.

In ASP.NET you can get the HTML of any control by creating a new instance of StringWriter. Using this instance of StringWriter create a new instance of HtmlTextWriter and then rendering the control to this HtmlTextWriter by using RenderControl() method. This method is defined in Control class; therefore every control will have this method. After rendering the control get the HTML from the StringWriter using ToString() method.

Code(C#) is as below:

System.IO.StringWriter stringWriter = new System.IO.StringWriter();
HtmlTextWriter newHtmlWriter = new System.Web.UI.HtmlTextWriter(stringWriter);
yourControlId.RenderControl(newHtmlWriter);
string output = stringWriter.ToString();


If you are rendering a Datagrid or any other control that has a textbox with "runat='server'" tag then this will not work. Because for every textbow with "runat='server'" tag you need to have a "form" with "runat='server'" tag. So if your textbox in Datagrid is a read-only textbox then better replace it with "label" so that the HTML can be rendered correctly.

2 comments:

Ranv said...

Nice, this is exactly what I needed. Thanks!

Anonymous said...

Sorry for my bad english. Thank you so much for your good post. Your post helped me in my college assignment, If you can provide me more details please email me.