Pages

Tuesday, January 3, 2012

How to set people and group column programmatically using Client Object Model


using SP = Microsoft.SharePoint.Client;
using (SP.ClientContext _ctx = new SP.ClientContext("http://YourSiteUrl"))
{
  SP.ListItem _listItem = null;

  ctx.Credentials = CredentialCache.DefaultCredentials;
 
  SP.List _testList = web.Lists.GetByTitle("TestList");
  SP.CamlQuery _query = new SP.CamlQuery();
  query.ViewXml = @"<View><Query><Where><Geq><FieldRef Name='ID'/>" + "<Value Type='Number'>10</Value></Geq></Where></Query></View>";
  SP.ListItemCollection _listitems = _configList.GetItems(_query);

  ctx.Load(_listitems);
  ctx.ExecuteQuery();
 
  if (_listitems != null && _listitems.Count > 0)
  {
     _listItem = _listitems[0];

     SP.FieldUserValue _userValue = new SP.FieldUserValue();
     SP.User _newUser = _ctx.Web.EnsureUser("domain\\username");
     _ctx.Load(_newUser);
     _ctx.ExecuteQuery();

     _userValue.LookupId = _newUser.Id;

     _listItem["userfield"] = _userValue;
     _listItem.Update();

     _ctx.ExecuteQuery();

  }   

);

2 comments: