tags:

views:

343

answers:

4

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>
A: 

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.

Pete OHanlon
+2  A: 

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());
James
+2  A: 
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>

CD
+1  A: 

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>

Rafe Lavelle