Tales from the Evil Empire

Bertrand Le Roy's blog

News


Bertrand Le Roy


Add to Technorati Favorites Tales from the Evil Empire - Blogged

Blogs I read

My other stuff

Archives

Alternating styles in ListView without AlternatingItemTemplate

ListView (the server-side control), like all repeating data controls in ASP.NET, has an AlternatingItemTemplate, but it would be a shame to have to copy all the markup in the ItemTemplate into AlternatingItemTemplate, just to alternate styles on the items. It's quite likely that only css classes will change between the two, and redundancy is bad <- big scoop here.

But there is a simpler way. From within any template, you have access to the current index of the row within the whole data set, using Container.DataItemIndex, and within the currently displayed items, using Container.DisplayIndex. This gives us an easy way to alternate styles:

<ItemTemplate>
  <li class="<%# Container.DisplayIndex % 2 == 0 ? "even" : "odd" %>">
<%# Eval("Name") %>
</li> </ItemTemplate>

Just define the even and odd classes in your stylesheet and you're pretty much done.

The full source code for the page is attached below:
http://weblogs.asp.net/bleroy/attachment/6436332.ashx

Comments

migo said:

great idea!

# July 23, 2008 10:56 PM

CareySon said:

wow..i think it's a great way.more simple and less code:-)

# July 24, 2008 12:14 AM

Andrei Rinea said:

Great tip! Simple and effective.

# July 24, 2008 6:47 AM

Evgenij said:

Yeah. Thanx, really cool.

# July 24, 2008 6:48 AM

kamii47 said:

Wow.

Very good idea we can implement that in othere areas also like gridview e.t.c

# July 24, 2008 7:35 AM

jao said:

cool! reminds me of those techniques from the classic asp style. =)

# July 27, 2008 9:51 PM

Mike.Borozdin said:

Good idea indeed!

# August 2, 2008 8:35 AM

JeffEsp said:

This didn't work for me until I added a cast to IDataItemContainer like so:

((IDataItemContainer)Container).DisplayIndex % 2 == 0 ? "even" : "odd"

Any ideas why?

# August 19, 2008 9:11 AM

Bertrand Le Roy said:

@JeffEsp: Are you using ListView or another data control?

# August 19, 2008 1:41 PM

Winston said:

Thanks for this tip. It really nice

# November 18, 2008 5:57 PM

richardneverett said:

Just as I was about to go jQuerying...!

Very helpful post, many thanks.

# December 11, 2008 9:42 AM

grinnellja said:

Doesn't work. It says character is not valid and highlights the row

# September 13, 2011 12:41 PM

Bertrand Le Roy said:

@grinnellja: it does work just fine. You have an invalid character there. Try to re-type it and save.

# September 13, 2011 12:59 PM