Alternate Row Colors

The code below will display the results from a database in alternate table row colors. The code uses the VBScript Mod operator. The VBScript Mod operator divides two numbers and returns the remainder. So in our code if our iRow counter is divisible by 2 leaving a remainder of 0 then we set the table row to <tr bgcolor=""#F7F7F7"">.

<%@ Language="VBScript" %>
<% Option Explicit %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Alternate row colors</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<%
'declare your variables
Dim Connection, Recordset
Dim sSQL, sConnString, iRow

'declare SQL statement that will query the database
sSQL="SELECT FirstName, SurName FROM tblFriends"

'define the connection string, specify database
'driver and the location of database
sConnString="PROVIDER=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & Server.MapPath("Friends.mdb")

'create an ADO connection and recordset
Set connection = Server.CreateObject("ADODB.Connection")
Set recordset = Server.CreateObject("ADODB.Recordset")

'Open the connection to the database
connection.Open sConnString

'Open the recordset object, execute the SQL statement
recordset.Open sSQL, connection

'first of all determine whether there are any records
If Recordset.EOF Then
Response.Write("No records returned.")
Else

Response.write "<table width=""100%"" border=""1"">"
'iRow is used as a table row counter
iRow=0
'If there are records then loop through the fields
Do While Not recordset.EOF

'Use Mod operator
If iRow Mod 2 = 0 Then
response.write "<tr bgcolor=""#F7F7F7"">"
Else
response.write "<tr bgcolor=""#CCCCCC"">"
End If

response.write "<td>"
response.write recordset("FirstName") & " " & recordset("SurName")
response.write "</td>"

'Increment iRow counter
iRow=iRow + 1

'move on to the next record
Recordset.MoveNext
Loop

response.write "</tr>"
Response.write "</table>"

End If

'close the connection and recordset objects and free up resources
Recordset.Close
Connection.Close
Set Recordset = Nothing
Set Connection = Nothing
%>
</body>
</html>

Get the best asp web hosting provider now and save 30%

Advertisements



MembersPro

MembersPro PayPal - ASP Membership software

Plug and play ASP membership script that integrates with PayPal to let you charge recurring membership fees.