How can I extract raw HTML from dynamic server controls in ASP.NET?

Hello all,

     Does anyone know of a way to "extract" the HTML from dynamically created controls in ASP.NET (VB) and save it to a string variable? Here is what I'm trying to do: Ive got a very nicely designed Database driven table that is adding cells and rows to the table control per iteration of DbRow. When the user clicks a button, I am going to send them an HTML-based email of that table with all of the formatting, etc.  Instead of *rebuilding* the table piece by piece into an html string, is there a way just to extract the raw HTML with all of the formatting so that I can include it into a message body?  Something like : TableControl.ToHTML(), if it existed?  The good news is: all of the table cells just contain dynamic labels and data.  Nothing funky. No dropdowns, no textboxes, nada.  Hopefully this makes sense. :)

Any help is appreciated!

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

You can get the generated html for a control as a string by using its RenderControl() method.


StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);

string output = sw.ToString();

You'll also need to override the method VerifyRenderingInServerForm method on the page:

public override void VerifyRenderingInServerForm(Control control)

Carl TawnSystems and Integration DeveloperCommented:
Well, in the simplest scenario you ca do something like:

            System.IO.StringWriter sw = new System.IO.StringWriter();
            HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);

            string content = htmlWriter.ToString();

Although this gets a little more fiddly depending on where you want to run the code from.

This article should help:

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
slugovskyAuthor Commented:
This worked famously! Thank you so much!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.