I have a document library with several layers of folders within, I'm trying to populate a dropdownlist in a web part to display a tree like display of the folders but my code

    foreach(SPListItem lItem in docLibrary.Items)
        if (lItem.Folder == null) {}
            ListItem ddlItem = new ListItem(lItem.Name, lItem.ID.ToString());

In my testing library I have two folders with one file in the second folder, when this loop executes it retrieves the count of ListItems as 3 but only ever iterates once, how can I make the list iterate and pick up the folders?

1 Answer 1


This code iterates all sub folder of your root folder and gets items by your query from subfolders

foreach (SPFolder subFolder in docLibrary.RootFolder.SubFolders)
     SPQuery oQuery = new SPQuery();
     oQuery.Query = "Your Query"
     oQuery.Folder = subFolder;                               
     collListItems = oList.GetItems(oQuery);                                
  • 1
    Thanks, I found that you can just use docLibrary.Folders instead of docLibrary.Items and it returns an SPListItemCollection containing only the folders. Dec 19, 2013 at 12:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.