ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

ConvertDataTableToHTML

Extension Method which converts Datatable to HTML table

Source

public static string ConvertDataTableToHTML(this DataTable dt)
{
    string html = "<table>";
   
        //add header row
        html += "<tr>";
        for (int i = 0; i < dt.Columns.Count; i++)
            html += "<td>" + dt.Columns[i].ColumnName + "</td>";
        html += "</tr>";
        //add rows
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            html += "<tr>";
            for (int j = 0; j < dt.Columns.Count; j++)
                html += "<td>" + dt.Rows[i][j].ToString() + "</td>";
            html += "</tr>";
        }
        html += "</table>";
   
    return html;
}

Example

DataTable dt = new DataTable();
//////////////
Populate your Table here
/////////////

string htmlTable = dt.ConvertDataTableToHTML();

Author: Vick

Submitted on: 29 okt. 2015

Language: C#

Type: Vick

Views: 4665