21

How do I set a ListItem's Lookup field using code?

SPFile file = list.RootFolder.Files.Add(destUrl, iStream, true);
SPListItem item = file.Item;

item["DocumentID"] = DocID.ToString();
item["Priority"] = "2";
item["StatusLookup"] = "Draft";
 item.Update();

This code throws an exception:

Invalid data has been used to update the list item. The field you are trying to update may be read only

What is the correct syntax to set lookup fields?

1

4 Answers 4

17

Use the ID of the lookup target:

        using(SPSite site = new SPSite("http://test.dev.com"))
        using (SPWeb web = site.OpenWeb())
        {
            SPList list = web.Lists["Suppliers"];
            SPListItem item = list.AddItem();

            item[SPBuiltInFieldId.Title] = "Test";
            item["Product"] = 1; // Use the ID; get it from the list

            item.Update();
        }

In this case, I have a list called Suppliers which has a field called Product that is a lookup to a list called Products. You can use the ID of the lookup target in either integer form or in string form ("1").

I've hardcoded it just to provide an example. You'll need to do a separate lookup to the target list to get the value.

16

A better way of doing this is the SPFieldLookupValue class. MSDN has a good example.

In short, something like:

SPListItem lookedUpItem =  GetItemSomeHow();
newItem[lookupField] = new SPFieldLookupValue( lookedUpItem.ID, lookedUpItem.Title);
newItem.Update();
2
  • 4
    I happen to have written an article on this very subject a few moments ago. :) tsstsst.com/?p=44
    – Stu Pegg
    Commented Aug 16, 2011 at 20:58
  • You don't actually have to set the Title from the lookup item. Using the ID alone is sufficient (and if you are passing stuff around in a query string, possibly easier). Commented Apr 26, 2016 at 15:10
2

Here's a function to find the lookup ID from the lookup table:

public static int GetLookupIDFromList(SPWeb web, string strListName, string strLookupColumnName, string strLookupValue)
    {
        try
        {
            SPList list = web.Lists[strListName];

            string strCAMLQuery = "<Where><Eq><FieldRef Name='"+strLookupColumnName+"' /><Value Type='Text'>"+ System.Web.HttpContext.Current.Server.HtmlEncode(strLookupValue)+"</Value></Eq></Where>";
             //If you are developing console application, use  
            // System.Web.HttpUtility.HtmlEncode(strLookupValue) instead of 
            //System.Web.HttpContext.Current.Server.HtmlEncode(strLookupValue)

            SPQuery query = new SPQuery();
            query.Query = strCAMLQuery;
            query.ViewFields = string.Concat(
                                    "<FieldRef Name='ID' />",
                                    "<FieldRef Name='"+strLookupColumnName+"' />");


            SPListItemCollection items=list.GetItems(query);

            if (items.Count > 0)
            {
                int iRet = items[0].ID;
                return iRet;
            }
            else
            {
                return 0;
            }
        }
        catch (Exception ex)
        {
            return 0;
        }
    }

Here is a sample of how to use the function:

using (SPSite site = new SPSite("http://yoursite/web"))
 {
   using (SPWeb web=site.OpenWeb())
   {
     SPList list=web.Lists["ListToUpdate"];

     SPListItem item =list.AddItem();


     string strLookupValue = "Lookup Value";

                    int LookupID= GetLookupIDFromList(web, "LookupListName", "Title", strLookupValue);

                    if (LookupID> 0)
                    {
                        SPFieldLookupValue spflv = new SPFieldLookupValue(LookupID,strLookupValue);
                        //spflv.LookupId = LookupID;

                        item["LookupFieldName"] = spflv;
                        item.Update();


                    }
                    else
                    {
                        strRet += "Lookup value [" + strLookupValue+ "] not found.<br />";

                    }

  }

}
1

http://www.sharepoint-tips.com/2007/10/code-practices-gettingsetting-values.html

Example 3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.