Adding a List Item inside a folder

As with v2, v3 also has seen its fair share of requests on how you can add an item to a folder in a list. Now, there are two types of lists that we are dealing with, lists that store documents and lists that store items. Internally they are identified by the list type which can be a DocumentLibrary or a GenericList. Actually the enumeration is quite huge, but these are the two values that we are concerned with. Both these types of lists can have folders and these folders can have items in them. Adding items to the folders though the UI is pretty straight forward. On the other hand, doing the same through code is a bit tricky. The SDK documents it to an extent but that is not very clear.

Adding a document to a folder in a document library is the simplest

 

SPSite site = new SPSite("http://blr3r01-13:10000");

SPWeb web = site.OpenWeb();

SPList list = web.Lists["Documents"];

SPListItemCollection folderColl = list.Folders;

foreach (SPFolder folder in folderColl)

{

if (folder.Name == "TestFolder")

{

SPFileCollection fileColl = folder.Files;

// Use fileColl.Add() to upload the file

}

}

 

Adding an item to a folder for a generic list took me some time to figure out. The point where I got mislead was believe it or not a missing '/' character. There were a number of things I tried in getting to the SPListItemCollection representing the items inside a folder. However, all attempts at getting there ended up in recurrent loops [sic]. The simplest approach was of course using the SPListItemCollection.Add() . The moment I finally obtained that collection, from there on it took me several tries to get the actual syntax right. So here's the polished up code.

 

SPSite site = new SPSite("http://blr3r01-13:10000");

SPWeb web = site.OpenWeb();

SPList list = web.Lists["Tasks"];

SPListItemCollection folderColl = list.Folders;

for (int i = 0; i < folderColl.Count; i++)

{

if (folderColl[i].Folder.Exists)

{

SPFolder folder = folderColl[i].Folder;

SPListItemCollection itemColl = list.Items;

SPListItem item = itemColl.Add("/Lists/Tasks/TestFolder", SPFileSystemObjectType.File, null);

item["Title"] = "AddedFromOM";

item.Update();

}

}

 

All in a day's work.

 

Cheerio

/Harsh

 

 

Blogged using Microsoft Office Word 2007 running on Microsoft Vista