Export (0) Print
Expand All

How to: Add or Delete a List in Multiple Web Sites

Windows SharePoint Services 3

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

You can use one of the Add methods of the SPListCollection class to add a list to multiple Web sites across a site collection.

The following example creates a generic list on every Web site, based on the title and description that is passed from two text boxes to the code. The AllWebs property of the SPSite class is used to return the collection of all Web sites that exist on the site.

This example assumes the existence of two text boxes on the .aspx page that contains a form.

string listTitle = TextBox1.Text.ToString();
string listDescription = TextBox2.Text.ToString();

SPSite mySite = SPContext.Current.Site;
SPWebCollection allWebs = mySite.AllWebs;

foreach (SPWeb web in allWebs)
{
    SPListCollection allLists = web.Lists;
    allLists.Add(listTitle,listDescription, SPListTemplateType.GenericList);
}

The previous example requires a using directive (Imports in Visual Basic) for the Microsoft.SharePoint namespace.

If you want to delete a list from every Web site in which it appears, use the Delete method of the SPListCollection class. The following example uses nested loops to drill down to a list that has a title matching the title specified in a text box. The example assumes the existence of a text box on the .aspx page that contains a form.

SPSite mySite = SPContext.Current.Site;
SPWebCollection allWebs = mySite.AllWebs;

foreach (SPWeb web in allWebs)
{
    SPListCollection allLists = web.Lists;

    for (int i=0; i<allLists.Count; i++)
    {
        SPList list = allLists[i];

        if (list.Title == TextBox1.Text)
        {
            Guid listGuid = list.ID;
            allLists.Delete(listGuid);
        }
    }
}

In the example the Title property of the SPList class is used to identify a list in the collection of lists for each Web site that matches the specified title. The ID property returns the globally unique identifier (GUID) of the list, which is passed as the parameter for the Delete method.

The previous example requires a using directive (Imports in Visual Basic) for the Microsoft.SharePoint namespace.

Show:
© 2014 Microsoft