Getting InnerHtml HTMLTable C #

This function returns an HTML table:

private HtmlTable ConvertToHtml(DataTable dataTable) { var htmlTable = new HtmlTable(); if (dataTable == null) return htmlTable; //null reference, empty table HtmlTableRow htmlRow = new HtmlTableRow(); htmlTable.Rows.Add(htmlRow); foreach (DataColumn column in dataTable.Columns) htmlRow.Cells.Add(new HtmlTableCell() { InnerText = column.ColumnName }); foreach (DataRow row in dataTable.Rows) { htmlRow = new HtmlTableRow(); htmlTable.Rows.Add(htmlRow); foreach (DataColumn column in dataTable.Columns) htmlRow.Cells.Add(new HtmlTableCell() { InnerText = row[column].ToString() }); } return htmlTable; } 

I would like to know how I can get innerHTML HtmlTable .

I am currently doing this:

  var bodyhtml = ConvertToHtml(r.tblSalesVolume); MessageBox.Show(bodyhtml.InnerHtml); 

but he says that he does not have such a property.

How to get HTML code for a table?

+2
html c # html-table winforms
source share
3 answers

You can use the HtmlTable.RenderControl () method.

Example:

 StringBuilder sb = new StringBuilder(); StringWriter tw = new StringWriter(sb); HtmlTextWriter hw = new HtmlTextWriter(tw); HtmlTable.RenderControl(hw); String HTMLContent = sb.ToString(); 
+4
source share

You wrote InnerText as a property, you have to write InnerHtml . And there is no need for ToString() , since HtmlTable.InnerHtml is a string.

See HtmlTable.InnerHtml


why don't you just create html instead of using HtmlTable? instead of TableRow, you simply use before "cell" -loop and after "cell" -loop. and when you write a cell, you just write "value". "There is really no reason to use an HtmlTable to create an html table row.


 private string ConvertToHtml(DataTable dataTable) { StringBuilder sb = new StringBuilder(); sb.Append("<table>"); if (dataTable != null) { sb.Append("<tr>"); foreach (DataColumn column in dataTable.Columns) sb.AppendFormat("<td>{0}</td>", HttpUtility.HtmlEncode(column.ColumnName)); sb.Append("</tr>"); foreach (DataRow row in dataTable.Rows) { sb.Append("<tr>"); foreach (DataColumn column in dataTable.Columns) sb.AppendFormat("<td>{0}</td>", HttpUtility.HtmlEncode(row[column])); sb.Append("</tr>"); } } sb.Append("</table>"); return sb.ToString(); } 
+2
source share

Based on Leon's answer using HtmlTable.RenderControl () with OP code:

 StringBuilder sb = new StringBuilder(); StringWriter tw = new StringWriter(sb); HtmlTextWriter hw = new HtmlTextWriter(tw); var bodyhtml = ConvertToHtml(r.tblSalesVolume); bodyhtml.RenderControl(hw); MessageBox.Show(sb.ToString()); 
+1
source share

All Articles