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




Recent Comments