Alternating CssClass without repeating code in AlternatingItemTemplate?

Discussion in 'ASP .Net' started by Danny Tuppeny, Oct 30, 2005.

  1. Hi all,

    Is there a way in something like a DataList, to have a different colour
    background (via CssClass) without repeating all my code in both the
    ItemTemplate and AlternatingItemTemplate blocks?

    I have quite a lot of stuff in the ItemTemplate block, but because so much
    of it is bound fields, creating a seperate user control mapping all of these
    fields across would be a nightmare to maintain. Instead, I'd like something
    like:


    <ItemTemplate>
    <div class="<% SomeExpress that returns True/False or Odd/Even etc. %>">
    // all my stuff here
    </div>
    </ItemTemplate>

    If there was a sort of "row number" I could get at, I could do "(row) Mod 2"
    to do what I want, but I can't see anything obvious to do that.

    Any ideas?

    Thanks,

    Danny Tuppeny
     
    Danny Tuppeny, Oct 30, 2005
    #1
    1. Advertisements

  2. It's going to be one of those days... The solution, is this:

    <%# Container.ItemIndex %>

    I tried it before posting and it didn't work, but I stupid had put it in the
    wrong place. I have a FormView at the top of my page displaying the
    "current" record. Then a DataList that displays "children". I'd put it in
    the ItemTemplate of the first one, which of course, only displays one record
    anyway. Doh!
     
    Danny Tuppeny, Oct 30, 2005
    #2
    1. Advertisements

  3. Danny Tuppeny

    Gaurav Vaish Guest

    : Is there a way in something like a DataList, to have a different colour
    : background (via CssClass) without repeating all my code in both the
    : ItemTemplate and AlternatingItemTemplate blocks?

    Not directly.

    One ugly way may be to use a variable with the "common" code. So,
    finally, the templates may look like:

    <ItemTemplate>
    <%= common %> CssClass=... <%= remaining %>
    </ItemTemplate>
    <AlternatingItemTemplate>
    <%= common %> CssClass=... <%= remaining %>
    </AlternatingItemTemplate>

    Or better still, you may like to make a CustomDataList as a sub-class of
    DataList... tougher way but will give you exactly what you want with finer
    control.
     
    Gaurav Vaish, Oct 30, 2005
    #3
  4. <snip>

    I managed it with the ItemIndex. Doing ItemIndex % 2 gives me an
    alternativing variable I can use in class names :)
     
    Danny Tuppeny, Oct 30, 2005
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.