Somacon.com: Articles on web development, software, and hardware
§ 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>

</asp:ListView>
Link to this page: <a href="http://www.somacon.com/p543.php">Alternating Table Row Colors with ASP.Net ListView Control</a>

Contact · Search · Print · Social bookmark this page · E-mail this page · Web Developer For Hire
Created 2009-03-18, Last Modified 2009-03-18, © Shailesh N. Humbad
Disclaimer: This content is provided as-is. The information may be incorrect.