Andre's Blog

Personal blog of Andre Perusse

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 (10) -

  • Mike

    8/23/2007 10:14:04 PM |

    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".

  • Ryan J.

    8/28/2007 6:57:07 AM |

    This was exactly what I was looking for.  Thank you for posting this!

  • Ashish

    9/16/2008 1:06:53 AM |

    Great great !!!!!!!!! just what i needed.

  • Joel H

    12/19/2008 2:49:37 AM |

    Thank you.  This is far superior to implementing the alternating item template!

  • Easter

    2/22/2009 10:47:32 PM |

    I am gonna use it

  • Stig

    2/26/2009 5:37:03 PM |

    imo bad of microsoft to not implement something gridview-like with the repeater..


  • Rajasekhar

    6/18/2009 5:35:47 AM |

    It really works for me. Thanks for the solution.

  • Barry

    9/25/2009 3:25:04 PM |

    I tried the C# way...I got "Server tag is not well formed"....and I checked it for accuracy, character by character....

  • SJR

    11/21/2011 6:13:23 AM |

    Great Share, Thank you very much.

  • nool

    1/3/2013 6:51:12 AM |

    Great, this is a lot much efficient than the usual way Smile Thanks !