If you’ve ever worked with SharePoint columns that are of type Lookup and you’re reading this data in via the object model, you’re probably already aware that the value gets returned as an ugly string in the form of:
What you want to avoid is using string manipulations to get at the ID or Value of that lookup. An example of a poor practice would be:
string city = Convert.ToString(listItem["City"]); city = city.Substring(city.IndexOf("#") + 1);
If you output the variable city, you’ll find it now contains Vancouver.
There is a better way to do this. The SharePoint object model actually contains some useful helpers for dealing with column types that return this format:
This class is very useful when working with columns that are of type Lookup. The syntax for using this is pretty straight forward. Given our example above where we have a column named City that is a lookup into the Cities list, here is what our code would look like:
SPFieldLookupValue cityLookup = new SPFieldLookupValue(Convert.ToString(listItem["City"]);
To access either the ID or the Value of that entry, we use:
string cityID = cityLookup.LookupId; string cityName = cityLookup.LookupValue;
Now what’s really handy about the above two strings I’ve created is that the cityID string now contains the ID of the city that’s referenced in the Cities list.
I’ve talked about reading values from a column of type Lookup, the next article in this series will talk about how to save values to a column of this type. Keep in mind that the SPFieldLookupValue class is just one of many for this type of operation. If you’re working with Hyperlink column types, as an example, you’ll want to check out the SPFieldUrlValue class.