Display Alternate Syle for Alternating Rows in C#

This is just a quick little tip to help you display alternating row colors in your C# code for a DataList or GridView control. Using the AlternatingItemTemplate method is a pain, as it forces you to duplicate your entire ItemTemplate block just to add the alternating CSS class. While trying to find another means of accomplishing this I found the Container.ItemIndex syntax. Using this you can write a little if statement with a MOD function in it to have the code display your alternating style. So my DataList now looks like this:

<code lang="csharp[lines]"><datalist id="ContentList" onitemdatabound="ContentList_ItemDataBound" runat="server" width="100%"><br></br><headertemplate></headertemplate></datalist>

">

TitleIDEditDelete
">%>">](add.aspx?id=<%# Eval()">Edit Record %>" commandname="deleteID" id="deleteBtn" imageurl="/admin/images/structure/delete-icon.gif" oncommand="delButton_Click" runat="server">
So every other row will now use a class named trDark. To use this with a GridView you would use the syntax of Container.DisplayIndex.

Comments

comments powered by Disqus