in

The Web Jedi

Home of Halifax's Web Jedi

Jedi Meditations

The Easy Way To Alternate Background Colours on a Repeater

The ASP.NET Repeater is one of my favourite controls because it provides total flexibility in the layout of your data. I'll often use it to generate a list of data similar to a DataGrid or DataList. However, if I want to alternate the background colour of each row of data, the usual prescribed method is to use the AlternatingItemTemplate. But this is a such a waste of code and can be a pain to maintain if your ItemTemplate has any kind of complexity.

There is a much easier method, though. A shortcut if you will. If you're using your Repeater to generate table rows, you can use the following code in your <tr> tag to change the CSS class for each alternating row:

<tr class="<%# IIf(Container.ItemIndex Mod 2 = 0, "rowOdd", "rowEven") %>">

Or, in C#:

<tr class="<%# Container.ItemIndex % 2 == 0 ? "rowOdd" : "rowEven" %>">

Easy peasy. This isn't really all that ingenious but every time I want to use this technique I forget the syntax (it's the "Container.ItemIndex" I can never remember) so I decided to write a blog entry so I'll have it for reference.  :-)

Comments

 

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com
June 19, 2007 6:27 AM
 

Mike said:

Thank you, I can't believe how long I've been searching for the Container.ItemIndex property!  Finally I can do alternating row styles "properly".
August 23, 2007 10:14 PM
 

Ryan J. said:

This was exactly what I was looking for.  Thank you for posting this!
August 28, 2007 6:57 AM

Leave a Comment

(required)  
(optional)
(required)  
Add

About Andre Perusse

I'm a .NET developer in Halifax, Nova Scotia. I've been involved with computers professionally since 1992 and as a professional web developer since 1995. I've worked for very large and very small companies in all sorts of different capacities. These days, I'm writing a combination of web and WinForms apps for a medium-sized company and I'm loving it!
Copyright - all rights reserved
Powered by Community Server (Non-Commercial Edition), by Telligent Systems