ASP.NET Get table html

10,474

Initially I though to just use the InnerHtml or InnerText methods, but these are not supported on the HtmlTable class.

So what if we use the Render method? Something like this (take from Anatoly Lubarsky)?

public string RenderControl(Control ctrl) 
{
    StringBuilder sb = new StringBuilder();
    StringWriter tw = new StringWriter(sb);
    HtmlTextWriter hw = new HtmlTextWriter(tw);

    ctrl.RenderControl(hw);
    return sb.ToString();
}

This method could obviously be cleaned up to handle closing the writers, etc.

Share:
10,474
Wayne Werner
Author by

Wayne Werner

I'm a husband to my beautiful wife, father to our children, Computer Science graduate from University of Central Arkansas. I love my wife, our children, computers, playing guitar (especially singing/playing for my wife and/or kids), bicycling (including taking my kids for rides in my bike trailer), woodworking, airbrushing, digital and traditional artistry, playing games with my family (traditional and digital), my poor Chevette that I had to sell, throwing knives, firearms, knot tying, rope making, whip making, and really just learning new stuff in general. If I don't know about it I probably want to learn about it, if only so I can make informed decisions about it. My three favorite programming languages are Python, Lisp, and Assembly (though I'm not sure about the order of those last two languages...). I think the CANSPAM act is one of the dumbest pieces of legislation in the history of the universe I love Python and HTML+Javascript. I'm #SOreadytohelp (I really want a t-shirt, what can I say?)

Updated on June 04, 2022

Comments

  • Wayne Werner
    Wayne Werner about 2 years

    I have a table on my ASP.net page something like this:

    <table runat="server" id="resultsTable"></table>
    

    I dynamically add content to the table, and it works just fine. However, I want to get the HTML of the table once I've added the dynamic content, i.e. something like this (formatting isn't important, I've just added it)

    <table runat="server" id="resultsTable">
      <tr>
        <td>Hello!</td>
      </tr>
      <tr>
        <td>Goodbye!</td>
      </tr>
    </table>
    

    I need the result as a string. Obviously I could do some looping and build my own table with the data, but I'd prefer to not do that if at all possible.