Alternating styles in ListView without AlternatingItemTemplate

ListView (the server-side control), like all repeating data controls in ASP.NET, has an AlternatingItemTemplate, but it would be a shame to have to copy all the markup in the ItemTemplate into AlternatingItemTemplate, just to alternate styles on the items. It's quite likely that only css classes will change between the two, and redundancy is bad <- big scoop here.

But there is a simpler way. From within any template, you have access to the current index of the row within the whole data set, using Container.DataItemIndex, and within the currently displayed items, using Container.DisplayIndex. This gives us an easy way to alternate styles:

<ItemTemplate>
  <li class="<%# Container.DisplayIndex % 2 == 0 ? "even" : "odd" %>">
<%# Eval("Name") %>
</li> </ItemTemplate>

Just define the even and odd classes in your stylesheet and you're pretty much done.

The full source code for the page is attached below:
http://weblogs.asp.net/bleroy/attachment/6436332.ashx

12 Comments

Comments have been disabled for this content.