• Post Reply Bookmark Topic Watch Topic
  • New Topic

alternate table row bgcolor using if/else  RSS feed

 
Thom Spencer
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello:
Using JSP, I'm trying to alternate the <tr bgcolor> when out putting from a database. Using the code below, I am able to out put the data, but the bgcolor stays the same on every row.
<%
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc dbc:jsptest");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM family");
while (rs.next()){
String familyId = rs.getString("ID");
String firstName = rs.getString("first_name");
String lastName = rs.getString("last_name");
String telephoneNumber = rs.getString("telephone_number");
int swapColor = 0;
if (swapColor == 0)
{
out.print("<tr bgcolor='#f4f4f4'>");
out.print("<td>" + familyId + "</td>");
out.print("<td>" + firstName + "</td>");
out.print("<td>" + lastName + "</td>");
out.print("<td>" + telephoneNumber + "</td></tr>");
swapColor = swapColor + 1;
}
else
{
out.print("<tr bgcolor='#cccccc'>");
out.print("<td>" + familyId + "</td>");
out.print("<td>" + firstName + "</td>");
out.print("<td>" + lastName + "</td>");
out.print("<td>" + telephoneNumber + "</td></tr>");
swapColor = 0;
}
}
con.close();
%>
If anybody can identify my mistake and post a suggestion or solution, I would appreciate it.
Thanks
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you do a view-source, is the HTML being generated with alternating colors? Incidently, my HTML 4 reference says that bgcolor is a deprecated usage.
Bill
 
Angela Lamb
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem is that you are setting swapColor to 0 for each iteration of the loop. Take the line int swapColor = 0; and move it outside of the while loop.
 
Thom Spencer
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The html source renders the bgcolors the same for each row
<tr bgcolor='#f4f4f4'>.
By the way, I'm enjoying "Java Devoloper's Guide to E-commerce with XML and JSP" very much.
Thanks
 
Thom Spencer
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Angela Ann,
I just tried your fix and I now have a beautiful table with alternating row colors.
Thank you very much.
Thom
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!