Come see us

100 Brunswick Street
Glasgow G1 1TF


t: 0141 559 5840
f: 0141 559 5841
digital@framecreates.co.uk

Ever built a usercontrol or webpage and had a repeater?  Did that repeater have an item and alternating item template?  And were those templates exactly the same except for the class on the row or li element?  Well I have, and for years I cried when I had to update the repeater.  

<ItemTemplate>
    <tr class="row">
	<td style="text-align: center;">Some&nbsp;Code or other HTML</td>                        
    </tr>
</ItemTemplate>
<AlternatingItemTemplate>
    <tr class="rowalt">
	<td style="text-align: center;">Some Code or other HTML</td>                        
    </tr>
</AlternatingItemTemplate>

Well I found the simplest way to fix this was with C# and a ? notation and some inline coding.  Yes inline coding.  Doesn't that break paradigms of keep C# in the code behind and so forth?  Well I have views on this and may at some point blog on it, but today let's just say yes, yes it does.  But the rules are there to be broken.

The Solution

Container.ItemIndex % 2 == 0 ? "row" : "rowalt"

Yes it's that simple!  By replacing the value in the "class" tag in your HTML with that you get a more concise piece of code.  It basically says "Take the row index of the current row, divide it by 2.  If you have no remainder, then its an even number and so output 'row' otherwise output 'rowalt'."

<ItemTemplate>
    <tr class='<%# Container.ItemIndex % 2 == 0 ? "row" : "rowalt"  %>'>
	<td style="text-align: center;">Some code or other HTML</td>                        
    </tr>
</ItemTemplate>

Roll on the next version of CSS to make this even easier.  It's also possible in Javascript libraries like MooTools or jQuery to do this, but this is the simplest option in my opinion.

Bookmark and Share

Posted in: Labs

Comments

8/4/2009 9:10:24 AM
William
Nice Colin, very nice. I have always hated duplicating the html and controls to simply alter a row. I have done the assessment of itemindex within the OnDataBound event handler to achieve similar results, but your inline version could be useful when there is no need to handle the OnDataBound event.