Call the function DataTableToHTMLTable as pass the DataTable as parameter. The return value would be a formatted HTML table.
Public Function DataTableToHTMLTable(ByVal inTable As DataTable) As String Dim dString As New StringBuilder dString.Append("<table>") dString.Append(GetHeader(inTable)) dString.Append(GetBody(inTable)) dString.Append("</table>") Return dString.ToString End Function Private Function GetHeader(ByVal dTable As DataTable) As String Dim dString As New StringBuilder dString.Append("<thead><tr>") For Each dColumn As DataColumn In dTable.Columns dString.AppendFormat("<th>{0}</th>", dColumn.ColumnName) Next dString.Append("</tr></thead>") Return dString.ToString End Function Private Function GetBody(ByVal dTable As DataTable) As String Dim dString As New StringBuilder dString.Append("<tbody>") For Each dRow As DataRow In dTable.Rows dString.Append("<tr>") For dCount As Integer = 0 To dTable.Columns.Count - 1 dString.AppendFormat("<td>{0}</td>", dRow(dCount)) Next dString.Append("</tr>") Next dString.Append("</tbody>") Return dString.ToString()
End Function
To create DataTable, you can read this article:
Creating and Using Datatables in VB.net
Thanks for the example it helped me with what I was working on. Just to note though, the getbody() should be 'Return dString.ToString()' as it is, it just returns a blank string every time.
ReplyDelete