Tag Archives: splist

SharePoint 2010: Add, Update and Delete List Items Using The Server Side Object Model

In this blog post I will explain and demonstrate how to Add, Update and Delete a SharePoint List Item using the server side object model.

Adding a New Item
In the code sample below I obtain the current context and the web and get the list I would like to add the new item to. After I have assigned values to my fields I call an update method from the item.

SPWeb spWeb = SPContext.Current.Web;
SPList spList = spWeb.Lists["MyList"];
SPListItem item = spList.Items.Add();
item["Title"] = "Hello, world!";
item.Update();

 
Update an Existing Item

Updating an existing item from a SharePoint List is very similar to adding a new item, but the only difference is instead of calling Add() from the SPListItemCollection, I now call the GetItemById(int) from the SPList object. There are other ways of getting an item from a list and another one is GetItemByTitle.

SPWeb spWeb = SPContext.Current.Web;
SPList spList = spWeb.Lists["MyList"];
SPListItem item = spList.GetItemById(1);
item["Title"] = "Hello, world!";
item.Update();

 
Deleting an Existing Item
Deleting an existing item from a SharePoint List all I need to do is get the item I want from this list and then call the Delete method from the item object. That’s how easy it is.

SPWeb spWeb = SPContext.Current.Web;
SPList spList = spWeb.Lists["MyList"];
SPListItem item = spList.GetItemById(1);
item.Delete();

I hope the information I have provided in this post is useful to you.

Binding SPList to Binding Controls.

To bind a SPList to a binding control list for example the DetailsView data control you will need to provide a DataSource to it. The problem is SPList doesn’t implment the IDataSource interface, but I have discovered that there is a SPDataSource which allows you to pass a SPList object as a parameter in the constructor. Below is a code

var spList = SPContext.Current.Web.Lists["List Name"];
var ds = new SPDataSource(spList);
DetailsView1.DataSource = ds;
DetailsView1.DataBind();