Binding to Sharepoint List Items (Part 1 of 2)

Tags: .NET, SharePoint

Databinding is cool. It lets us connect our front-end GUI elements (say, a DataGrid) to our back-end data elements (a DataSet, for instance) without the drudgery of synchronizing the two all the time. True, ASP.NET Datagrids are one-directional, but it's still cool.

The nice thing about databinding is that it can be done with custom objects, not only DataSets and such. Specifically, a DataSet's DataSource can be any object that implements ICollection. Let's see two ways to use this to bind a datagrid to a group of SPListItems:

1) Binding to a SPListItemCollection - the straightforward way.

The binding itself is a snap - if we have an SPListItemCollection object (from an SPList's Items property, for instance) we can simply set it as the DataSource of our grid - it implements ICollection and all is well:
SPListItemCollection items = myList.Items;
dgItems.DataSource = items;

The problem, however, is with the Binding code in our ASPX page. We can bind to properties of the SPListItem object, but not to indexed properties. Code such as this will work, and bind to the current item's ID property:
<%# DataBinder.Eval (Container.DataItem, "ID") %>

But how do I bind to myListItem["Title"] or myListItem["MyCustomProperty"]?

One thing that's easy to forget is that we can write normal .NET code inside the <%# %> blocks, even if the lack of Intellisense seems otherwise. So we can cast our DataItem to an SPListItem and get the property:

<%# ((SPListItem)Container.DataItem)["MyProperty"] %>

This requires a few additions to the top of the ASPX:

<%@ Import Namespace="Microsoft.SharePoint" %>   <!-- This is so we can reference SPListItem without the full namespace -->
<%@ Assembly Name=""Microsoft.SharePoint, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"" %> 

Note the second line. This is because the code in our embedded script blocks doesn't use the references from the main project, and we have to manually specify the Sharepoint assembly reference.

Using the same concept, we can bind to any property - or even method call results - of any custom object we have.

7 Comments

Comments have been disabled for this content.