December 16, 2008

Issue: SPQuery doesn't return items from sub-folders

In using SPQuery object to get specific items from a list, you will see that it returns only the items from the root folder. To get also items from sub-folders, you have to set ViewAttributes with "Scope='RecursiveAll'" like in the following piece of code.

using (SPSite mySiteCollection = new SPSite("http://myserver/myspsite"))
{
    using (SPWeb mySite = mySiteCollection.OpenWeb(mySiteCollection.RootWeb.ID))
    {
        SPList studentsList = mySite.Lists["Students"];
        SPQuery query = new SPQuery();
        query.ViewAttributes = "Scope='RecursiveAll'";
        SPListItemCollection items = studentsList.GetItems(query);
    }
}

No comments: