Thursday, 12 April 2012

How to Apply Unique value Constraint in Person and Group column in Sharepoint 2010

Recently an issue was reported to me where one of the site admin was unable to apply uniqueness in a column of type Person or Group in a list. When he was trying to create a column of that kind he was getting a screen like this:

In the above screenshot there is no possibility to enforce uniqueness. Hence the next approach was to do this pro grammatically. In case of Sharepoint 2007 this would have required creating an event receiver or workflow that could have checked uniqueness . However in case of Sharepoint 2010 a property "EnforceUniqueValues" on SPField that can be marked as true and it will work out. However we need to be sure that there should not be any existing values in the list violating this constraint or else this will fail. We also need to be sure that this should get applied only on indexed column. Hence I have ensured this in the code itself.

Here is the code for this:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Microsoft.SharePoint;

namespace EnforceUniqueness


class Program


static void Main(string[] args)




Console.WriteLine("This tool will apply unique value constratint to a column in a list. Make sure that your list does not contain duplicate values in this column");


Console.WriteLine("Enter the URL of Your Site");

String siteUrl = Console.ReadLine();

Console.WriteLine("Enter the Name of List name");

String listName = Console.ReadLine();

Console.WriteLine("Enter the Column Name");

String columnName = Console.ReadLine();

using (SPSite site = new SPSite(siteUrl))


SPWeb web = site.OpenWeb();

SPList list = web.Lists[listName];

SPField field = list.Fields[columnName];

field.Indexed = true;

field.EnforceUniqueValues = true;


Console.WriteLine("Tool Executed successfully. Press Enter to Terminate");




catch (Exception e)


Console.WriteLine(e.Message + "\n"+ e.StackTrace);






The execution will follow in this way:

I hope this will help you out.

Rahul Rashu

No comments:

Post a Comment