Public Shared Function ToHtml(ByVal dt As DataTable) As System.Xml.Linq.XDocument Dim resultHtml = _ <?xml version="1.0"?> <table name=<%= dt.TableName %>> <tr class="row0"><%= dt.Columns.Cast(Of DataColumn)().Select(Function(cl, idx) <th class=<%= "col" + (idx + 1).ToString() %>><%= cl.ColumnName %></th>) %></tr> <%= dt.AsEnumerable().Select(Function(rw, rowidx) <tr class=<%= "row" + (rowidx + 1).ToString() %>> <%= dt.Columns.Cast(Of DataColumn)().Select(Function(cl, idx) <td class=<%= "col" + (idx + 1).ToString() %>><%= rw(cl.ColumnName) %></td>) %> </tr>) %> </table> Return resultHtml End Function
Thursday, February 17, 2011
Linq with XML literals
Every once in awhile I write something in VB that feels like the days-long-gone when I did crazy-kung-fu Perl/Ruby. It's a strange mix of being proud, shocked, and slightly embarassed, but thrilled that the problem is fully solved. Is it ugly - like a pitbull with lipstick, youbetcha! But still, for those who really dig Linq and think that XML literals in VB are pretty slick, check this out - it converts a System.Data.DataTable to an XHTML table that I could then use in a quick-and-dirty e-mail alert I needed to send out based on the results of some ad-hoc queries.