Setting the value of LookUp Fields in C#

by

LookUp Fields are a common sight in SharePoint environments, but working with them is not as straightforward as one might expect. Setting a LookUp Field Value (object type SPFieldLookupValue) on a list item offers several options:

1. Setting the value to a SPFieldLookupValue

This one is obvious. The SPFieldLookup value property is – as with all field values – of type object in the SharePoint object model, but is internally used as a SPFieldLookupValue.

2. Setting the value to a formatted String

LookUp Field Values have a string representation of “(ID);#(VALUE)”, i.e. “2;#Second Entry”. Setting the value to a String in the before mentioned format works as well as it is converted to a SPFieldLookupValue.

3. Setting the value to an ID only (which is an Integer)

To my surprise, the value can be set to the ID only without raising any errors.

4. Not working: Setting the value to the String value only

Unfortunately, just setting the value to the desired value and skipping the ID part does not work and will throw an “Index Out Of Range” Exception. But the GUID of the LookUp List is conveniently stored in the SPFieldLookup object. In some situations it is useful to set the value using Strings and I wonder why that is not a build-in option. The following code achieves this goal:

public static SPFieldLookupValue getLookUpValue(string lookupValue, SPList myList, String fieldname)
        {
            SPFieldLookup lookUpField = (SPFieldLookup)myList.Fields[fieldname];
            SPList lookupSourceList = myList.ParentWeb.Lists[lookUpField.LookupList];

            SPQuery query = new Microsoft.SharePoint.SPQuery();
            query.Query = String.Format("{0}", lookupValue);
            SPListItemCollection listItems = lookupSourceList.GetItems(query);

            return new SPFieldLookupValue(listItems[0].ID.ToString());
        }

        // use like this:
        item["myLookUpField"] = getLookUpValue("the new value", item.ParentList, "myLookUpField");

Thanks to R.MARAN., who brought up parts of this code in his blog. If you’re looking for a way to get multiple lookup values, check this blog entry.

Tags: , ,

One Response to “Setting the value of LookUp Fields in C#”

  1. How to organize business Says:

    How to organize business…

    [...]Setting the value of LookUp Fields in C# « CAIRO Sharepoint Team[...]…

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 )

Connecting to %s


Follow

Get every new post delivered to your Inbox.