Generate HTML table from list of objects and convert to string

Ankaprasad
Posted by Ankaprasad under C# category on | Points: 40 | Views : 750
 private static string GetHtmlTable(List<Quote> quotes)
{
DataTable dt = new DataTable();
dt.Columns.Add("Company");
dt.Columns.Add("Discount");
dt.Columns.Add("Premium");
dt.Columns.Add("Type");
dt.Columns.Add("Idv");

foreach (var item in quotes)
{
DataRow dr = dt.NewRow();
dr["Company"] = item.CompanyName;
dr["Discount"] = item.Discount;
dr["Premium"] = string.Format("{0:0.##}", item.Premium);
dr["Type"] = item.Type;
dr["Idv"] = string.Format("{0:0.##}", item.Idv);
dt.Rows.Add(dr);
}
return ConvertToHtml(dt);
}



 private static string ConvertToHtml(DataTable dt)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.AppendLine("<html>");
sb.AppendLine("<body>");
sb.AppendLine("<table BORDER ='1'>");
foreach (DataColumn dc in dt.Columns)
{
sb.AppendFormat("<th align = 'center'>{0}</th>", dc.ColumnName);
}

foreach (DataRow dr in dt.Rows)

{
sb.Append("<tr>");
foreach (DataColumn dc in dt.Columns)
{
string cellValue = dr[dc] != null ? dr[dc].ToString() : "";
sb.AppendFormat("<td>{0}</ td>", cellValue);
}
sb.AppendLine("</tr>");
}
sb.AppendLine("</table>");
sb.AppendLine("</body>");
sb.AppendLine("</html>");
return sb.ToString();
}

Comments or Responses

Login to post response