Monday, November 8, 2010

SPQuery on SPView gives an exception "Value does not fall within the expected range"

Inorder to get the results from the specific view of a list where the view is created with some filter conditions SPQuery should be run on spcific view (SPView) of a list instead default list.
SPList spList = spWeb.Lists["List Name"];
SPView view = spList.Views["View Name"];
SPQuery query = new SPQuery(view);
SPListItemCollection collection = spList.GetItems(query);
The statement executes and gets the result collection, but the result item(listitem) of collection doesn't have the properties or columns loaded by default.

So collection[0]["Title"] gives "value does not fall within the range" exception.

To avoid the exception, all the fields which are going to be read in the further statements should be specified for the view as viewfields.
query.ViewFields = "
Similarly 'n' number of fields which are going to be used in further can be specified as view fields.