How to retrieve and update the Lookup Field in Sharepoint using c#

This code will guide you, how to retrieve and update lookup field in sharepoint using C#

1. My Skill is the list that contains Skill field which is lookup.

using (SPSite site = new SPSite("http://URL"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["My Skill"]; //My Skill is the list contains Skill as a lookup field
                    SPListItemCollection itemCollection= list.Items;

                    //Retrieve lookup fields
                    foreach (SPListItem item in itemCollection)
                    {
                        SPFieldLookupValue lookupField = new SPFieldLookupValue(item["Skill"].ToString());
                        string lookUpValue = lookupField.LookupValue;
                    }

                    //Retrieve  lookup id which you want to update first
                    int ValueId = 0;
                    foreach (SPListItem item in itemCollection)
                    {
                        SPFieldLookupValue lookupField = new SPFieldLookupValue(item["Skill"].ToString());
                        if (lookupField.LookupValue.Equals("ASP"))
                        {
                            ValueId = lookupField.LookupId;
                            break;
                        }
                    }

                    //Now update it with id and value
                    foreach (SPListItem item in itemCollection)
                    {
                        SPFieldLookupValue lookupField = new SPFieldLookupValue(item["Skill"].ToString());
                        if (lookupField.LookupValue.Equals("JAVA"))
                        {
                            item["Skill"] = new SPFieldLookupValue(ValueId, "ASP");
                            item.Update();
                            break;
                        }
                    }

                }
            }

Advertisements

3 thoughts on “How to retrieve and update the Lookup Field in Sharepoint using c#

  1. This doesn’t work. You can’t update an item’s value with an ID of another value. Say that ASP is #2 and JAVA is #3, this is like saying you can set item[“Skill”] = #3,JAVA by supplying the ID for the “ASP” record (#2). The code above would set item[“Skill”] = #2;JAVA, which is incorrect (should be #3). I’d like to know how to get the ID using the text of the object in the lookup and then update that lookup with it.

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 )

Google+ photo

You are commenting using your Google+ 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