Skip to content

Instantly share code, notes, and snippets.

@lukas-shawford
Last active February 11, 2019 19:10
Show Gist options
  • Save lukas-shawford/13d57dca75b385f0a359 to your computer and use it in GitHub Desktop.
Save lukas-shawford/13d57dca75b385f0a359 to your computer and use it in GitHub Desktop.
VB.NET: Convert DataTable to HTML table
'
' An elegant way of converting a DataTable into an HTML table using VB.NET.
'
' This uses a feature of VB.NET called XML Literals:
' http://msdn.microsoft.com/en-us/library/bb384629.aspx
'
' This allows you to write HTML/XML directly in the code, and use ASP.NET-style
' interpolation tags to include LINQ expressions in the body.
'
' A couple notes:
' - You must add a reference to System.Xml.Linq to use XML Literals
' - Unfortunately, XML Literals are not available in C#.
' - The DataTable must be passed ByVal, not ByRef, as you will otherwise
' not be able to use it within lambda expressions.
' - The casting of dt.Columns and dt.Rows is technically not necessary
' for the code to run, but Intellisense won't work without it.
'
'
Public Function ConvertDataTableToHTML(ByVal dt As DataTable) As String
ConvertDataTableToHTML =
<table>
<thead>
<tr>
<%=
From col As DataColumn In dt.Columns.Cast(Of DataColumn)()
Select <th><%= col.ColumnName %></th>
%>
</tr>
</thead>
<tbody>
<%=
From row As DataRow In dt.Rows.Cast(Of DataRow)()
Select
<tr>
<%=
From col As DataColumn In dt.Columns.Cast(Of DataColumn)()
Select <td><%= row(col) %></td>
%>
</tr>
%>
</tbody>
</table>.ToString()
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment