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

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

Hi,
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)
 
{
 
try
 
{
 
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("\n");
 
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;
 
field.Update();
 
Console.WriteLine("Tool Executed successfully. Press Enter to Terminate");
 
Console.ReadLine();
 
}
 
}
 
catch (Exception e)
 
{
 
Console.WriteLine(e.Message + "\n"+ e.StackTrace);
 
Console.ReadLine();
 
}
 
}
 
}
 
}

The execution will follow in this way:

Leave a Comment
  • Please add 4 and 2 and type the answer here:
  • Post
Wiki - Revision Comment List(Revision Comment)
Sort by: Published Date | Most Recent | Most Useful
Comments
  • Richard Mueller edited Revision 1. Comment: Removed tag "SPS 2010", added tag

Page 1 of 1 (1 items)
Wikis - Comment List
Sort by: Published Date | Most Recent | Most Useful
Posting comments is temporarily disabled until 10:00am PST on Saturday, December 14th. Thank you for your patience.
Comments
  • Richard Mueller edited Revision 1. Comment: Removed tag "SPS 2010", added tag

Page 1 of 1 (1 items)