, ,

I have decided to use an event receiver to create a copy of previous version of an item from a list into a separate list, created for keeping versions. So I created first a list called “Tickets” with the following structure.

Column Name Column Type
Ticket Title Single line of text
Priority Choice

I have also created another list with the same structure (I kept also column names for making work easier) and I called it “Tickets History”.
After I completed those steps, I created a static class for adding items to the SharePoint lists. In general, I prefer static classes for operations I execute often, because I do not rewrite a lot of code in each section of a project.

    public class ListOperations
        public static void AddListItem(Dictionary<string, string> listItem, string listName, SPWeb web)
            SPList lst = web.Lists[listName];
            SPListItem item = lst.AddItem();
            foreach (KeyValuePair<string, string> field in listItem)
                item[field.Key] = field.Value;

Event receiver was attached to “Sprint Tickets” list and triggered by update operations. Code presented below shows how event receiver is using my static class to add previous version into “Sprint Tickets History”.

 public class TicketChangedEvent : SPItemEventReceiver
        /// <summary>
        /// An item is being updated.
        /// </summary>
        public override void ItemUpdating(SPItemEventProperties properties)

            SPWeb web = properties.OpenWeb();
            Dictionary<string, string> historyItem = new Dictionary<string, string>();
            historyItem["Ticket Title"] = (String)properties.ListItem["Ticket Title"];
            historyItem["Priority"] = (String)properties.ListItem["Priority"];
            ListOperations.AddListItem(historyItem, "Tickets History", web);   

Note that SPContext cannot be used from an event receiver to get current site or web, but properties.OpenWeb() or properties OpenSite() can do the job in this case.