About Links Archives Search Feed Albums of Note

Binding To An IEnumerable

Didn’t find this in any easily searchable place, so here’s one for reference. Consider a scenario where you’re binding a templated control to an IEnumerable object. In my case, I needed to display a list of the keys in my cache.

protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { lvwKeys.DataSource = AllCacheKeys(); lvwKeys.DataBind(); } } private IEnumerable AllCacheKeys()


IDictionaryEnumerator enumerator = HttpContext.Current.Cache.GetEnumerator();

while (enumerator.MoveNext())


yield return enumerator.Key.ToString();



So how do I reference the string values in my template? <%#Eval(“xyz”) %> expects xyz to be the property of the object being bound to, but a simple string has no property for its value. I’ve seen <%#Eval(“.”) %> suggested else place where . is supposed to refer to the object as whole, but this does not work here. Instead, we must use <%# Container.DataItem %> to refer to the object itself.

   </table>    </LayoutTemplate>    <ItemTemplate>       <tr>          <td><%# Container.DataItem %></td>       </tr>    </ItemTemplate> </asp:ListView>

Indeed, this the way to approach binding IEnumerable where T is any value type – int, double, bool, etc. Container.DataItem returns the string representation of the value you are binding to. In the case of bool, it renders True and False.

Hope that helps. Happy coding!

Posted on January 26, 2010   #Geek Stuff     #ASP.NET  

← Next post    ·    Previous post →