如何将事件处理程序附加到SharePoint中的特定列表?

时间:2011-03-17 16:44:13

标签: sharepoint sharepoint-2007

我已经读过这个问题how to attach an event receiver to a custom list in sharepoint?,但我有疑问。

当我使用EventReceivers.Add方法附加我的事件接收器时,是否必须激活事件接收器功能,或者它是否足以安装它?

而且,如果必须安装,我应该在事件功能的elements.xml中使用什么ListTemplateId?

提前致谢

3 个答案:

答案 0 :(得分:1)

事件接收器是一个定义。该定义映射到程序集和类实例。使用列表模板时,以声明方式(指定listtemplateid)使用事件接收器关联功能。当您基于非唯一的列表类型附加到特定列表时,通常使用对象模型。例如,通过使用TemplateTypeID ='104',将与具有该模板类型的所有列表相关联。

使用对象模型可以识别特定实例,这样您就可以简单地创建关联。因此,如果您想将事件接收器部署为一个功能,您将拥有一个加载程序集的功能和一个功能接收器代码,它将通过对象模型为您创建关联。

希望这是有道理的。

答案 1 :(得分:1)

您只需要为事件接收器部署解决方案。这使得代码可以附加到列表中。

要将事件接收器附加到特定列表,请在控制台应用程序中使用以下代码:

using (SPSite site = new SPSite(url))
{
    using (SPWeb siteWeb = site.OpenWeb())
    {
         SPList list = siteWeb.Lists["TheList"];

         SPEventReceiverDefinition defItemAdding = list.EventReceivers.Add();

         defItemAdding.Assembly = "MyEventHandlerProject, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=placeTokenHere";
         defItemAdding.Class = "MyEventHandlerProject.ClassName";
         defItemAdding.Name = "ItemAdding Event";
         defItemAdding.Type = SPEventReceiverType.ItemAdding;
         defItemAdding.SequenceNumber = 1000;
         defItemAdding.Synchronization = SPEventReceiverSynchronization.Synchronous;

         defItemAdding.Update();

}        }

你已经完成了!

答案 2 :(得分:0)

您可以创建一个控制台应用程序,将事件处理程序附加到Sharepoint列表。检查以下链接以获取示例控制台应用程序的代码。

http://ceprogrammingnotebook.blogspot.sg/2013/10/attaching-event-handler-to-sharepoint.html