Somacon.com: Articles on websites & etc.

§ Home > Index > Web Development

Alternating Table Row Colors with ASP.Net ListView Control

A simple way to display alternating background colors with the ASP.Net 3.5 ListView Control.

This method avoids using the AlternatingItemTemplate, which results in redundant code when it is almost identical to the ItemTemplate. HTML markup is reduced by the use of a style sheet. This technique can also work with other ASP.Net controls like GridView, Repeater, etc., but may require some slight modifications. The sample code for VB.Net and C#.Net is below.

Solution

<style type="text/css">
table.example { }
table.example th { }
table.example td { background-color: #FFFFFF; }
table.example tr.a td { background-color: #FFFFF0; } /* Alternating rows */
</style>

<asp:ListView ID="ListView1" runat="server">
<LayoutTemplate>
<table class="example"> 
    <tr>
        <th>Column1</th>
    </tr>
    <tr id="itemPlaceholder" runat="server"></tr>
</table>
</LayoutTemplate>

<%-- VB.Net 2008 Syntax --%>
<ItemTemplate>
    <tr class="<%# If(Container.DisplayIndex Mod 2 = 0, "", "a") %>">
        <td><%# Eval("Column1") %></td>
    </tr>
</ItemTemplate>

<%-- C#.Net Syntax --%>
<ItemTemplate>
    <tr class="<%# Container.DisplayIndex % 2 == 0 ? "" : "a" %>">
        <td><%# Eval("Column1") %></td>
    </tr>
</ItemTemplate>

<%-- VB.Net 2005 Syntax : NOTE: Prefer VB.Net 2008 syntax to avoid side-effects --%>
<ItemTemplate>
    <tr class="<%# IIf(Container.DisplayIndex Mod 2 = 0, "", "a") %>">
        <td><%# Eval("Column1") %></td>
    </tr>
</ItemTemplate>

</asp:ListView>

Have you heard of the new, free Automated Feeds offered by Google Merchant Center? Learn more in Aten Software's latest blog post comparing them to traditional data feed files.
Created 2009-03-18, Last Modified 2011-07-24, © Shailesh N. Humbad
Disclaimer: This content is provided as-is. The information may be incorrect.