Zebrafying ListView without AlternatingItemTemplate

It’s a common task, that you have to create a table with zebra stripes on the webserver. This is quite easy in ASP.NET using the ListView control, because thanks to its ItemTemplate and AlternatingItemTemplate you can create separate row templates for the odd and the even rows. The drawback of this solution is that if the two templates have only minor differences, – for example just a single CSS class that sets the background color is attached to every second row – the code quickly becomes overcomplicated which is hard to maintain.

You can solve this problem with a single ItemTemplate, if you don’t hardcode, but instead calculate the CSS class of the row on the fly with data binding:

  <tr class="<%# Container.DisplayIndex % 2 == 0 ? "odd" : "" %>">

The same solution works with other controls as well, however you have to slightly modify the condition. For example if you use a Repeater you should use the Container.ItemIndex property to query the current row number.



2 thoughts on “Zebrafying ListView without AlternatingItemTemplate

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s