Sunday, October 2, 2011

Client Object Model Add,Update and delete List Items

Creating, Updating, Deleting List items using Client Object Model, is almost similar to doing this using Server Object Model.

Create List Items
Create List item, set its properties and update the object.

string siteUrl = "http://anmol-pc";
ClientContext clientContext = new ClientContext(siteUrl);
SP.List oList = clientContext.Web.Lists.GetByTitle("Test");

ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
ListItem oListItem = oList.AddItem(itemCreateInfo);
oListItem["Title"] = "My First Item!";
oListItem["FirstName"] = "Anmol Rehan";

oListItem.Update();
clientContext.ExecuteQuery();
//-----------------------------------------------------------------------------------------------

Update List Items
To update List item, get the item by id using GetById() method. Then set the properties and update the object.

string siteUrl = "http://anmol-pc";
ClientContext = new ClientContext(siteUrl);
SP.List oList = clientContext.Web.Lists.GetByTitle("Test");

ListItem oListItem = oList.GetItemById(6);
oListItem["FirstName"] = "Anmol";
oListItem["LastName"] = "Rehan";
oListItem.Update();

clientContext.ExecuteQuery();

//-----------------------------------------------------------------------------------------------

Delete List Item
To update List item, get the item by id using GetById() method. Then call objects deletion method DeleteObject().

string siteUrl = "http://anmol-pc";
ClientContext = new ClientContext(siteUrl);
SP.List oList = clientContext.Web.Lists.GetByTitle("Test");

ListItem oListItem = oList.GetItemById(6);
oListItem.DeleteObject();
clientContext.ExecuteQuery();

3 comments:

  1. Thanks you blog has helped a lot.

    ReplyDelete
  2. Hi Anmol,

    If you want to delete document library itew by Title, then how should I do it? I have ClientContext only.

    Thank you

    ReplyDelete

Popular Posts