Sunday, August 27, 2006

Alternating Row Colors

When displaying tabular data, it's often useful to alternate row colors to help differentiate the different rows.

So you've opened your recordset and have retreived an unknown number of rows, and now you want to display them. The following ASP code will build a table with alternating row colors:

<table>
<%
'set your counter to 0
i = 0

'loop through the record set
Do While Not rs.EOF
'increment the counter; I always do this 1st; no reason though
i = i + 1

'set background color to nothing
vBGColor = "white"

'check your counter; if alternate row set background color to gray
If i mod 2 = 1 then vBGColor = "gray"

'write the row, td and data
response.write("<tr bgcolor="&vBGColor&">")
response.write("<td>")
response.write(data goes here)
response.write("</td>")
response.write("</tr>")

'move to the next record
rs.movenext
Loop
%>
</table>
You could easily use more than 2 colors by changing and adding to the mod statement:
vBGColor="white"
If i mod 4 = 1 then vBGColor = "gray"
If i mod 4 = 2 then vBGColor = "yellow"
If i mod 4 = 2 then vBGColor = "beige"
You can use hex codes for the colors - you don't have to use names.

Here's a handy color chart with both names and hex codes.

No comments: