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();
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.