Thursday, June 20, 2013

Event Receivers - Basics - Item Adding Example

Event Receivers are of two types, Before and After Events. Let me explain with an example, Consider you have a custom list "Employees" in your site which has columns 'Name','salary' and 'Hire Date'. You want to add a 1000$ bonus to employees hired before a year. So, you want to fire an event which basically adds 1000$ to their salary depending on hire date. Now we don't have 'hire date' in the database because it has not been committed yet. so, that is an after property.

Simple Event Receiver which adds 1000$ bonus based on 'Hire Date':
public override void ItemAdding(SPItemEventProperties properties)
        {
            int year = Convert.ToDateTime(properties.AfterProperties["Hire Date"]).Year;
            if (year < DateTime.Today.Year)
            {
                properties.AfterProperties["salary"] = Convert.ToDecimal(properties.AfterProperties["salary"]) + 100;

            }

        }


No comments:

Post a Comment