tags:

views:

46

answers:

6

Hi,

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.

Thanks!

A: 

Hmm. I'd javascript the table markup to some hidden field (which is a server control) before the form gets posted.

<div id="tablediv">
<table>...</table>
</div>

javascript:

var html = document.getElementById('tablediv').innerHTML;
document.getElementById('hfTableHtml').value = html;

EDIT: And yes, I'd worry about the request validation that is going to happen! You'd have to disable it or substitute those markup elements w/ something else before storing it into the hidden field

deostroll
A: 

Hi,

Since your table is a server control, you may use its RenderControl method to obtain the render result:

    public static string GetRenderResult(Control control) {
        using(StringWriter sw = new StringWriter(CultureInfo.InvariantCulture)) {
            using(HtmlTextWriter writer = new HtmlTextWriter(sw))
                control.RenderControl(writer);
            sw.WriteLine();
            return sw.ToString();
        }
    }
DevExpress Team
A: 

There is a couple of way I can think of how to do this. The easy would be to surround the table in a . Then on your vb/C# side simply call hold.innerhtml and it will return a string.

Ryan
Unfortunately that doesn't work "because the contents are not literal."
Wayne Werner
A: 

I used the following in the OnLoad method of my page to convert your table to a string of HTML:

    string html;
    using (var writer = new StringWriter())
    using (var xmlwriter = new HtmlTextWriter(writer))
    {
        this.resultsTable.RenderControl(xmlwriter);
        html = writer.ToString();
    }
kbrimington
+1  A: 

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.

sgriffinusa
A: 

Look into the HTMLAgilityPack (several SO posts reference it.)

LesterDove