Basic List Operations in SharePoint with object model

Basic List Operations in SharePoint with object model
3 votes, 4.67 avg. rating (92% score)

Introduction

In this post we will see complete basics of SharePoint list operations through object model with better code

  • Accessing SharePoint List
  • Create / Update / Delete items of List

Skill Level – Basics

Accessing SharePoint List

Method 1

using (SPSite siteCollection = new SPSite("http://intranet.adicodes.com"))
{
  using (SPWeb site = siteCollection.OpenWeb())
  {
    SPList toyList = site.Lists.TryGetList("MyTasks");
    if(toyList != null)
      Console.WriteLine("Success!");
    else
      Console.WriteLine("List does not exist");
   
  }
}

Method 2

using (SPSite siteCollection = new SPSite("http://intranet.adicodes.com"))
{
  using (SPWeb site = siteCollection.OpenWeb())
  {
    try
    {
      SPList taskList = site.GetList("/Lists/MyTasks");
      Console.WriteLine("Success!");
    }
    catch(FileNotFoundException)
    {
      Console.WriteLine("List does not exist");
    }
  }
}

We can use both the ways to get list object but, I prefer Method 1


Create / Update / Delete items of List

//Create a new item
SPListItem newItem = list.Items.Add;
newItem["Title"] = "Created Item " + DateTime.Now.ToLongDateString;
newItem.Update; //NOTE: Update must be called

//Read items by binding to grid
SPListItemCollection items = list.Items; //NOTE: This loads all items, folders, and fields!
itemGrid.DataSource = items; // Binding to grid to display items, just for scenario
itemGrid.DataBind;

//Delete the first item
list.Items[0].Delete;

//Update the first item
//Note the use of a temporary SPListItem
SPListItem updateItem = list.Items[0];
updateItem["Title"] = "Updated Item " + DateTime.Now.ToLongDateString;
updateItem.Update;

Update method must be called to save the new item. If the Update method is not called, then the list item will be lost.
When updating a list item, be sure to use a temporary SPListItem object, as shown in the code, or your changes will not be saved.
If the item was edited by another user before the update is saved, the operation will fail.

When reading items from a list, you should be careful about accessing the Items property of the list. When the Items property is accessed, it attempts to load all items, folders, and fields, which can cause performance issues. I will cover reading the items of list in a better way in another post

Conclusion

Hope this helps for users who are looking for basics before they enjoy some complex functionalities of SharePoint

October 30, 2013 В· Adi В· No Comments
Tags: , ,  В· Posted in: Basics, C#, Sharepoint 2007, Sharepoint 2010, SharePoint 2013

Leave a Reply

What is 14 + 6 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)