My Digital Junk Drawer

I recently took my old blog offline, but this was one of the posts that I know at least a few people benefited from, so I am republishing it here for anybody looking for this information in the future.

If you have used the asp.net listview control, you know that you place your output elements in between the ItemTemplate tags. You may or may not have noticed that there is also an AlternateItemTemplate tag that can be used to render every other item differently. This is great when you want to alter the layout of every other item, but if you just want to apply a different CSS class on alternate items, you will be duplicating a lot of markup for a fairly minor change. Well, I have good news, there is an easier way. All you need to do is look at the DataItemIndex for your data item, determine if it is even or odd and apply the appropriate css class. The code is pretty self-explanatory, so here it is:

<asp:ListView ID="lvPeople" runat="server" ItemPlaceholderID="plcItem">
    <LayoutTemplate>
        <div id="people">
            <asp:PlaceHolder runat="server" ID="plcItem" />
        </div>
    </LayoutTemplate>
    <ItemTemplate>
        <div class='<%# Container.DataItemIndex % 2 == 0 ? "even" : "odd" %>'>
            First Name: <asp:Label runat="server" ID="lblFirstName" Text='<%# Eval("FirstName") %>' /><br />
            Last Name: <asp:Label runat="server" ID="lblLastName" Text='<%# Eval("LastName") %>' /><br />
            Age: <asp:Label runat="server" ID="lblAge" Text='<%# Eval("Age") %>' />
        </div>
    </ItemTemplate>
</asp:ListView>

The key is this line of code:

<div class='<%# Container.DataItemIndex % 2 == 0 ? "even" : "odd" %>'>

This allows alternating styles without duplicating your markup, which makes changing the item layout in the future much easier. You could also accomplish this with some javascript (in a line or two using jQuery) but that is a topic for another post.

  1. clewellgrl8935 reblogged this from avanslaars
  2. gorczycajexp593398 reblogged this from avanslaars
  3. avanslaars posted this
Blog comments powered by Disqus