Tuesday, February 1, 2011

Extension method in VB.net to clear items in a SharePoint List

        ''' <summary>
        ''' Clear all items in a SharePoint list - Created by Ken
        ''' </summary>
        ''' <param name="list"></param>
        ''' <remarks></remarks>
        <Extension()> _
        Public Sub Clear(ByRef list As SPList)
            If Not list.ItemCount = 0 Then
                Dim sbDelete As New System.Text.StringBuilder
                sbDelete.Append("<?xml version=""1.0"" encoding=""UTF-8""?><Batch>")
                For Each listItem In list.Items
                    sbDelete.Append("<Method>")
                    sbDelete.Append("<SetList>" & list.ID.ToString & "</SetList>")
                    sbDelete.Append("<SetVar Name=""Cmd"">DELETE</SetVar>")
                    sbDelete.Append("<SetVar Name=""ID"">" + listItem("ID").ToString + "</SetVar>")
                    sbDelete.Append("</Method>")
                Next
                sbDelete.Append("</Batch>")
                list.ParentWeb.ProcessBatchData(sbDelete.ToString())
                list.Update()
            End If
        End Sub

Another implementation of the same is shown below. Performance is very poor with the below code. If you have a lot of list items then make sure you use processbtachdata instead.


        ''' <summary>
        ''' Clear all items in a SharePoint list - Created by Ken
        ''' </summary>
        ''' <param name="list"></param>
        ''' <remarks></remarks>
        <Extension()> _
        Public Sub Clear(ByRef list As SPList)
            If Not list.ItemCount = 0 Then
                For i = list.ItemCount - 1 To 0 Step -1
                    Dim listItem = list.Items(i)
                    listItem.Delete()
                Next
                list.Update()
            End If
        End Sub


In VB 10 you do not need the underscore after the attribute declaration. In other words, line continuation is supported in VB 10 / Visual studio 2010/ .net framework 4.0. For more info refer to Scott guthries article 

Similar example can be found here