Tuesday, December 23, 2008

Convert DataTable to HtmlTable in c#

After looking around for ten minutes, or so, and not finding a decent example if converting a System.Data.DataTable to System.Web.UI.HtmlControls.HtmlTable in c# (you can find some great examples of over-complexity and bad design), I wrote one.

This was not fun, it was easy. This is the most basic implementation I could come up with.

In the hopes of allowing someone else to avoid it, here is the code:

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;
}

As a challenge, can you come up with a shorter way to write this code (or something more functionally complex? Here are some thoughts that I had:

1. WriteXml and use Xslt to translate to Html
2. WriteXml and then use LinqToXml to translate

Ideas? Post them.

Resources:
HtmlTable Class
System.Data.DataTable