Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / productivity / SharePoint / SharePointOnline

How to Create a Log (History) for a Specific List Item in SharePoint 2013?

5.00/5 (2 votes)
29 Jul 2016CPOL 11.1K  
Creating a history version for list items

Introduction

Imagine if you have a list named Employees and you have an item on that list called Department and you want to keep track of each change in Department. Log is quite useful for companies with 500+ employees.

This goal could be done in many ways. One way to do this is as follows:

  • Create a new list column named Departmentlog
  • Create another list column named worklog - this should be of type multi lines of text and enable append changes to existing text in bottom of settings
  • Open Visual Studio and create a new project and select empty SharePoint project
  • On solution, click add and add new Item, then select event receivers
  • You need 2 event receivers for your desired list. First event receiver must be On Item is being updated and Second event receiver must be On item was updated.

Code

For the first event receiver, you must have the following code:

C#
public override void ItemUpdating(SPItemEventProperties properties)
{
    base.ItemUpdating(properties);

    properties.AfterProperties["Departmentlog"] =
           properties.ListItem["Department"].ToString(); //this one stores the old department.

    base.EventFiringEnabled = false;
    properties.ListItem.SystemUpdate(false);
    base.EventFiringEnabled = true;
}

For the second event receiver, you must have the following code:

C#
public override void ItemUpdated(SPItemEventProperties properties)
    {
        base.ItemUpdated(properties);

        string dep = properties.ListItem["Department"].ToString();
        string loguDep = properties.ListItem["Departmentlog"].ToString();

        if (loguDep == dep) { }

        else if (loguDep != dep) // in this point we make sure that old department 
                                 // is not same as new department, because every updates 
                                 // that are applied same changes will be in log too 
                                 // this condition prevents from this mistake. 
        {
            properties.ListItem["worklog"] = "Department was changed from: " + 
                         properties.ListItem["Departmentlog"].ToString() + " To: " + 
                         properties.ListItem["Department"].ToString();
        }

        base.EventFiringEnabled = false;
        properties.ListItem.SystemUpdate(false);
        base.EventFiringEnabled = true;        
    }

Build and deploy it. This should work properly.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)