Delete item from SharePoint List

In my previous post SharePoint List C# Part 1 I discussed how we can add items to SharePoint list. We also have to delete items from a list. Following C# code can be used in your custom webpart or feature to delete item from SharePoint list. Here I am going to find the items to delete using CAML query.




public void DeleteListItem(){



string strUrl = "http://merdev-moss:5050/testsite";

SPSite site = new SPSite(strUrl);

SPWeb web = site.OpenWeb();



SPList list = web.Lists["Tasks"];

SPListItemCollection itemCollection;



SPQuery oQuery = new SPQuery();

oQuery.Query = "<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>ABC</Value></Eq></Where>";

itemCollection = list.GetItems(oQuery);



List<SPListItem> valuesToDelete = new List<SPListItem>();



foreach (SPListItem item in itemCollection){

if (item != null){

try{

valuesToDelete.Add(item);

}

catch (Exception e){

Console.Write(e.ToString());

}

}

}

web.AllowUnsafeUpdates = true;

foreach (SPListItem itm in valuesToDelete){

itm.Delete();

}

list.Update();

web.AllowUnsafeUpdates = false;

In the above example I have use a CAML query to delete items in the Task list which title equal to ABC. As above you have to maintain separate list to stote items that you are goint to delete, otherwise it will not work.