Alternating items without using an AlternatingItemTemplate
Many of the controls in ASP.Net (e.g. a Repeater) support the concept of an AlternatingItemTemplate, which, as the name suggests, allows you to define an additional item template to change the look and feel for each alternating item in the data source. This is all well and good, but I’ve never seen a good use for it; more often than not, all you really want to do in your alternating item is, for example, slightly change the background colour for ease of visual differentiation.
Though you can use the alternating item template for this, it typically involves you duplicating a lot of code, since the AlternatingItemTemplate is mostly the same as your ItemTemplate (save perhaps for a CSS class declaration somewhere).
<asp:Repeater ID="rpt" runat="server">
<HeaderTemplate>
<table cellpadding="0" cellspacing="0">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("FirstName") %></td>
<td><%# Eval("LastName") %></td>
<td><%# Eval("Age") %></td>
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr class="Alternating">
<td><%# Eval("FirstName") %></td>
<td><%# Eval("LastName") %></td>
<td><%# Eval("Age") %></td>
</tr>
</AlternatingItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
If this sounds like you, then never fear - there IS a better way!
When you’re binding, you have access to the RepeaterItem via the Container property, which contains an ItemIndex property. As such, the simplest way of alternating your items is simply to check if the number divides evenly by two:
<asp:Repeater ID="rpt" runat="server">
<HeaderTemplate>
<table cellpadding="0" cellspacing="0">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr class="<%# Container.ItemIndex % 2 == 0 ? "Alternating" : String.Empty %>">
<td><%# Eval("FirstName") %></td>
<td><%# Eval("LastName") %></td>
<td><%# Eval("Age") %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
There is a minor downside using this approach - the non-alternating rows will all declare an empty CSS class within them. But, this is a sacrifice I think is acceptable to decrease repetition of code.