x'tian x'tian - 2 months ago 16
Vb.net Question

Dynamically add css class in td cell backend using Vb.net

My table current layout is like this :

<tr>
<td> Field1 </td>
<td> Field2 </td>
<td> Field3 </td>
<td> Field4 </td>
<td >Field5 </td>
</tr>

<tr>
<td> anothefield1 </td>
<td> anothefield2 </td>
<td> anothefield3 </td>
<td> anothefield1 </td>
<td> anothefield1 </td>
</tr>


What I want to achieve is to dynamically add a css class in every td per column. Like this :

<tr>
<td class = '1'> Field1 </td>
<td class = '2'> Field2 </td>
<td class = '3'> Field3 </td>
<td class = '4'> Field4 </td>
<td class = '5'> Field5 </td>
</tr>

<tr>
<td class = '1'> anothefield1 </td>
<td class = '2'> anothefield2 </td>
<td class = '3'> anothefield3 </td>
<td class = '4'> anothefield4 </td>
<td class = '5'> anothefield5 </td>
</tr>


and so on for the next tr.

How can I able to achieve that kind of layout?

Here's what I have so far

Dim dv As New DataView(ds.Tables(0))
Dim dvfilter As DataTable = dv.ToTable(True, {"date"})
Dim dt2 As New DataTable
For Each dtrow As DataRow In dvfilter.Rows

dv.RowFilter = "Total_Load < Potential_Load"
dt2 = dv.ToTable(False, "Field1", "Field2", "Field3", "Field4", "Field5"})
Next

Dim builder As New StringBuilder
builder.Append("<!DOCTYPE html><html>")
builder.Append("<head>")
builder.Append("</head>")
builder.Append("<body>")
builder.Append("<div class = 'email-section'>")
builder.Append("<table id = 'email' class='emai_table'>")
builder.Append("<thead>")
builder.Append("<tr>")
builder.Append("<th>Field1</th>")
builder.Append("<th>Field2</th>")
builder.Append("<th>Field3</th>")
builder.Append("<th>Field4</th>")
builder.Append("<th>Field5</th>")
For Each row As DataRow In dt2.Rows
builder.Append("<tr>")
For Each col As DataColumn In dt2.Columns
builder.Append("<td>" & row(col).ToString + " " & "</td>")
Next
builder.Append("</tr>")
builder.AppendLine()
Next
builder.Append("</tbody>")
builder.Append("</table>")
builder.Append("</div>")
builder.Append("</body>")
builder.Append("</html>")


Any help would be much appreciated. Thank you!

Answer

Create a new counter inside the outer For loop, then crank out its value and increment within the inner For loop.

For Each row As DataRow In dt2.Rows
    builder.Append("<tr>")
    Dim i as Integer
    i = 1
    For Each col As DataColumn In dt2.Columns
         builder.Append("<td class=""" & i & """>" & row(col).ToString + " " & "</td>")
         i = i + 1
    Next
         builder.Append("</tr>")
         builder.AppendLine()
Next

My VB is a little rusty, so it may not be 100% correct syntax, but I think you'll get the gist.