This extension method helps you to clear / Delete all rows in a SharePoint List. This code can be used in both SharePoint 2010 and SharePoint 2013.
Add the below listed SharePoint List Extension Class to your existing project. This adds an extension method to SPList class named as ClearList. Execution of this method clears all data from that list.
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
| namespace SFS.Intranet.Helpers { public static class ListDataHelper { public static bool ClearList( this SPList list) { SPWeb web = list.ParentWeb; bool AllowUnsafeUpdate = web.AllowUnsafeUpdates; try { web.AllowUnsafeUpdates = true ; StringBuilder str = new StringBuilder(); str.AppendLine( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" ); str.AppendLine( "<Batch>" ); string command = "<Method><SetList Scope=\"Request\">" + list.ID + "</SetList><SetVar Name=\"ID\">{0}</SetVar><SetVar Name=\"Cmd\">Delete</SetVar></Method>" ; foreach (SPListItem item in list.Items) { str.Append( string .Format(command, item.ID.ToString())); } str.Append( "</Batch>" ); list.ParentWeb.ProcessBatchData(str.ToString()); return true ; } catch { throw ; } finally { if (!AllowUnsafeUpdate) web.AllowUnsafeUpdates = false ; } } } } |
Execution
1
2
3
4
5
6
7
8
| using (SPSite site = new SPSite( "SITE COLLECTION URL" )) { using (SPWeb web = site.OpenWeb()) { SPList list = web.Lists[ "Temp Data" ]; list.ClearList(); } } |
Comments