Lookup and Author fields broken

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 NullException or 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:

[code language=”csharp”]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace SPTest
{
class Program
{
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>";

SPListItemCollection collection;
collection = list.GetItems(query);

SPListItem item = collection[0];
}
}
}
[/code]

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:
[code language=”csharp”]
/// <summary>
/// Extract value from List Lookup or Author field
/// </summary>
/// <param name="val">List Lookup / Author field content</param>
/// <returns>manipulated string</returns>
string GetCorrectValue(string val)
{
string returnString = String.Empty;

if (!String.IsNullOrEmpty(val))
{
string[] valProperties = val.Replace("#", String.Empty).Split(‘;’);

if (valProperties.Length >= 2)
returnString = valProperties[1];
}
return returnString;
}
[/code]

You can then call the method as follows:
[code language=”csharp”]
newStr = GetCorrectValue((string)item["LookupOrAuthor"]);
[/code]

Leave a Reply

Your email address will not be published. Required fields are marked *