Pages

Showing posts with label ItemAdding and ItemUpdating in eventhandler. Show all posts
Showing posts with label ItemAdding and ItemUpdating in eventhandler. Show all posts

Monday, June 22, 2009

How to access fields of List Item in ItemAdding and ItemUpdating event handlers into SharePoint

When we need to validate something or put restriction before adding or modifying data, at that time we need to use ItemAdding or ItemUpdating Event Handler, here I’ll demonstrate how to access fields of List into event handlers.

Example:

As per my requirements, I don’t want to add duplicate Name into List. For this I need to check that condition before I add and update item to List, I need to use “ItemAdding” and “ItemUpdating” event handlers

public override void ItemAdding(SPItemEventProperties properties)
{
string strName = string.Empty;

foreach (DictionaryEntry entry in properties.AfterProperties)
{
if (entry.Key.Equals("Name"))
{
strName = entry.Value.ToString();
}
}

SPList list = properties.OpenWeb().Lists[properties.ListId];
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='" + list.Fields["Name"].InternalName + "' /><Value Type='Text'>" + strName + "</Value></Eq></Where>";
if (list.GetItems(query).Count > 0)
{
properties.Cancel = true;
properties.ErrorMessage ="Name already exists!";
}
}
public override void ItemUpdating(SPItemEventProperties properties)
{
string strName = string.Empty;
foreach (DictionaryEntry entry in properties.AfterProperties)
{
if (entry.Key.Equals("Name"))
{
strName = entry.Value.ToString();
}
}
SPList list = properties.OpenWeb().Lists[properties.ListId];
SPQuery query = new SPQuery();
query.Query=  "<Where><And><Neq><FieldRef Name='"+ list.Fields["ID"].InternalName+ "' /><Value Type='Number'>"+ properties.ListItemId+  "</Value></Neq><Eq><FieldRef Name='"+ list.Fields["Name"].InternalName+ "' /><Value Type='Text'>"+ strName+ "</Value></Eq></And></Where>" ;
if (list.GetItems(query).Count > 0)
{
properties.Cancel=true;
properties.ErrorMessage ="Name already exists!";
}
}