Custom Event Receiver in SharePoint

What is Event Receiver in SharePoint? By creating event receivers, you can respond when a user interacts with SharePoint objects such as lists or list items.

Feature receivers provide developers with an opportunity to execute code as a feature goes through different stages. The following is the list of feature event receivers:


  • FeatureActivated 
  • FeatureDeactivating  
  • FeatureInstalled 
  • FeatureUninstalling 
  • FeatureUpgrading


Two types of event-

Synchronous events (also known as before events) are triggered as a result of actions that are performed against SharePoint objects like SPSite, SPWeb, SPList, SPContentType, etc.

Asynchronous Events (also known as after events) are triggered for SharePoint objects like SPSite, SPWeb, SPList, SPContentType, etc.


 public override void ItemAdded(SPItemEventProperties properties)
        {
            //base.ItemAdded(properties);

            SPList announcementsList = properties.Web.GetList("/Lists/Announcements") as SPList;
            if (null != announcementsList)
            {
                SPListItem contactItem = properties.ListItem; SPListItem newItem = announcementsList.Items.Add();
                newItem[SPBuiltInFieldId.Title] = string.Format("Please welcome {0} in group, you can reach {1} at {2}", contactItem["FullName"], contactItem["FirstName"], contactItem["Email"]);
                newItem.Update();
            }
        }


Elements.xml:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Receivers ListUrl="/Lists/Employees"> 
      <Receiver>
        <Name>EventReceiver1ItemAdded</Name>
        <Type>ItemAdded</Type>
        <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
        <Class>ContactListEventReceiver.EventReceiver1.EventReceiver1</Class>
        <SequenceNumber>10000</SequenceNumber>
      </Receiver>

  </Receivers>
</Elements>

Before deployment create a contact list and name it "Employees".
After successful deployment, add item to Employee List. Once item added check Announcement List and you will see a new announcement.

To get data property in event Receiver:
string data = properties.ReceiverData;

Comments

Popular