In SharePoint 2007, querying a List is fairly straightforward. Occasionally however you might run into some problems with processing and manipulating the retrieved Lookup and Author contents though. It could be for instance that a
Index (zero based) must be greater than or equal to zero and less than the size of the argument list occurs. And as you may know, these are very nasty errors always.
When retrieving Lookup and Author fields from a SharePoint List, you will notice that additional information is inserted in the contents.
This can be checked easily when you have Visual Studio 2008 with Extensions for SharePoint Svcs 1.3 installed. Here’s how.
Create a new Console application and reference the Microsoft.SharePoint assembly. Add following code:
static void Main(string args)
SPSite site = new SPSite("http://yoursite");
SPWeb web = site.OpenWeb();
SPList list = web.Lists["YourList"];
SPQuery query = new SPQuery();
query.Query = "<OrderBy><FieldRef Name=’Modified’ Ascending=’FALSE’ /></OrderBy>";
collection = list.GetItems(query);
SPListItem item = collection;
On debugging, you can add the
item object to your watchlist and see for each column the Value and its Type. For a
Lookup column, the ID is added before the actual content. This refers to information that is already available on the site in another List. Also, for the
Created By column, the author is prepended with the unique User ID by default.
The provided information might be valuable in some way, but most likely you do not need it. You want to use the Author or Lookup columns in your CAML queries or for further processing, without the IDs.
Luckily this is easy to overcome. The IDs need to be filtered out.
In both cases, the object is returned as a string and strings can be easily manipulated of course.
In fact, the below method helps you extract the value you need:
/// Extract value from List Lookup or Author field
/// <param name="val">List Lookup / Author field content</param>
/// <returns>manipulated string</returns>
string GetCorrectValue(string val)
string returnString = String.Empty;
string valProperties = val.Replace("#", String.Empty).Split(‘;’);
if (valProperties.Length >= 2)
returnString = valProperties;
You can then call the method as follows:
newStr = GetCorrectValue((string)item["LookupOrAuthor"]);