Kategoriarkiv: SPListItem

Programmatically move a SPListItem to another folder in the same list

I had a hard time finding a good source for this, and therefore decided to write a short post about it.

First of all, I want to say that I am against the use of folders unless you absolutely need them. They add unnecessary complexity, and you can have the benefits of folders without many of the drawbacks by using metadata instead, for example with managed metadata fields. However, as there are no OOTB (out of the box) way of handling permissions for a group of items based in their metadata, folders MIGHT be useful for that purpose. There are other solutions though.

Now to the task at hand, moving a SPListItem based on it’s metadata, and then moving it to a subfolder in the same list. In my example, I will be moving the item in an event receiver.

What we need to do is to check the SPFileSystemObjectType of the SPListItem. This value will actually be File, even it it’s not a document library. Regular list items will also return object type File. This is only needed if you don’t want to move folders the same way.

This code assumes you have already got your SPListItem:

Then we need to get the file object of the item. The file object will exist even if the list is not a library, and this code will work for documents and list items alike.

Then we want to build the new destination path were the item will be moved to. The path should follow the pattern: “<web url>/<list rootfolder url>/<subfolder>/<item Id>._000″

And lastly, we simply call the SPFile.MoveTo method on our file object, and add the destination path.

And that’s it. Put this in an ItemAdded function in an event receiver for a list and items will automatically be moved to the correct folder. Below is my complete example where I also make sure the folder exist before moving the item.

Sources:

http://zhebrun.blogspot.se/2011/06/sharepoint-how-to-move-listitem-or.html

 

Get and format DateTime string from SharePoint DateTime field

A collegue of mine (his blog here) showed me something nice yesterday. We have a webpart which shows how long ago some list items where created by simply getting the DateTime string from the standard “Created” column.

string x = ((DateTime)item[SPBuiltInFieldId.Created]).ToString();

We ran into trouble however, when we used this webpart on a server in a country using a different time format. The problem was easily fixed like so:

string x = ((DateTime)item[SPBuiltInFieldId.Created]).ToString(“s”);

This converts the DateTime string to a standard format which allows it to be understood by various javascript and jQuery functions and plugins, which was exactly what we needed.

Here is a list of other formats you can get with this method by simply replacing the “s” with another letter.