How to: Alternate row color with the ASP.NET Repeater control
April 2, 2009
The ASP.NET Repeater control is great in a whole range of scenarios. I use it all the time my self because it’s flexible and simple to use. Often, it’s for outputting rows of data, where I want to avoid using the GridView control, or simply because I don’t want it to be built as a table. In that case, I find my self wanting to apply a different color to every second row a lot of the time, to get an effect like this:
| John Doe |
| Jane Doe |
| John Doe |
| Jane Doe |
Microsoft offers a way to accomplish this with the repeater:
<asp:Repeater runat="server" ID="repData"> <ItemTemplate> <div style="background-color: #fff;"> <%# Container.DataItem.ToString() %> </div> </ItemTemplate> <AlternatingItemTemplate> <div style="background-color: silver;"> <%# Container.DataItem.ToString() %> </div> </AlternatingItemTemplate> </asp:Repeater>
Now, that’s just fine for such a simple example, but usually my repeater will contain way more markup. Having it in two separate places fills up my file and forces me to make modifications in two places instead of one. It’s simply not a very practical solution, especially not when considering that we’re doing all that to output a different background color. It’s time to get creative:
<asp:Repeater runat="server" ID="repData"> <ItemTemplate> <div style="background-color: <%# GetRowColor() %>;"> <%# Container.DataItem.ToString() %> </div> </ItemTemplate> </asp:Repeater>
As you can see, instead of outputting the color directly, we make a call to a function called GetRowColor(). It should be implemented in your CodeBehind file like this:
private int counter = 0;
protected string GetRowColor()
{
if(counter++ % 2 == 0)
return "#fff";
else
return "silver";
}
If you’re new to C#, you might wonder what that function does, but in fact, it’s quite simple. We have a counter variable, and each time the GetRowColor() method is called, we increment that variable (counter++ is the same as counter = counter + 1). We then use the modulo operator (%) to test if the number is an equal number or not – if it is, we return one color, and if it’s not, we return another color. This ensures that every other row is rendered with another background color.
Now, in a real life example, you might want to output the color choice another way. For instance, you could have an “even” and an “odd” CSS class to use each time you want even and odd rows, allowing you to define the color in one common place. Or perhaps you only want the style declaration on odd rows, letting equal rows default to the parent background color? No problem, just change the GetRowColor() method into something else and use it accordingly.