Friday, September 7, 2012

How to create folder in sharepoint custom list programmatically


Here is steps to add new item as a folder in sharepoint list programmatically.

- Create new instance of site with your current application
using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
{

- Create new web instance and open web for current application
using (SPWeb webFolder = site.OpenWeb())
{

- Get folder by folder name in list

SPFolder folder = webFolder.GetFolder("/Lists/Your List Name/Your Folder Name");

- Check whether folder is exist in list or not, if not then create new folder
if (folder.Exists)
{
Response.Write("Folder name already exists.");
return;
}

- Create list and Get County list
SPList list = webFolder.Lists[Your List Name];

- Set AllowUnsafeUpdates to true to insert new item through code
webFolder.AllowUnsafeUpdates = true;

- Create new item to add
SPListItem item = list.Items.Add();
item.FileSystemObjectType = SPFileSystemObjectType.Folder;

- Set values for the folder name
item["Title"] = “Your Folder Name”;

- fire update event for County list
item.Update();
webFolder.Update();

 }
}

-That’s it for adding new item to your sharepoint list as folder.