Thursday, March 18, 2010

SPFolder related operations in SharePoint

1) Get SPListItem(s) of a particular SPFolder


SPList splist;
SPFolder spfolder; //Get the required folder instance
SPQuery spquery = new SPQuery();
spquery.Query = string.Empty;
spquery.Folder = spfolder;
spquery.ViewAttributes = "Scope=\"Recursive\""; //For nested folder structure

SPListItemCollection itemCol = splist.GetItems(spquery)


2) Create a SPListItem based on a custom ContentType or SPFolder ContentType

SPWeb spweb; //get the SPWeb instance
SPContentType myCType = splist.ContentTypes["Custom content type"];
SPList splist = spweb.Lists["My SPList"];
SPListItem splistitem = splist.Items.Add();
splistitem["ContentTypeId"] = myCType.Id;
splistitem.Update();

splistitem["Title"] = "New Item";
splistitem.Update();


3) Add a SPListItem in a particular SPFolder

SPWeb spweb; //get the SPWeb instance
SPContentType myCType = splist.ContentTypes["Custom content type"];
SPList splist = spweb.Lists["My SPList"];
//get folder instance
SPFolder spfolder = splist.Folders[1];
SPListItem splistitem
= splist.Items.Add(spfolder.ServerRelativeUrl
, SPFileSystemObjectType.File, null);

splistitem["ContentTypeId"] = myCType.Id;
splistitem.Update();

splistitem["Title"] = "New Item";
splistitem.Update();

4 comments:

Term Papers said...

I have been visiting various blogs for my term papers writing research. I have found your blog to be quite useful. Keep updating your blog with valuable information... Regards

Mina said...

Hi
In section 3 the line
SPFolder spfolder = splist.Folders[1];
is wrong as SPList.Folders[1] will return SPListItem not SPFolder object
thanks

Avinash said...

Hi Mina,
Yes you are right... you have to typecast SPListItem to SPFolder.

SPFolder spfolder = (SPFolder) splist.Folders[1];

~ Avinash

Dave Walker said...

Hi Avinash,

Where can I learn about this?:

Knowing very little about it, I am trying to add some simple functionality to my SharePoint NewForm.aspx using javascript.

I see you have many nice routine for (what I think is) asp.net, but can they be adapted for javascript?

For example, I want to move the folder "Shared Documents/test1/test" to "Shared Documents/test2/test"

How do I adapt this code to work for javascript:
string url = web.ServerRelativeUrl + "/shared documents/myfolder";
SPFolder folder = web.GetFolder(url);
folder.Item[SPBuiltInFieldId.Title] = newName;
folder.Item.Update(); // or SystemUpdate(false)

Thanks,
Dave
dwalker@altera.com

Google