Alternate Row Color

If you need to display a long list of database records on your web page, it might be a good idea to alternate the colors of each row so that each record stands out and is easier to read. Here is an easy way to handle it.

The first thing you need to do is create a database called MyDatabase. Then create a table called tblData with these fields:
ID – autonumber
Item – text field
DateEntered – date/time field *** Also add “=Date()” as the default value for the field. This will add the date automatically, everytime a new record is entered. ***

Then, start adding some data to your database. If you leave the database empty, the script will simply display a blank page.

Next, create a page called /AlternateRowColor.asp and copy the below code into your page:

<!--#INCLUDE VIRTUAL="/includes/connection.asp" -->

<%
DIM mySQL, objRS
mySQL = "SELECT * FROM tblData"
Set objRS = Server.CreateObject("ADODB.Recordset")
objRS.Open mySQL, objConn, adOpenKeySet

<table>
<tr><td>These are my database records.</td></tr>

<%
DIM iRecordCount
iRecordCount = 0
DO WHILE NOT objRS.EOF

IF iRecordCount Mod 2 = 0 THEN
%>
<tr bgcolor="#CCCCCC">
<%
ELSE
%>
<tr bgcolor="#FFFFFF">
END IF
<td> <% objRS("Item") %> </td> </tr>
</table>

<%
iRecordCount = iRecordCount + 1
objRS.MoveNext
Loop

objRS.Close
Set objRS = Nothing
objConn.Close
Set objConn = Nothing
%>

This will display the first record in gray and the second record in white and will continue to alternate the color of each row displayed on your page.

< Back to ASP Scripts