Event Receiver and Custom Error Page

In this example I am going to show you how to use list item event receiver and how to redirect users to error page if something goes wrong. We have a list of contacts and we want to display an error message if the entered zip code doesn't a specific value. For this example I am using zip code 98052. If user enters a different ZIP code we display a custom error page. For custom error page we are going to create an application page.

Start by creating a new Event Receiver project (I am using C# Event Receiver project). Because we are going to use an application page, select Deploy as farm solution. In the Event Receiver wizard, select List Item Events for the type of the event receiver. Event source is going to be Contacts and we are interested in "An item is being added" event.

Next, add an application page to the project and name it CustomErrorPage.aspx. Let’s modify the application page and add a Label control to display the error message. Your markup code should look something like this:

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server"> 
<asp:Label ID="lblError" runat="server"></asp:Label> 

<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server"> 
Error Page

<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
Error Page

I removed the Text attribute of the Label control because we are going to create the error message in the event receiver code and then pass the error message to the page. In order to display the error message on the ASPX page (Label control), we need to get that parameter somehow. Switch to the application page code view and add the following code to the Page_Load method:


protected void Page_Load(object sender, EventArgs e) 
        lblError.Text = Request.Params["Error"]; 


Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
     lblError.Text = Request.Params("Error")
End Sub

We are requesting the parameter called "Error" and then setting it to the Text property of lblError label control. Now that custom error page is created open the EventReceiver1.cs file and adds the following code to the ItemAdding method:


public override void ItemAdding(SPItemEventProperties properties) 
    string zipCode = properties.AfterProperties["WorkZip"].ToString(); 

    if (zipCode != "98052") 
        string errorMessage = string.Format ("ZIP Code '{0}' is Invalid!", zipCode); 
        properties.Cancel = true; 
        properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl; 
        properties.RedirectUrl = "/_layouts/EventReceiverProject1/CustomErrorPage.aspx?Error=" + errorMessage; 


Public Overrides Sub ItemAdding(properties as SPItemEventProperties)
        Dim zipCode As String = properties.AfterProperties("WorkZip").ToString()
        If zipCode <> "98052" Then
            Dim errorMessage As String = String.Format("Zip Code '{0}' Is Invalid!", zipCode)
            properties.Cancel = True
            properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl
            properties.RedirectUrl = "/_layouts/CustomErrorPage/CustomErrorPage.aspx?Error="  & errorMessage
        End If
 End Sub

In the above method we are getting the value of the ZIP code (WorkZip field) and then comparing it to 98052. If the zip code doesn't match we are setting the Cancel property of the SPItemEventReceiverProperties to true and cancelling the event. Because we want to display the custom error page we set the Status property to CancelWithRedirectUrl. You could also cancel the event without an error or even continue it. Last thing we need to do is to redirect the users to the custom error page we created before and pass the error message to the ASPX page.

Press F5 or deploy the project to verify the behavior. Start by creating a new Contacts list (click the List s link and the Create to create new Contacts list). Navigate to the created list, add a new contact and enter an 'invalid' zip code (in our case invalid zip code is anything that is different from string 98052). As you click Save to add the contact custom error page we created should be displayed.

Peter Jausovec

Comments (5)
  1. Naresh says:

    Hey, can we do the cancelwithredirecturl in MOSS 2007.. if can you suggest any workaround. i am dealing with itemdeleting event reciever..

    thanks much..

  2. Hi,

    Yes, you can cancel the ItemDeleting event and use the CancelWithRedirectUrl in MOSS 2007. However, there’s no project template you could use in Visual Studio. You will have to create a class that derives from SPItemEventReceiver(http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spitemeventreceiver(v=office.12).aspx) and then register the event receiver in the feature manifest (http://msdn.microsoft.com/en-us/library/bb802822(v=office.12).aspx).


  3. Naresh says:

    Thanks peter,

    I have used the class derived from ‘SPItemEventReciever’ and registerd with a console application. and while coding,i do not see the "CancelWithRedirectUrl" in the inteliigence and the only properties that i see are "CacelNoerror,CacelWithError,Continue". am i missing anything.. appriciate your help.. thanks.


  4. Naresh,

    You are right actually. The CancelWithRedirectUrl is new in SharePoint 2010. But for previous versions of SharePoint you could still use CancelNoError for example and then use SPUtility.Redirect method to redirect users to your custom error page.

  5. Greg says:

    Do you know why the redirect wouldn't work with a list that has the NewItem form customized by InfoPath?

Comments are closed.

Skip to main content