SharePoint 2010 - List - Add, Edit, Delete Using Code

In this article we can experiment with list manipulations through code. The following are the list operations to perform:

  1. Add
  2. Edit
  3. Delete

Pre-Requisite

To proceed we need to create a list named "Tasks" using the template "Tasks".

ShrLst1.jpg

Now create a new "SharePoint Console Application" project inside Visual Studio.

ShrLst2.jpg

Ensure you changed the "Application Target Framework" to the .Net 3.5 version.

Adding an Item

For adding a new Task Item execute the following code:

using (SPSite site = new SPSite("http://appes-pc"))
{
    using (SPWeb web = site.OpenWeb())                 
    {
        SPList list = web.Lists["Tasks"];
        SPListItem item = list.Items.Add();
        item["Title"] = "New Task";
        item["Description"] = "Description of Task";

        item.Update();
    }
}

Now you can check the Tasks list inside SharePoint and you will see the new item there.

ShrLst3.jpg

Editing an Item

For editing an existing task use the following code. Here we are changing the first item Title and Description.

using (SPSite site = new SPSite("http://appes-pc"))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPList list = web.Lists["Tasks"];
        SPListItem item = list.Items[0];
        item["Title"] = "Edited Task";
        item["Description"] = "Description of Task (edited)";
 
        item.Update();
    }
}


Going back to SharePoint you will see the edited task:

ShrLst4.jpg

Deleting an Item

For deleting an item use the following code:

using (SPSite site = new SPSite("http://appes-pc"))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPList list = web.Lists["Tasks"];
        SPListItem item = list.Items[0];

        item.Delete();
    }
}


Now you can go back to SharePoint and see that the item was deleted.

ShrLst5.jpg

References

http://suguk.org/blogs/tomp/archive/2006/09/28/Adding_SPListItems.aspx

Summary

In this article we have experimented with the list manipulations Add, Edit and Delete through code. In real-life we will need to automate list manipulations and the programming will be a help in this regard.