An indexed foreach for .aspx Web Forms

 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!

One Response to “An indexed foreach for .aspx Web Forms”

  1. jimi Says:

    Hi there – stumbled across this while looking for something totally unrelated to the above post. however, it caught my interest as i too ‘loathe’ putting in repeaters (or any ‘logic’ for that matter) in the aspx page. however, i had an issue in being able to use the code as i’m not sure of the namespaces required to make all of this work. Here’s the code that i pasted into a default blank default.aspx.cs page:

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

    (i had to add the colon after i++;). however, it still tells me that it ‘wants’ an assembly for this to work. please tell this idiot what he’s missing :)

    thanks – btw, some great photos too!!!

Leave a Reply