I am using sp 2013 onpremise. I have some custom list with a custom column "VolgNummer". This is a text field. When I add a new item on this list this number needs to increase with 1. I enabled "unique enforced values" on this field. When I add an item as administrator everything is working fine. When another normal user try to add an item he gets an exception. It looks like the event receiver below generate an clientNumber which is existing. I translate the exception from dutch to english:
The listitem cannot added or edited because there are double values founded on column : [Volgnummer]
Here is the code I am using. Is there something wrong in my code, or do I need to do it another way?
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
// gets the last 2 characters of the year, for example: 14
string year = DateTime.Now.Year.ToString().Substring(2, 2);
SPField field = properties.List.Fields[new Guid(properties.Web.Properties[Constants.VOLGNUMMER])];
// get the last added item from the list
SPListItemCollection completedItems = properties.List.GetItems(new SPQuery()
{
Query = string.Format("<OrderBy><FieldRef Name='{1}' Ascending='FALSE' /></OrderBy><Where><BeginsWith><FieldRef Name='{1}' /><Value Type='Text'>{0}</Value></BeginsWith></Where>",
year, field.InternalName),
RowLimit = 1
});
// this number is for initial (first time) if there are no items existed in the list
string nextNumber = string.Format("{0}{1}",
year, "001");
if (completedItems.Count > 0)
{
// last added item volgnummer + 1
nextNumber = (int.Parse(completedItems[0][field.Id].ToString()) + 1).ToString();
}
properties.AfterProperties[field.InternalName] = nextNumber;
}