Posted by: R Manimaran | July 16, 2012

Update Lookup Field using Client Object Model

Update Lookup Field using Client Object Model

I already wrote a blog article on updating the Lookup field using the Server Object Model.  Here is the blog post for reference. Click here

Here in this post, I use the same approach using the Client Object model.

Update a Lookup field

ClientContext context = new ClientContext("http://SharePoint2010Server");
List myList = context.Web.Lists.GetByTitle("CustomList1");
List lookuplist= context.Web.Lists.GetByTitle("Lookuplist");
ListItem item = myList.GetItemById(3);
context.Load(myList);
context.Load(item);
context.ExecuteQuery();
item["Country1"] = GetLookFieldIDS(context, "CANADA", lookuplist);
item.Update();
context.ExecuteQuery();

Helper Method to get the lookup field ID’s.

public static SPFieldLookupValueCollection GetLookFieldIDS(ClientContext context,
string lookupValues,
List lookupSourceList)

{
SPFieldLookupValueCollection lookupIds = new SPFieldLookupValueCollection();
string[] lookups = lookupValues.Split(new char[] { ',' },
StringSplitOptions.RemoveEmptyEntries);
foreach (string lookupValue in lookups)
{
CamlQuery query = new CamlQuery();
query.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name='Title'/>
<Value Type='Text'>{0}</Value></Eq></Where></Query></View>",lookupValue);
ListItemCollection listItems=lookupSourceList.GetItems(query);
context.Load(lookupSourceList);
context.Load(listItems);
context.ExecuteQuery();
foreach (ListItem item in listItems)
{
SPFieldLookupValue value = new SPFieldLookupValue(
Convert.ToInt32(item["ID"]), item["Title"].ToString());
lookupIds.Add(value);
break;
}
}
return lookupIds;
}
About these ads

Responses

  1. This is very. very helpful indeed, and you sir, are to be applauded.


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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: