Event handler to archive items when deleted

The requirement – copy a list item that is deleted to an archive list. The solution – event receiver that copies the item. The code below does the job, but again is only a sample – you still need to implement error handling, and there are hard coded variables there you will want to change.

Note: this code is specifically for list items, not for documents in document libraries. You can easily change the code to support documents as well (see the CopyAttachments function for an example on how to copy files).

public override void ItemDeleting(SPItemEventProperties properties) {

//note: may require permission elevation. //TODO: add error handling //get the item being deleted

SPListItem item = properties.ListItem;

//get the target list

SPList targetList = properties.Web.Lists[“Announcements Archive”];

//create the new item

SPListItem newItem = targetList.Items.Add();

//copy the list item to the target

foreach (SPField f in item.Fields) {

if (!f.ReadOnlyField && newItem.Fields.ContainsField(f.InternalName)) newItem[newItem.Fields.GetFieldByInternalName(f.InternalName).Id] = item[f.Id]; }

//copy “special” read only fields that can be written to

newItem[“Created By”] = item[“Created By”];

newItem[“Modified By”] = item[“Modified By”];

newItem[“Modified”] = item[“Modified”];

newItem[“Created”] = item[“Created”];

newItem.SystemUpdate(false);

CopyAttachments(item, newItem);

base.ItemDeleting(properties); }

Note: for the “CopyAttachments” View this Page : How to copy attachments from one list item to another

Ref : Sharepoint Tips And Tricks

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s