Tuesday, October 18, 2011

Delete all items from a SharePoint List C# programatically

/// <summary>
/// Delete items and folders from a listFromItemTobeDeleted
/// Define WSSV3 to remove listFromItemTobeDeleted folders
/// </summary>listFromItemTobeDeleted
/// The SPList you want to
/// Delete items from
private static void DeleteAllItemfromTheList(SPList listFromItemTobeDeleted)
{
Console.WriteLine("Purging listFromItemTobeDeleted: " + listFromItemTobeDeleted.Title);
Console.WriteLine("Base Type: " + listFromItemTobeDeleted.BaseType.ToString());

// ===========================================================
// listFromItemTobeDeleted.ItemCount returns a count that includes all items
// "AND" folders.
// You can't use listFromItemTobeDeleted.Items.DeleteItemById() to remove a
// folder
// ===========================================================
System.Collections.Hashtable hashtableItemCollection =
new System.Collections.Hashtable(listFromItemTobeDeleted.ItemCount);

// ===========================================================
// SPList.Items returns all listFromItemTobeDeleted items in the entire listFromItemTobeDeleted
// regardless of folder containment
// Note, just because listFromItemTobeDeleted.ItemCount includes folders,
// listFromItemTobeDeleted.Items does not.
// ===========================================================
foreach (SPListItem listItems in listFromItemTobeDeleted.Items)
hashtableItemCollection.Add(listItems.ID,null);

// Remove the listFromItemTobeDeleted items
foreach (int ID in hashtableItemCollection.Keys)
listFromItemTobeDeleted.Items.DeleteItemById(ID);
// Clear the hashtable
hashtableItemCollection.Clear();
// ===========================================================
// SPList.Folders returns all folder items in the entire listFromItemTobeDeleted
// regardless of parent folder containment
// ===========================================================
foreach (SPListItem listItems in listFromItemTobeDeleted.Folders)
hashtableItemCollection.Add(listItems.ID,null);

// Remove the folder items
foreach (int ID in hashtableItemCollection.Keys)
{
listFromItemTobeDeleted.Folders.DeleteItemById(ID);
}
}

No comments:

Post a Comment

Thank you for Commenting Will reply soon ......

Featured Posts

How to Disable Sleep When You Close the Laptop Lid in Ubuntu

Have you ever connected your Ubuntu laptop to an external monitor, SSH session, server, or other device and discovered that everything stops...