Update a LookupField value for a SharePoint ListItem using Client Object Model C#

A lookup data in a SharePoint can be treated as a choice options that has been maintained in a different List. Hence if one of your field in your List is a lookup then, its value should be the ID[integer] the actual Lookup-Item (i.e., the list item id of the List as a LookUp).

For ex, in a blog site, List, Category has been used as lookup field for the List Post. By default, in SP2013, you’ll get three items for Categories. Say, their Ids are 1,2, & 3.

  • Events[1]
  • Ideas[2]
  • Opinions[3]
Now if you want to change the Category field of a Post, then, you have to pass the ID of the item and not the text value.

ClientContext ctx = new ClientContext(targetURL);
ctx.Credentials = new SharePointOnlineCredentials(userName, passWord);

this.ctx.Load(this.ctx.Web);
SP.ListCollection listCol = web.Lists;
ctx.Load(listCol);

SP.List list = listCollection.GetByTitle("ListTitle");

SP.CamlQuery camlQuery = new SP.CamlQuery();
camlQuery.ViewXml = "";
SP.ListItemCollection listItemCollection = list.GetItems(camlQuery);
this.ctx.Load(listItemCollection);
this.ctx.ExecuteQuery();

SP.ListItem listItem = listItemCollection.FirstOrDefault(t => t.DisplayName == "NameOfTheListItem");
this.ctx.Load(listItem.FieldValuesAsText); 
this.ctx.ExecuteQuery();

//[Say, for one of the Id mentioned above.]
listItem.FieldValuesAsText["PostCategory"] = 2; 

listItem.Update(); 
this.ctx.ExecuteQuery(); 

To get the id of the listItem Ideas, you’ll have to re-connect to the SharePoint server and get the ID for the text Ideas from the List Category.

NOTE: Here, I have faced a strange issue. If I update any value of the Post Item before updating the lookupField value then the previous made changes were getting overwritten. So I have to ensure that the lookupField value should always get updated first before any other field.

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 )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.