Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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?

share|improve this question
add comment

4 Answers 4

up vote 5 down vote accepted

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.

share|improve this answer
add comment

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>";

            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 iLookup = GetLookupIDFromList(web, "LookupListName", "Title", strLookupValue);

                    if (iLOE > 0)
                    {
                        spflv.LookupId = iLOE;

                        item["LookupFieldName"] = spflv;

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

                    }
     item["LookupField"]=iLookupID;

     item.Update();

  }

}
share|improve this answer
add comment

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();
share|improve this answer
3  
I happen to have written an article on this very subject a few moments ago. :) tsstsst.com/?p=44 –  Stuart Pegg Aug 16 '11 at 20:58
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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