Tuesday, March 12, 2013

Add, Update and Delete List Items Programmatically in Sharepoint


Programmatically adding items to a SharePoint list

using(SPSite site = new SPSite("http://"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["SharePointList"]; // you can use web.GetList method which is better for performance.
SPListItem Item = list.Items.Add();
item["Title"] = txtCompanyName.Text; // the text which need to update
//can add required items
 item.Update();
}
}
Note: 1. No need to use SPSecurity.RunWithElevatedPrivileges.
2. No need to use allowunsafeupdate property
3. No need to update web object.

Updating a List Item programmatically
Introduction:
In this article I am going to explain you how to update list item programmatically .
Also I will explain you that How to “update content type of list item programmatically” which is little tricky.
The Code:
Update List Item metadata:-
Get the SPListeItem object and update metdata. At lst never forget to use “SPListItem.update()”.
See sample code below:-

using(SPSite oSite = new SPSite("site url"))
{
        using(SPWeb oWebsite = oSite.OpenWeb())
        {
               SPList oList = oWebsite.Lists["Tasks"];
               SPListItem oListItem = oList.Items[5];
               oListItem["Title"] = "Some Title";
               oListItem.Update();// without this line item will not update
        }
}

Update List Item content type:-
Trick:- To update content type of list item, we need to assign content type id rather than content type name.

using(SPSite oSite = new SPSite("site url"))
{
        using(SPWeb oWebsite = oSite.OpenWeb())
        {
               string cTypeName = "NewContentType";
               SPList oList = oWebsite.Lists["Tasks"];
               // get content type id
               SPContentType spCType = oList.ContentTypes[cTypeName];
               SPListItem oListItem = oList.Items[5];

               // below line will not update content type
               // oListItem["ContentType"] = “NewContentType”;

               // Correct implementation to apply new content type
               oListItem["ContentTypeId"] = spCType.Id.ToString();
               oListItem.Update();
        }
}

Delete selected Items from sharepoint list programmatically
Introduction
There are few ways to delete item from sharepoint list, however I like the way to perform ProcessBatchData method (approach 1 in this article) which seems faster to me.
Here I am going to explain about 2 approaches in which we will  use SPListItem.Delete or SPWeb.ProcessBatchData method. My example will delete items from list if DeptID match with list item.
Approach 1 (SPWeb.ProcessBatchData):
/// get SPListItemCollection using spquery.
/// generate query for all items
/// Pass query into ProcessBatchData method.
Public void DeleteItemUsingBatch(string deptId)
{
    using (SPSite site = new SPSite(SPContext.Current.Web.Url))
    {
        SPWeb web = site.OpenWeb();
        web.AllowUnsafeUpdates = true;
        SPList list = web.Lists[“Departments”];
        SPQuery query = new SPQuery();
        query.Query = "<Where> <Eq><FieldRef Name=’deptId’ /><Value Type=’Lookup’>" +
                         deptId + "</Value> </Eq></Where>";
        SPListItemCollection listItem = list.GetItems(query);
        StringBuilder sbDelete = new StringBuilder();
        string xmlFormat = @"<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        sbDelete.Append(xmlFormat);
        sbDelete.Append("<Batch>");
        string buildQuery = "<Method><SetList Scope=\"Request\">" + list.ID + "</SetList>";
        buildQuery = buildQuery +
        "<SetVar Name=\"ID\">{0}</SetVar><SetVar Name=\"Cmd\">Delete</SetVar></Method>";
        foreach (SPListItem item in listItem)
        {
               sbDelete.Append(string.Format(buildQuery, item.ID.ToString()));
        }
        sbDelete.Append("</Batch>");
        web.ProcessBatchData(sbDelete.ToString());
    }
}
Approach 2 (SPListItem.Delete):

/// get SPListItemCollection using spquery.
/// Create loop as per SPListItemCollection.count
/// in loop Delete item using SPListItem.delete.
Public void DeleteItemWithoutBatch(string deptId)
{
        SPWeb web = site.OpenWeb();
        web.AllowUnsafeUpdates = true;
        SPList list = web.Lists[“Departments”];
        SPQuery query = new SPQuery();
        query.Query = "<Where> <Eq><FieldRef Name=’deptId’ /><Value   Type=’Lookup’>" + deptId + "</Value> </Eq></Where>";
        SPListItemCollection listItems = list.GetItems(query);
        int itemCount = listItems.Count;
        for (int k=0; k<itemCount; k++)
        {
               SPListItem item = listItems[k];
               listItems.Delete(k);
        }
}


delete entire sharepoint list (Approach 1)

/// To delete list you need 2 things
/// 1. Get SPListCollection object
/// 2. Get SPList object for list which need to be deleted.
/// Then you can use like this <SPListCollection object>.Delete(SPList.ID)
SPList list;
SPListCollection lists;
using (SPSite site = new SPSite("site url"))
{
        using (SPWeb web = site.OpenWeb())
        {
               lists = web.Lists;
               string listPath = "/lists/testlist"; // you can write your list path
               list = web.GetList(listPath);
        }
}
System.Guid listGuid = list.ID;
lists.Delete(listGuid);
delete entire sharepoint list (Approach 2)

/// To delete list you need 2 things
/// 1. Get SPList object for list which need to be deleted
/// 2. Then you can use like this <SPList object>.Delete()
SPList list;
using (SPSite site = new SPSite("site url"))
{
        using (SPWeb web = site.OpenWeb())
        {                     
               string listPath = "/lists/testlist"; // you can write your list path
               list = web.GetList(listPath);
        }
}
list.Delete();

No comments:

Post a Comment