How to: Create an Event Receiver
By creating event receivers, you can respond when a user interacts with SharePoint items such as lists or list items. For example, the code in an event receiver can be triggered when a user changes the calendar or deletes a name from a contacts list. By following this topic, you can learn how to add an event receiver to a list instance.
To complete these steps, you must have installed Visual Studio and supported editions of Windows and SharePoint. For more information, see Requirements for Developing SharePoint Solutions. Because this example requires a SharePoint project, you also must have completed the procedure in the topic Walkthrough: Create a Site Column, Content Type, and List for SharePoint.
Adding an Event Receiver
The project that you created in Walkthrough: Create a Site Column, Content Type, and List for SharePoint includes custom site columns, a custom list, and a content type. In the following procedure, you’ll expand this project by adding a simple event handler (an event receiver) to a list instance to show how to handle events that occur in SharePoint items such as lists.
To add an event receiver to the list instance
Open the project that you created in Walkthrough: Create a Site Column, Content Type, and List for SharePoint.
In Solution Explorer, choose the SharePoint project node, which is named Clinic.
On the menu bar, choose Project, Add New Item.
Under either Visual C# or Visual Basic, expand the SharePoint node, and then choose the 2010 item.
In the Templates pane, choose Event Receiver, name it TestEventReceiver1, and then choose the OK button.
The SharePoint Customization Wizard appears.
In the What type of event receiver do you want? list, choose List Item Events.
In the What item should be the event source? list, choose Patients (Clinic\Patients).
In the Handle the following events list, select the check box next to An item was added, and then choose the Finish button.
The code file for the new event receiver contains a single method that’s named ItemAdded. In the next step, you’ll add code to this method so that every contact will be named Scott Brown by default.
Replace the existing ItemAdded method with the following code, and then choose the F5 key:
Public Overrides Sub ItemAdded(ByVal properties As SPItemEventProperties) properties.ListItem("Patient Name") = "Scott Brown" properties.ListItem.Update() MyBase.ItemAdded(properties) End Sub
public override void ItemAdded(SPItemEventProperties properties) { properties.ListItem["Patient Name"] = "Scott Brown"; properties.ListItem.Update(); base.ItemAdded(properties); }
The code runs, and the SharePoint site appears in the web browser.
On the QuickLaunch bar, choose the Patients link, and then choose the Add New Item link.
The entry form for new items opens.
Enter data in the fields, and then choose the Save button.
After you choose the Save button, the Patient Name column automatically updates to the name Scott Brown.