Tuesday, March 16, 2010

Routine to Output Datatable to HTML

I had a request to build a report where the users can choose tables, columns, where and order by and create this report on the fly. I decided the best way to do it is to create a datatable from the users selections then output it to HTML, then I could print the page. So what I did was create a routine that would take a datatable and report title and return the string of everything in the table. Then I took the results and set a labels text property equal to the returned string. So here is the Method I created:

public string rptHTML(string rptTitle, DataTable rptData)
{
string outputHTML = "";
try
{
int cCount = rptData.Columns.Count;
StringBuilder strText = new StringBuilder( "<TABLE cellpadding=\"0\" cellspacing=\"0\"><TR><TD align=center colspan=\"" + cCount.ToString() + "\" style=\"border-style: solid; border-width: 1px; border-color: #000000;\"><H1>" + rptTitle + "</H1></TD></TR>");

strText.Append("<TR>");
foreach (DataColumn dc in rptData.Columns)
{
strText.Append("<TD style=\"border-style: solid; border-width: 1px; border-color: #000000;\">" + dc.ColumnName + "</TD>");

}
strText.Append("</TR>");
foreach (DataRow dr in rptData.Rows)
{
strText.Append("<TR>");
foreach (DataColumn dcr in rptData.Columns)
{
strText.Append("<TD style=\"border-style: solid; border-width: 1px; border-color: #000000;\">");

if (Convert.ToString(dr[dcr] + "") == "")
{
strText.Append("&nbsp;</TD>");
}
else
{
strText.Append(Convert.ToString(dr[dcr] + "") + "</TD>");
}
}
strText.Append("</TR>");
}
strText.Append("</TABLE>");
return strText.ToString();
}
catch (Exception ex)
{
outputHTML = "An Error occurred during processing of the selected items. Please try again or contact support.";

return outputHTML;
}
}

Enjoy!

No comments: