Last active
February 11, 2019 19:10
-
-
Save lukas-shawford/13d57dca75b385f0a359 to your computer and use it in GitHub Desktop.
VB.NET: Convert DataTable to HTML table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
' | |
' 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