Quantcast
Channel: Andre's Blog - Entertainment
Viewing all articles
Browse latest Browse all 8

The Easy Way To Alternate Background Colours on a Repeater

$
0
0

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:

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

Or, in C#:

<trclass="<%# 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.  :-)


Viewing all articles
Browse latest Browse all 8

Trending Articles