Tuesday, May 10, 2011

How to create event receivers using Visual Studio 2010 in SharePoint 2010?

In this post we will discuss how to create an event receiver in SharePoint 2010?

Also you can check out:

- How to create an application page using Visual Studio 2010 for SharePoint 2010?

- Content Editor Web Part in SharePoint 2010

- JQuery reference in Application pages in SharePoint

We can create event receivers using Visual Studio 2010 in our SharePoint 2010 site. You can follow the below steps for the same.

Open Visual Studio 2010 -> File -> New Project -> Select SharePoint 2010 under Visual C# section. Then choose Event Receiver project template from the list of templates. Give a name for the project and click ok as shown in the figure below.

Then choose deploy as farm solution and give the URL for debugging in the drop down as shown below then
click on Next.

This step is very much important. Here first choose what type of receiver you want. Here I have added List Item Events.
Then select the event source and Here I have choose custom list.
Then choose what the events and I have selected Item Added and Item Updated Event. After selection the window should be look like the below figure.

Now you can write code for the events that you have selected in Step-3. Here I have only add a sample code for a ItemAdding event as below. This will cancel the operation with error message if the particular list title is not "Test".

Here is the code below:

public override void ItemAdding(SPItemEventProperties properties)
           if (properties.ListTitle != "Test")
               properties.Status = SPEventReceiverStatus.CancelWithError;
               properties.ErrorMessage = "You can only add to the Test List !!!";
               properties.Cancel = true;

You can also check how to attach event receiver to SharePoint list.