Saturday, August 1, 2009

Odd Error When Retrieving Items from an SPView

When attempting to retrieve items from an SPView programmatically, you cannot reference fields by name or by their ID.  Note, I’m using MOSS 2007 with SP2.  So here’s the code that causes the issue (and resulted in over 3 hours of wasted time)…

Guid listId = new Guid(...);
Guid viewId = new Guid(...);

SPList list = SPContext.Current.Web.Lists[listId];
SPView view = list.Views[viewId];

SPListItemCollection filteredItems = list.GetItems(view);

foreach (SPListItem item in filteredItems)
{
Response.Write(item["Title"]); // THIS FAILS
}

And you’ll see this error:


Exception has been thrown by the target of an invocation. ---> System.ArgumentException: Value does not fall within the expected range. at Microsoft.SharePoint.SPFieldMap.GetColumnNumber(String strFieldName) at Microsoft.SharePoint.SPListItemCollection.GetRawValue(String fieldname, Int32 iIndex) …


Thankfully, the SPView object exposes a Query property which is a string that contains the CAML that filters list items.  Using this property, you can just create your own SPQuery object and retrieve the items from the list.  The following code has this modification.


Guid listId = new Guid(...);
Guid viewId = new Guid(...);

SPList list = SPContext.Current.Web.Lists[listId];
SPView view = list.Views[viewId];

SPQuery query = new SPQuery();
query.Query = view.Query; // GET THE QUERY PROPERTY FROM THE VIEW

SPListItemCollection filteredItems = list.GetItems(query);

foreach (SPListItem item in filteredItems)
{
Response.Write(item["Title"]);
}

Hopefully, this saves you some time.