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!";
}
}
Showing posts with label ItemAdding in Eventhandler. Show all posts
Showing posts with label ItemAdding in Eventhandler. Show all posts
Monday, June 22, 2009
How to access fields of List Item in ItemAdding and ItemUpdating event handlers into SharePoint
Labels:
Event handler types,
eventhandler,
How to access fields of List Item in ItemAdding and ItemUpdating event handlers into SharePoint,
ItemAdding and ItemUpdating,
ItemAdding and ItemUpdating in eventhandler,
ItemAdding in Eventhandler,
ItemUpdating in Eventhandler,
MOSS 2007,
Sharepoint,
Sharepoint Event Handler Example,
SharePoint event handlers,
Sharepoint Event Hanlder,
Sharepoint Event Hanlder Types,
sharepoint eventhandler,
SPItemEventProperties,
Synchronous Event Handler in sharepoint,
Synchronous Event Hanlders in Sharepoint With ItemAdding and ItemUpdating,
Synchronous EventHandler in sharepoint
Subscribe to:
Posts (Atom)