Friday, April 26, 2013

Event receiver for specific list


Introduction

In this post we will see how we can attach event receiver for specific list in SharePoint 2010.
In general coders tend to write event receiver which is global for all the lists. In the event receiver code they will compare with the list name and then provide specific functionality.
In this post we will see the better practice and simple way how to set the event receiver(ex: ItemAdding event) only for a particular list

 

Event Receiver


Open Visual Studio 2010, select File > New > Project.
Select Event Receiver template under SharePoint > 2010
image

Provide the site url and select deploy as form solution and click Next button
image

Select List Item Events under type of the event receiver. Select Custom List and check the events we want to trigger.
image

Once finished, go to the solution explorer and see the the elements.xml.
image
ListTemplateId=”100″ is the main value that attaches event receiver to any custom list.
Change the  ListTemplateId to ListUrl like the following and deploy the solution
ListUrl=”Lists/MyCustomList”
MyCustomList is the name of the custom list which I have created in my site. Now the Item Adding event receiver will be triggered only for the custom list MyCustomList but not to all the lists.
You can test the triggered event by attaching the debugger to see the event is fired only for that list.

Conclusion

In this way we can attach any event receiver for a specific list. Small change in the elements.xml file makes a better coding.