How to delete multiple Items from a SharePoint List
There are scenarios where you want to delete multiple list items at once. Insetad of using delete method of SPListItem you can use the following code that deletes multiple list items that uses batch process.
void DeleteBulkItems(SPWeb web,SPList list, String Ids)
{
StringBuilder sbDelete = new StringBuilder();
sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");
string command = "<Method><SetList Scope=\"Request\">" + list.ID + "</SetList><SetVar Name=\"ID\">{0}</SetVar><SetVar Name=\"Cmd\">Delete</SetVar></Method>";
string[] _DeletedIDs = Ids.Split(',');
foreach (String item in _DeletedIDs)
{
sbDelete.Append(string.Format(command, item.ToString()));
}
sbDelete.Append("</Batch>");
web.ProcessBatchData(sbDelete.ToString());
}
In this method 3 parametrs are there SPWeb, SPList(List name from where you want to delete items) and Ids (List item ids to be deleted).
In above code snippet you can see that i am using a xml batch with command delete to delete list items with the specified List Item ids.
Here is the code snippet from where above function is called ;
SPweb web =SPContext.Current.Web;
SPList list=web.Lists["your list title"];
SPListItemCollection _coll = list.Items
string IDs = string.Empty;
if (_coll.Count > 0)
{
foreach (SPListItem item in _coll)
{
IDs = IDs + string.Format("{0},", item.ID);
}
}
IDs = IDs.TrimEnd(',');
DeleteBulkItems(web, list, IDs);
In above code i have used a string variable and that stores the ids of list items separetd by comma and in the end called the "DeleteBulkItems" function with the parameterts and the ids of the items to be deleted.
This is an eaxample of batch process that deletes the list items.
No comments:
Post a Comment