Archive for the ‘webforms’ Category

An indexed foreach for .aspx Web Forms

Tuesday, March 11th, 2008

 Nick blogged about why ASP.Net Repeaters Suck the other week and talked about using foreach loops in your .aspx.  I love this and have been doing it for a while – the strong typing and consice syntax is great.  However, sometimes I need format data based on odd and even rows…

 <table>
   <tr class='Row'><td></td></tr>
   <tr class='AltRow'>...</tr>
</table>

To accomplish this I created a helper function in the page code behind:

protected void Foreach<T>(IEnumerable<T> enumerable, Proc<T, int> action){
 int i = 0;
 foreach(T t in enumerable){
    action(t, i);
  i++
}
}

Then in the .aspx

<%Foreach(People, (person, i) => { %>
  <tr class='<%=i%2==0 ?  "Row" : "AltRow"%>'><td><%=person.FullName%></td></tr>
<%});%>

Just what I needed!