Quantcast
Channel: Bram Nuyts » Event
Viewing all articles
Browse latest Browse all 4

Prevent items from being deleted using an event receiver

$
0
0

One way to prevent item deletion is creating a custom permission level, where the item deletion permission is unchecked. When you use this method to prevent item deletion, you’ll have to break the permission inheritance of your list. Plus, you’ll create the permission level for the whole site collection. If that’s a problem you can also use an event receiver.

The following code snippet will prevent item deletion and also notify the user of what happened. If you simply use the properties.Cancel = true; property, then the item is prevented from deletion, but the user isn’t notified.

By setting the properties.Status = SPEventReceiverStatus.CancelWithError; property, we tell SharePoint to generate an error message. The properties.ErrorMessage = “This item cannot be deleted; Contact your administrator”; property defines the message the user sees.

/// <summary>
/// An item is being deleted.
/// </summary>
public override void ItemDeleting(SPItemEventProperties properties)
{
    base.ItemDeleting(properties);
    properties.Status = SPEventReceiverStatus.CancelWithError;
    properties.ErrorMessage = "This item cannot be deleted; Contact your administrator";
    properties.Cancel = true;
}

The above snippet generates the following error when a user tries to delete an item in a list where the event receiver is active:

error screenshot from event receiver



Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles





Latest Images