Welcome to Comunidade Bloggers |create|it| Sign in | Join | Help

Miguel Isidoro

.NET
SharePoint
Tek

News

SharePoint 2007 - "Value does not fall within the expected range" when updating an SPListItem in a Search

A very common error message that appears when developing in the SharePoint platform is "Value does not all within the expected range" when trying to update an SPListItem that is the result of a query to a SharePoint list. Let's look at the following example:

class SearchListItem
{
/// <summary>
///
Search document by title
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
private static SPListItem SearchDocument(SPList list)
{
//search document by title
StringBuilder query = new StringBuilder();
query.Append("<Where>");
query.Append("<Eq>");
query.Append("<FieldRef Name='Title' />");
query.Append("<Value Type='Text'>My document</Value>");
query.Append("</Eq>");
query.Append("</Where>");

SPView queryView = list.Views["All Documents"];
SPQuery spQuery = new SPQuery(queryView);
spQuery.Query = query.ToString();
spQuery.ViewAttributes = "Scope=\"RecursiveAll\"";

SPListItemCollection items = list.GetItems(spQuery);
if (items != null && items.Count > 0)
return items[0];

return null;
}

/// <summary>
///
Update document.
/// </summary>
/// <param name="list"></param>
private static void UpdateDocumentError(SPList list)
{
//search document by title
SPListItem doc = SearchDocument(list);
//update item in list
doc["Title"] = "My document modified";
doc.Update(); //error "Value does not fall
//within the expected range" is thrown
    }

/// <summary>
///
Update document.
/// </summary>
/// <param name="list"></param>
private static void UpdateDocumentSucess(SPList list)
{
//search document by title
SPListItem doc = SearchDocument(list);
//get SPListItem directly from list
SPListItem item = doc.ParentList.GetItemById(doc.ID);
//update item in list
item["Title"] = "My document modified";
item.Update(); //item updated sucessfully
}
}

In the previous example, the following actions are being performed:

  • A search is performed within a list for a document named "My Document". As a result of that search, a SPListItem instance is returned containing the document information;
  • In the "UpdateDocumentError" method, after the search is performed, the returned item is modified and the list is updated. This action will cause the exception "Value does not fall within the expected range" to be raised;
  • In the "UpdateDocumentSucess" method, after the search is performed, we obtain the item directly from the list using the ID of the SPListItem returned from the search (the line "SPListItem item = doc.ParentList.GetItemById(doc.ID);" was added, returning a new SPListItem instance). The new instance is then modified and used to update the item in the list. This way, the item is sucessfully updated.
Posted: Saturday, June 07, 2008 11:32 AM by misidoro
Filed under: ,

Comments

No Comments

Anonymous comments are disabled