Lars Nielsen's Discoveries

January 24, 2012

ArgumentException “Value does not fall within the expected range” error using fields on SPListItem

Filed under: Development,SharePoint,Troubleshooting — Lars Nielsen @ 7:56 pm
Tags: , ,

Here’s a pointer that might save a few minutes (or hours!) of frustration if you hit the same problem as me.  I was trying to extract the column (field) values from an SPListItem.  Easy enough, you just use code like this:


public void ProcessItem(SPListItem item)
{
    string name = item.Name;
    string title = item.Title;
    int id = item.ID;
    // Do something else here
}

OK so far so good. I had this code within my project and ran it. As soon as it got the line where it assigns the name variable it threw an exception:

System.ArgumentException: Value does not fall within the expected range

I put a breakpoint in the function and ran it with the VS debugger attached to the W3WP process to hit the breakpoint.  I began to check the item object in Visual Studio, and tried out a few expressions:

  • item.Name and item.Title both threw the exception
  • item[“Name”] and item[“Title”] both threw the exception as well
  • item.ID and item[“ID”] returned the correct values
  • item.Fields.ContainsField(“Name”), item.Fields.ContainsField(“Title”) and item.Fields.ContainsField(“ID”) returned true
How weird.  The ID column was behaving like I expected, but Title and Name were not.  All three  fields were in the Fields property on the item, but I couldn’t extract their column values without getting the ArgumentException.  It took a while and a fair bit of chasing around on forums to figure this out.  What was happening is that my SPListItem objects were coming out of the results of a query in SharePoint, using an SPQuery object.  It turns out that this is the behaviour you see if you forget to include the columns that you want in the ViewFields property of SPQuery.  This property should have a list of FieldRef XML elements so I had to add elements like this:
<FieldRef Name=’Name’><FieldRef Name=’Title’>
Check the MSDN documentation for more information about using SPQuery and ViewFields.
Advertisements

1 Comment »

  1. thanks, I lost one day for this problem

    Comment by sla12 — June 2, 2014 @ 7:49 am


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: