Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

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();

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

                    }

  }

}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a sharepoint.stackexchange
scroll top