ASP.NET: Data-binding array of hashtables
Spent this morning in ASP.NET land working on a small modification in which I needed to data bind an array of hashtables to an <asp:repeater>. Looks like some other ASP.NETers had the same problem, but the ’solutions’ they offered didn’t seem to solve the errors I was getting. First, in the code behind, I had something like this in the code behind:
public Repeater events = new Repeater();
private ArrayList aEvents = new ArrayList();
public void Page_Load(Object sender, EventArgs e) {
Hashtable event1 = new Hashtable();
event1.Add("name", "name of event 1");
event1.Add("date", "5/31/2004");
Hashtable event2 = new Hashtable();
event2.Add("name", "name of event 2");
event2.Add("date", "06/20/2004");
aEvents.Add(event1);
aEvents.Add(event2);
events.DataSource = aEvents;
events.DataBind();
}
and then a standard repeater tag in my ASP.NET code:
<asp:repeater id="events" runat="server">
<ItemTemplate>
Name:<%# DataBinder.Eval(Container.DataItem,"name") %>
Date:<%# DataBinder.Eval(Container.DataItem,"date") %>
</ItemTemplate>
</asp:repeater>
The first error I got was DataBinder.Eval: 'System.Collections.Hashtable' does not contain a property with the name name., which means that the DataBinder uses reflection to find a property called ‘name’ on the current object in the iteration. This is a problem because obviously a hashtable doesn’t have a public property for ‘name’, it only has an associate array of values. The workaround, although I don’t know why this works, is to wrap the keys in a brackets:
Name:<%# DataBinder.Eval(Container.DataItem,"[name]“) %>
Date:<%# DataBinder.Eval(Container.DataItem,”[date]“) %>
Using brackets lets you use an array of hashtables as a datasource. Since this works, it might be helpful to add it to the Data Binding Expression Syntax guide on MSDN.
2 Comments