Add, Update and Delete item in SharePoint List

I remembered add, update and delete item in SharePoint list is one of the first thing that I’ve learned in SharePoint. I know its quite common task that you have to deal within SharePoint and hence I reiterate it in this article.

The code below will Add new item into SharePoint list, Update the description of item added and Delete the item at the end.

using (SPSite site = new SPSite("http://sitename"))
// Or SPContext.Current.Site.Url
{
   using (SPWeb Web = site.OpenWeb())
   {
      Web.AllowUnsafeUpdates = true;

      // Open List
      SPList list = Web.Lists["MyList"];

      // Add new item in List
      SPListItem item = list.Items.Add();
      item["Title"] = “Test Title”;
      item["Description"] = “Test Description”;
      item.Update();

      // Get Item ID
      int listItemId = item.ID;

      // Update the List item by ID
      SPListItem itemUpdated = list.GetItemById(listItemId);
      itemUpdated["Description"] = “Update Description”;
      itemUpdated.Update();

      // Delete item
      SPListItem itemDeleted = list.GetItemById(listItemId);
      itemDeleted.Delete();

      Web.AllowUnsafeUpdates = false;
   }
}
Advertisements

Tagged: , , , , ,

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: