SharePoint: How to Add/Update/Delete List Items using Client Object Model

In this article we will see how to perform basic CRUD operations on SharePoint List using Managed Client object model.

Steps to add new List Item:

·         Go to Visual Studio 2010.

·         Go to File => New => Project.

·         Select Console Application and name it as CreateListItem.

·         Click Add.

·         Add the references to Microsoft.SharePoint.Client.dll.

 

using Microsoft.SharePoint.Client;

namespace CreateListItem
{
class Program    {
static void Main(string[] args)
{
string siteUrl = “http://xxxxxxxx:9999/sites/mysitecollection”;
ClientContext clientContext = new ClientContext(siteUrl);
List oList = clientContext.Web.Lists.GetByTitle(“TestList”);
ListItemCreationInformation listCreationInformation = newListItemCreationInformation();
ListItem oListItem = oList.AddItem(listCreationInformation);
oListItem[“Title”] = “Creating New Item”;
oListItem.Update();
clientContext.ExecuteQuery();
}
}
}

·         Hit F5.

·         Go to the SharePoint list “TestList” and you could see a new item is added.

Steps to update List Item:

using Microsoft.SharePoint.Client;
namespace UpdateListItem
{
class Program    {
static void Main(string[] args)
{
string siteUrl = “http://xxxxxxxx:9999/sites/mysitecollection”;
ClientContext clientContext = new ClientContext(siteUrl);
List oList = clientContext.Web.Lists.GetByTitle(” TestList”);
ListItem oListItem = oList.GetItemById(1); // 1 is id of item to be updated
oListItem[“Title”] = “Updating Item.”;
oListItem.Update();
clientContext.ExecuteQuery();
}
}
}

Hit F5.
Go to the SharePoint list “TestList” and you could see a item is updated.

Code to delete List Item based on ItemID:

using Microsoft.SharePoint.Client;
namespace UpdateListItem
{
class Program    {
static void Main(string[] args)
{
string siteUrl = “http://xxxxxxxx:9999/sites/mysitecollection”;
ClientContext clientContext = new ClientContext(siteUrl);
List oList = clientContext.Web.Lists.GetByTitle(“TestList”);
ListItem oListItem = oList.GetItemById(1); // 1 is item id to be delted
oListItem.DeleteObject();
clientContext.ExecuteQuery();
}
}
}

Hit F5.
Go to the SharePoint list “TestList” and you could see a new item is added.

Hope this helps…Happy Coding!!!!

(Visited 68 times, 1 visits today)