Reputation: 9129
Can I convert a dynamically created c# table to an html string ?
I mean like this;
Table t = new Table();
TableRow tr = new TableRow();
TableCell td = new TableCell();
td.Text = "Some text... Istanbul";
tr.Cells.Add(td);
t.Rows.Add(tr);
t.ToString();
Response.Write(t.ToString());
I wanna see in the page;
<table> <tr> <td> Some text...
Istanbul </td> <tr> </table>
Upvotes: 9
Views: 25663
Reputation: 74176
using (StringWriter sw = new StringWriter())
{
Table t = new Table();
TableRow tr = new TableRow();
TableCell td = new TableCell {Text = "Some text... Istanbul"};
tr.Cells.Add(td);
t.Rows.Add(tr);
t.RenderControl(new HtmlTextWriter(sw));
string html = sw.ToString();
}
result:
<table border="0"><tr><td>Some text... Istanbul</td></tr></table>
Upvotes: 22
Reputation: 5769
Just have a Panel on the page, and add the table to the Panel.
So, in your aspx file:
<asp:Panel id="MyPanel" runat="server" />
and in your code behind:
MyPanel.Controls.Add(t)
// where 't' is your Table object
That places the table in your panel, which renders the Table as Html to the page, in a nice <div>
Upvotes: 1
Reputation: 82136
You should update your question to be a little more informative. However, I will assume you are using a DataGrid:
StringBuilder stringBuilder = new StringBuilder();
StringWriter stringWriter = new StringWriter(stringBuilder);
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
DataGrid1.RenderControl(htmlWriter);
string dataGridHTML = Server.HtmlEncode(stringBuilder.ToString());
Upvotes: 4
Reputation: 9144
Yes. It must become a string at some point for it to be rendered out to the browser - one way to do it is to take this and extract the table out of it.
Upvotes: 0