Wednesday, 30 July 2014

Programmatically Delete all Item in SharePoint List using c#

Share it Please
       
        public static void DeleteAllItems(string list)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (SPSite spSite = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        spWeb.AllowUnsafeUpdates = true;
                        StringBuilder deletebuilder = BatchCommand(spWeb.Lists[list]);
                        spSite.RootWeb.ProcessBatchData(deletebuilder.ToString());
                        spWeb.AllowUnsafeUpdates = false;
                    }
                }
            });

        }
        private static StringBuilder BatchCommand(SPList spList)
        {
            StringBuilder deletebuilder = new StringBuilder();
            deletebuilder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");
            string command = "<Method><SetList Scope=\"Request\">" + spList.ID +
                "</SetList><SetVar Name=\"ID\">{0}</SetVar><SetVar Name=\"Cmd\">Delete</SetVar></Method>";

            foreach (SPListItem item in spList.Items)
            {
                deletebuilder.Append(string.Format(command, item.ID.ToString()));
            }
            deletebuilder.Append("</Batch>");
            return deletebuilder;
        }
   DeleteAllItems("Employee");

No comments:

Post a Comment

Followers

Follow The Author