Adding a list folders were look simple, but adding items inside list folders has got little different way. I was little confused when seeing the list.Items.Add() having a only below 3 over loadings.
1) SPListItem item = list.Items.Add()
2) SPListItem item = list.Items.Add(string folderUrl, SPFileSystemObjectType underlyingObjectType)
3) SPListItem item = list.Items.Add(string folderUrl, SPFileSystemObjectType underlyingObjectType, string leafName)
The SPFileSystemObjectType enum has got only File, Folder, Invalid & Web . As my list is not a document library I was thinking that I cannot use any of these enum options. But I was wrong, when I saw MSDN I found that SPFileSystemObjectType .File is the option to be used. Following few lines of code will let you know how you to add items inside a Folder.
Note: Text that are in RED to be replaced with appropriate values.
using (SPSite site = new SPSite (SITE URL ))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists[LIST NAME ];
if (list != null )
{
web.AllowUnsafeUpdates = true ;
// create a list item entry into the folder
SPListItem item = list.Items.Add(“/Lists/LIST NAME/FOLDER NAME ”, SPFileSystemObjectType .File, null );
item["Title" ] = TITLE ;
item["Field1" ] = value ;
item["Field2" ] = value ;
item["Field3" ] = value ;
item.Update();
}
}
}
If you know the list folder name, then use the below method, if you have the list older object, instead of string “/Lists/LIST NAME/FOLDER NAME ” you can use itemFolder.ServerRelativeUrl .
One last final word, use relative URL when ever adding a folder items; this is the very common mistake done by lot of people, which may eat couple of trouble shooting hours to fix.