I was reading this nice article about basic event handling in sharepoint http://karinebosch.wordpress.com/walkthroughs/event-receivers-walkthrough1/ but while doing the exercise a question arised: Why should I call the column as "Title" both in the CAML query and the properties, even if I renamed it before to be called "Planet". If I use "Planet", the event does not fire the correct behavior (an error message).
Here is the piece of code:
public override void ItemAdding(SPItemEventProperties properties)
{
// get the name of the planet that needs to be saved
string planet = properties.AfterProperties["Title"].ToString();
using (SPWeb web = properties.OpenWeb())
{
// get the Planet list (will be queried for existing planet name)
SPList list = web.Lists[properties.ListId];
// build the query
SPQuery query = new SPQuery();
query.Query = string.Format("<Where><Eq><FieldRef Name=\"Title\" /><Value Type=\"Text\">{0}</Value></Eq></Where>", planet);
// execute the query
SPListItemCollection items = list.GetItems(query);
if (items != null && items.Count > 0)
{
properties.ErrorMessage = string.Format(
"The planet with the name {0} already exists.", planet);
properties.Status = SPEventReceiverStatus.CancelWithError;
properties.Cancel = true;
}
}
}
Also, what implications have using this code, not in a custom list but in a document library, where you have to upload the file first and then fill up the required metadata. Should the event handling method change in this case to validate metadata?