Here i am displaying you a demo of creating a html table using all the columns and rows of datatable in c#.
Suppose we have a datatable which contains data regarding items and we want this data to be sent to users through email as html(email`s body to be html). So the simplest way to show the data in email body will be to convert the data and column of datatable in a html table and then use the html as body of email. In this scenario the following code will help you in creating html table.
public static string CreateHTMLTableFromDatatable(DataTable dtItems)
{
string html = "<table>";
//add header row
html += "<tr>";
for (int i = 0; i < dtItems.Columns.Count; i++)
html += "<td>" + dtItems.Columns[i].ColumnName + "</td>";
html += "</tr>";
//add rows
for (int i = 0; i < dtItems.Rows.Count; i++)
{
html += "<tr>";
for (int j = 0; j < dtItems.Columns.Count; j++)
html += "<td>" + dtItems.Rows[i][j].ToString() + "</td>";
html += "</tr>";
}
html += "</table>";
return html;
}
In above code, First we are iterating the columns of datatable and adding table header and then we are iterating the data rows of datatable to add the data in respective column.
I hope this quick and dirty implementation will help you.
0 Comment(s)