In this post we will discuss about how to create an event handler to prevent items from deleting item from SharePoint list using Visual Studio 2010. Also you can check my previous posts on:
Follow below steps:
- Open Microsoft Visual Studio 2010 and then go to File -> New -> Project.
- Then from the New Project dialog box, From Visual C# template, Select SharePoint and then 2010 and from there select Event Receiver project template, then give a name DeleteEventReceiver and click on OK as shown in the fig below.
- Then in the SharePoint Customization Wizard, Give a local deployment URL and choose Deploy as a sandboxed solution. Click Next.
- Then in the Next dialog box Choose Event Receivers Settings.
Select List Item Events in What type of event receiver do you want.
Then Select the List name in the What item should be the event source? dropdown. You can select the Task list or Announcement list etc.
Choose the An item is being deleted option in the Handle the following events list. Click Finish as shown in the fig below:
Then it will open the visual studio EventReceiver1 class file. Then override the ItemDeleting event handler.
public override void ItemDeleting(SPItemEventProperties properties)
properties.Status = SPEventReceiverStatus.CancelWithError;
properties.ErrorMessage = "You could not delete the list item !!!";
The full code will look like below:
Now deploy the solution and try to delete an item from the Task list it will show the error as shown in the fig below: