Extension method to Convert DataTable to HTML Table

By [)ia6l0 iii

Snippet to convert data table to HTML Table

public static string ToHtmlTable(this DataTable myDataTable)
{
            StringBuilder sb = new StringBuilder();
            
            //start the table.
            sb.AppendLine(""<table width='100%' border='2'>"");
            
            //start the row.
            sb.AppendLine(""<tr>"");

            //write the columns.
            for (int columnCounter = 0; columnCounter <= myDataTable.Columns.Count - 1; columnCounter++)
            {
                sb.AppendLine(string.Format(""<th align='left'>{0}</th>"", myDataTable.Columns[columnCounter]                                   .ColumnName));
            }

            //close the row.
            sb.AppendLine(""</tr>"");

            //add the data.
            for (int rowCounter = 0; rowCounter <= myDataTable.Rows.Count - 1; rowCounter++)
            {
                sb.AppendLine(""<tr>"");
                for (int columnCounter = 0; columnCounter <= myDataTable.Columns.Count - 1; columnCounter++)
                {
                    sb.AppendLine(""<td >"" +
                        myDataTable.Rows[rowCounter][columnCounter].ToString() + ""</td>"");
                }
                sb.AppendLine(""</tr>"");
            }

            //close the table and create a new line.
            sb.AppendLine(""</table><br>"");

            //return the html.
            return sb.ToString();
}

Extension method to Convert DataTable to HTML Table  (3604 Views)