Tuesday, October 11, 2011

Event receiver to update an item's in list

How to update Created By and Modified By fields in sharepoint list using C#
In this article I will explain, how to update list item in event receiver. In event receiver, I will update Created By /Modified By/Title metadata of list item.
Code:

public override void ItemUpdated(SPItemEventProperties properties)
    {
        int userID=0;
        string userNTID = "WIN\AMITKUMAR";
        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
        SPListItem CurrentItem = properties.ListItem;
        CurrentItem.Web.AllowUnsafeUpdates = true;
        CurrentItem.Web.Site.AllowUnsafeUpdates = true;
        // In the next statment i am updating CreatedBy(Author) filed with SystemAccount
        CurrentItem["Author"] = CurrentItem.Web.Site.SystemAccount.ID; //CreatedBy
        //We can also update CreatedBy(Author)/ModifiedBy(Editor) field with Any user account
         FindUserIDByNTID(userNTID, CurrentItem.Web.Site, ref userID);
         if (userID > 0)
         {
            CurrentItem["Editor"] = userID; //ModifiedBy
         }
         else
         {
            CurrentItem["Editor"] = CurrentItem.Web.Site.SystemAccount.ID; //ModifiedBy
         }
        CurrentItem["Title"] = "Amit Kumar";
        CurrentItem.Update();
        CurrentItem.ParentList.Update();
        CurrentItem.Web.Update();
        CurrentItem.Web.AllowUnsafeUpdates = false;
        CurrentItem.Web.Site.AllowUnsafeUpdates = false;
        });
    }
public static void FindUserIDByNTID(string userNTID, SPSite site, ref int userID)
        {
          try
            {
              //--Check user NTID is null or not
              if (!string.IsNullOrEmpty(userNTID))
              {
               //--userNTID is not null
               //--then fetch ID of the user
               userID = site.RootWeb.AllUsers[userNTID].ID;
              }
              else
              {
               //--If userNTID is null
               userID = 0;
              }
          }
        catch (ArgumentException ex)
            {
              userID = 0;
            }
      catch (Exception ex)
      {
      userID = 0;
      }
     }
Share:

0 comments:

About Me

My photo
Based in Bangalore, INDIA, Amit is a MCC. He has an MCA from the U.P.T.U., INDIA and holds Microsoft certifications including SharePoint 2007/2010/2013. He is an contributor to MSDN and http://amitkumarmca04.blogspot.com/. Amit have experience in SharePoint,ASP.Net with C#, Classic ASP, VB,Macros,HTML,JavaScript,JSON,BootStrap and AngularJS.

Followers

Labels