Thursday, June 2, 2011

Prevent duplicate item in a SharePoint List

The following Event Handler code will prevent users from creating duplicate value in  "Title" field.

ItemAdding Event Handler

 public override void ItemAdding(SPItemEventProperties properties)
        {
            base.ItemAdding(properties);
            if (properties.ListTitle.Equals("My List"))
            {
                try
                {
                    using(SPSite thisSite = new SPSite(properties.WebUrl))
                    {
                        SPWeb thisWeb = thisSite.OpenWeb();
                        SPList list = thisWeb.Lists[properties.ListId];
                        SPQuery query = new SPQuery();
                        query.Query = @"<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + properties.AfterProperties["Title"] + "</Value></Eq></Where>";
                        SPListItemCollection listItem = list.GetItems(query);
                        if (listItem.Count > 0)
                        {
                            properties.Cancel = true;
                            properties.ErrorMessage = "Item with this Name already exists. Please create a unique Name.";
                        }
                    }
                }
                catch (Exception ex)
                {
                    PortalLog.LogString("Error occured in event ItemAdding(SPItemEventProperties properties)() @ AAA.BBB.PreventDuplicateItem class. Exception Message:" + ex.Message.ToString());
                    throw new SPException("An error occured while processing the My List Feature. Please contact your Portal Administrator");
                }
            }
        }


Feature.xml


<?xml version="1.0" encoding="utf-8"?>
<Feature  Id="1c2100ca-bad5-41f5-9707-7bf4edc08383"
          Title="Prevents Duplicate Item"
          Description="Prevents duplicate Name in the "My List" List"
          Version="12.0.0.0"
          Hidden="FALSE"
          Scope="Web"
          DefaultResourceFile="core"
          xmlns="http://schemas.microsoft.com/sharepoint/">
  <ElementManifests>
    <ElementManifest Location="elements.xml"/>
  </ElementManifests>
</Feature>

Element.xml


<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Receivers ListTemplateId="100">
    <Receiver>
      <Name>AddingEventHandler</Name>
      <Type>ItemAdding</Type>
      <SequenceNumber>10000</SequenceNumber>
      <Assembly>AAA.BBB, Version=1.0.0.0, Culture=neutral, PublicKeyToken=8003cf0cbff32406</Assembly>
      <Class>AAA.BBB.PreventDuplicateItem</Class>
      <Data></Data>
      <Filter></Filter>
    </Receiver>
  </Receivers>
</Elements>

The source code of this feature is available at Technet Gallery

10 comments:

  1. Hi!

    I have a problem that i think the mencioned above is the answer. When someone tries to enter an item with the same title field that order it returns the message (when clicking OK) "This value already exists in the list" but so far so good beacuse i have that restrition.
    The wierd thing is that the ID field jumps ahead one or more (as many times as you click OK) numbers.

    Does this solutions solves this? If yes how can i implement this?

    Thank you very much in advance :)

    André

    ReplyDelete
  2. I've not tested that, but I guess since we are using ItemAdding event the ID field should not add up.

    ReplyDelete
  3. Hi Prasath C!

    Can you please tell me how do I implement that? I need some help with that.

    Thank you

    André

    ReplyDelete
  4. I've tested this code and the ID field is not adding up on every click of OK button. You can try to implement this code in your site and test.

    ReplyDelete
  5. Yes I can test that in my test site, but i don't know how. Can you help me? I sent you an email earlier.

    Thank you

    André

    ReplyDelete
  6. Hi there. First off, great tutorial :)

    My question is how would you handle if there where two columns that needed to be unique?
    Example: A booking system that cant double book a date and time. Column "Time" and Column "Date" togetter cant be added if the combination already exsists.

    ReplyDelete
    Replies
    1. Just try to add another condition with < ADD> clause in the CAML Query
      query.Query = @"< Where>< AND >< Eq>< FieldRef Name='Date' />< Value Type='DateTime'>" + properties.AfterProperties["Date"] + "< /Value>< /Eq>< Eq>< FieldRef Name='Time' />< Value Type='Text'>" + properties.AfterProperties["Time"] + "< /Value>< /Eq>< /AND>< /Where>";

      Delete
  7. Thanks...
    but how to use Feature.xml and Element.xml?

    ReplyDelete
    Replies
    1. You can deploy the feature using STSADM. Refer to the following posts for more information
      http://www.objspsite.com/2011/05/deploying-sharepoint-event-handler.html
      http://blog.sharedove.com/adisjugo/index.php/2009/03/12/develop-and-deploy-a-sharepoint-event-receiver-from-the-scratch/

      Delete
    2. i need to chck the status column for active for only one item others they have to select inactive how to achieve this

      Delete