How to Create an Event Handler to Force Unique in SharePoint?

Long back, I did an Event handler to prevent duplicates in a SharePoint list. There is a another requirement of same kind now. This time, Let me do it with WSP builder. Requirement is simple – Prevent duplicate titles from a List. Hmm.., But in SharePoint 2010 this is an instinct feature, we don’t need to do any event handlers.

Lets get started.

Create an Event handler for SharePoint 2007 with WSP Builder – Step by step:

Step 1:  Open the Visual studio, Create a New Project, Choose WSP Builder Project type

Create Event Handler for MOSS 2007 with WSP Builder

Step 2: Add a new item to the Project

create event handler moss 2007

Step 3: Choose Event Handler under WSP Builder node, Name it and click “Add”

sharepoint 2007 wspbuilder event handler

Step 4: In the Event Handler code, place this code:

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;

namespace PreventDuplicateEventHandler
{
    class PreventDuplicates : SPItemEventReceiver
    {
        public override void ItemAdding(SPItemEventProperties properties)
        {
            base.ItemAdding(properties);
              try
                {
                    using(SPSite oSPSite= new SPSite(properties.WebUrl))
                    {
                        SPWeb oSPWeb = oSPSite.OpenWeb();
                        SPList oSPList = oSPWeb.Lists[properties.ListId];

                        SPQuery oSPquery = new SPQuery();
                        oSPquery.Query = @"<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + properties.AfterProperties["Title"] + "</Value></Eq></Where>";
                        SPListItemCollection oListItemColl = oSPList.GetItems(oSPquery);
                        if (oListItemColl.Count > 0)
                        {
                            properties.Cancel = true;
                   properties.ErrorMessage = "There is already an item with the title " + properties.AfterProperties["Title"] + " in this list";
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.EventLog.WriteEntry("Error encountered in Event Handler", ex.Message);
            }

        }

    }
}

Step 5: Build the project, Build the WSP, Deploy the WSP.

Step 6: Navigate to the site, go to Site settings >> Site features >> and then activate “Prevent Duplicate” feature.

Activate Feature in Site Features

Step 7: Now, we have the feature ready. We have to associate the event handler with our List. To do that, there are a lot of tools available. Here is one of them: Download and run the executable. (By the way, You can write your own  code to register the event handler)

Step 8: Register the event handler to the desired list.

Event Handler Manager to Regiter Unregister Event Handler with SharePoint List or Library
Update:
Found a bug in the above tool! use the SharePoint Event Receiver Manager instead!!!

That’s all. We are done, See it in action!!

Force Unique in MOSS 2007 with event handler

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

6 thoughts on “How to Create an Event Handler to Force Unique in SharePoint?

  • I set properties.Cancel = true and properties.ErrorMessage = “Custom Validation Error Message” in the itemUpdating synchronous event receiver method. Instead of seeing the SharePoint error page, I am getting the IIS server error page with the full stack trace, etc. What am I missing?

    Reply
  • Really nice article!!

    But remember that SPQuery only works with up to 2000 items limit.
    Helpful links:

    https://msdn.microsoft.com/en-us/library/bb687949(v=office.12).aspx#UsingSPQueryObjs
    https://blogs.msdn.com/b/sowmyancs/archive/2008/10/26/best-practices-sharepoint-object-model-for-performance-tuning.aspx

    Thanks!

    Reply
  • Thanks for the walthrough. Could you please fix the link given in step# 7

    Reply
    • Thank you for your real quick response buddy!

      Reply
    • thanks fo helping me out

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *