Wednesday, November 9, 2011

Output a VB.NET System.Data.DataTable to HTML

It is not very difficult to write this code snippet, but believe me, you will not find snippets as easy as this one. You don't need to read anything except this paragraph. The DataTable to use is called dt, the HTML code is attached to the page as a Literal Control.

Dim html As New System.Text.StringBuilder
Dim i as Integer
html.AppendLine("<table><tr>")
For Each col As System.Data.DataColumn In dt.Columns
   html.AppendLine("<th>" & col.Caption & "</th>")
Next
html.AppendLine("</tr>")
For Each dr As System.Data.DataRow In dt.Rows
   html.AppendLine("<tr>")
   For i = 0 To dr.ItemArray.Length - 1
      html.AppendLine("<td>" & dr.ItemArray(i).ToString & "</td>")
   Next
   html.AppendLine("</tr>")
Next
html.AppendLine("</table>")
Page.Controls.Add(New System.Web.UI.LiteralControl(html.ToString))

No comments:

Post a Comment