Item event receivers are similar to triggers existing in databases. They are executed on certain moments(events) on a SharePoint lists, libraries etc. Thanks to the events You can control Your items content, perform necessary validation before commiting any changes to the item.

There are many types ov event receivers, but the most popular are:

  • ItemAdding – fired before new item is added
  • ItemAdded – fired after new item is added
  • ItemUpdating – fired before existing item is updated
  • ItemUpdated – fired after existing item is updated
  • ItemDeleting – fired before existing item is deleted
  • ItemDeleted – fired after existing item is deleted

Below You can find the code used to create a class with will handle ItemAdding event:

public class OnItemAdding : SPItemEventReceiver//You have to inherit from SPItemEventReceiver class
    {
        public override void ItemAdding(SPItemEventProperties properties)
        {
            try
            {
               this.DisableEventFiring();//Disable any other events while our event is beeing executed

                base.ItemAdding(properties);//Call base class event

                //Perform some actions, f.e. check if the Title colomn is not empty
                if(String.IsNullOrEmpty(properties.AfterProperties["Title"] + String.Empty))
                {
                   throw new ApplicationException("Field 'Title' should not be empty");
}
                else
                {
                   //Field is not empty
                   properties.Cancel = false;//We do not want to cancel the event
                   properties.Status = SPEventReceiverStatus.Continue;//We want to continue the process
                   properties.ErrorMessage = String.Empty;//There is no error message
                }
            }
            catch (Exception ex)
            {
                //Exception occurred
                properties.Cancel = true;//We cancel the event
                properties.Status = SPEventReceiverStatus.CancelWithError;//Set appropriate status
                properties.ErrorMessage = ex.Message;//Set the error message
            }
            finally
            {
                this.EnableEventFiring();//Regardless if the exception occurred or not, we have to enable earlier disabled events
            }
        }
    }

With the class like that we can add out event receiver to the list using the code:

SPList list = GetElevatedList(listId);//We have to get the list in the elevated mode to be sure that we have the needed permissions. We can do that using the SPSecurity.RunWithElevatedPrivileges described in some previous post

string assemblyQualifiedName = "MyApp.Forms, version=1.0.0.0, culture=neutral, PublicKeyToken=xxxxxxxxxxxxxxxxA";//You can use System.Reflection.Assembly.GetExecutingAssembly().FullName
string receiverClass = "MyApp.Forms.EventReceivers.OnItemAdding"//Namespace.ClassName
SPEventReceiverType receiverType = SPEventReceiverType.ItemAdding;

SPEventReceiverDefinition eRecv = list.EventReceivers.OfType<SPEventReceiverDefinition>().Where(recv => recv.Class == receiverClass).FirstOrDefault();

if (eRecv == null)
{
    bool allowUnsafeUpdates = list.ParentWeb.AllowUnsafeUpdates;
    list.ParentWeb.AllowUnsafeUpdates = true;
    list.EventReceivers.Add(receiverType, assemblyQualifiedName, receiverClass);
    list.ParentWeb.AllowUnsafeUpdates = allowUnsafeUpdates;
}

To disable added receiver:

SPList list = GetElevatedList(listId);

string receiverClass = "MyApp.Forms.EventReceivers.OnItemAdding"//Namespace.ClassName

SPEventReceiverDefinition eRecv = list.EventReceivers.OfType<SPEventReceiverDefinition>().Where(recv => recv.Class == receiverClass).FirstOrDefault();

if (eRecv != null)
{
    bool allowUnsafeUpdates = list.ParentWeb.AllowUnsafeUpdates;
    list.ParentWeb.AllowUnsafeUpdates = true;
    eRecv.Delete();
    list.ParentWeb.AllowUnsafeUpdates = allowUnsafeUpdates;
}

The most important thing You have to remember about is to not use the SPContext.Current property, becasue the current context in event receivers is always equal to null. If You need a SPWeb object You can use:

properties.OpenWeb();