Click here to Skip to main content
15,881,380 members
Articles / All Topics

DataBinding to SPListItemCollection

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
16 Sep 2009CPOL 21.3K  
This is one of those things that I always forget about and end up having to debug.

This is one of those things that I always forget about and end up having to debug. (Also for those planning to do MCTS, I guarantee that there will be a question about this one ;) )

While it is technically possible to databind to a SPListItemCollection, when you try to refer to any of the SPListItem fields by name you’ll end up with an error similar to this:

[ArgumentException: Value does not fall within the expected range.]
Microsoft.SharePoint.SPFieldMap.GetColumnNumber(String strFieldName) +161
Microsoft.SharePoint.SPListItemCollection.GetRawValue(String fieldname, Int32 iIndex) +56
Microsoft.SharePoint.SPListItem.GetValue(SPField fld, Int32 columnNumber, Boolean bRaw) +319
Microsoft.SharePoint.SPListItem.GetValue(String strName, Boolean bThrowException) +111
Microsoft.SharePoint.SPListItem.GetValue(String strName) +39
Microsoft.SharePoint.SPListItem.get_Title() +41

So using code like this won’t work:

SPList listData = SPContext.Current.Web.Lists[ListName];

SPView view = listData.Views[ViewName];

_theList.DataSource = listData.GetItems(view);

_theList.DataTextField = DataTextField;

_theList.DataValueField = DataValueField;

_theList.DataBind();

The SPListItemCollection provides a GetDataTable() method that converts the SPLIstItemCollection into a datatable that is much easier to use with databinding.

So the revised code looks like this:

_theList = new DropDownList();

SPList listData = SPContext.Current.Web.Lists[ListName];

SPView view = listData.Views[ViewName];

_theList.DataSource = listData.GetItems(view).GetDataTable();

_theList.DataTextField = DataTextField;

_theList.DataValueField = DataValueField;

_theList.DataBind();

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer www.activeware.net
United Kingdom United Kingdom
I've been working as a freelance software developer for almost 15 years, covering everything from VB3 and Delphi through to .Net 3.5 and SilverLight. I'm a Microsoft Gold certified partner and have gained MCSE, MCTS and MCP certifications. Most of my time these days is spent on Microsoft SharePoint and related technologies.

I live in Scotland with my wife Nicola, my two sons Cameron and Fraser and so many animals that I'm considering growing a long white beard and building a large wooden boat.

Comments and Discussions

 
-- There are no messages in this forum --