Data Binding a Repeater to a SortedList of structures
Kelly’s comment in the phone numbers in data bound controls post reminded me of something I did this morning:
The problem: I had a bunch of data that I needed to report on, based on date. Unfortunately, there were a bunch of different dates in the table that needed to be aggregated (various timestamps for events in a record’s life) that couldn’t be summed up in one SQL statement.
The solution: I love the System.Collections namespace, so I went with a structure containing the counters, and stored one structure per day in a SortedList. There were three counters that needed to be rolled up, so three DataReader.Read() loops later, I had my data structure.
But how to render it?
Once again, I had to use every fibre of my being to avoid implementing an OnDataBound event handler and doing a bunch of FindControl() calls. Yes, that was a good step away from the old ASP style of Response.Write() calls embedded in the table markup, but come on, it’s 2006 already (although this was ASP.NET 1.1)
The rendering code:
_report.DataSource = counters;
_report.DataBind();
So how do we bind a SortedList (or a Hashtable if you don’t care about the order)?
Within the ItemTemplate of my Repeater, I used this for the key (the date):
<%# ((DateTime)((DictionaryEntry)Container.DataItem).Key).ToString(”d”) %>
For the individual elements of the structure:
<%# ((Record)(((DictionaryEntry)Container.DataItem).Value)).aCounter %>
A few too many brackets for my liking, but hey, it beats hiding it in a CodeBehind.