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 override void ItemAdded(SPItemEventProperties properties) { properties.ListItem["Patient Name"] = "Scott Brown"; properties.ListItem.Update(); base.ItemAdded(properties); }
- 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.
No comments:
Post a Comment