atrljoe
atrljoe

Reputation: 8151

SharePoint Subsite - Iterate over lists

I have a SharePoint site. I am trying to open a subsite and get a list of all lists in that subsite. This code returns the top level "http://myspserver" lists.
How do I get only the lists from /mysubsite?

string webUrl = "http://myspserver/mysubsite";

using (SPWeb oWebsite = new SPSite(webUrl).OpenWeb()) //Open SP Web
{

    SPListCollection collList = oWebsite.Lists; //Open Lists

    foreach (SPList oList in SPContext.Current.Web.Lists)
    //For Each List Execute this
    {
        ....
    }
}

Upvotes: 3

Views: 4940

Answers (2)

theChrisKent
theChrisKent

Reputation: 15099

You create the SPListCollection object, but there you use the SPContext.Current.Web.Lists in your foreach, correct your code like this and things should be fine:

string webUrl = "http://myspserver/mysubsite";

using (SPWeb oWebsite = new SPSite(webUrl).OpenWeb()) //Open SP Web
{

    SPListCollection collList = oWebsite.Lists; //Open Lists

    foreach (SPList oList in collList)
    //For Each List Execute this
    {
       ....
    }
}

Upvotes: 2

Kobi
Kobi

Reputation: 138117

You should iterate over collList, not SPContext.Current.Web.Lists.

foreach (SPList oList in collList)
{
}

SPContext.Current.Web.Lists will get the site you are currently in. Presumably, this is http://myspserver when you run your code.

Also, note that your code leaks - you do not dispose of the SPSite object. It should look like:

using(SPSite site = new SPSite(webUrl))
using(SPWeb oWebsite = site.OpenWeb())
{
}

Upvotes: 4

Related Questions