9

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>
3
  • You should explain your question a little more... Commented Oct 6, 2009 at 7:39
  • 7
    What is a C# table? Commented Oct 6, 2009 at 7:45
  • What do you want to do? When do you need that table? Commented Oct 6, 2009 at 8:00

4 Answers 4

22
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>

Sign up to request clarification or add additional context in comments.

Comments

4

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());

Comments

1

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>

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.