通常注册事件处理程序有三种方式:
- 通过部署 feature,以 XML 声明方式注册到指定列表模板
- 通过部署 feature,以 XML 声明方式注册到指定内容模型
- 通过编程,访问 SPList/SPWeb.EventReceivers 属性的 Add 方法动态注册
这里展示第三种方法。
如何注册
private void button1_Click(object sender, EventArgs e)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite("网站名称"))
{
using (SPWeb web = site.RootWeb)
{
SPList list = web.Lists["列表名称"];
string asmName = "CallCenterEvent, Version=1.0.0.0, Culture=neutral, PublicKeyToken= ae8dab1f1ede53e5";//程序集名称
string className = "CallCenterEvent.CallCenterEvent";//程序集中的类名
list.EventReceivers.Add(SPEventReceiverType.ItemAdded, asmName, className);
MessageBox.Show("OK");
}
}
});
}
如何取消
private void button2_Click(object sender, EventArgs e)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite("网站地址"))
{
using (SPWeb web = site.RootWeb)
{
SPList list = web.Lists["列表名称"];
string asmName = "CallCenterUnitEvent, Version=1.0.0.0, Culture=neutral, PublicKeyToken= c7869734ebdef00e";//程序集名称
string className = "CallCenterUnitEvent.CallCenterUnitEvent";//程序集中的类名
/*list.EventReceivers.Add(SPEventReceiverType.ItemUpdating, asmName, className);*/
SPEventReceiverDefinitionCollection eventReceivers = list.EventReceivers;
for (int i = 0; i < eventReceivers.Count; ) // can not use foreach due to the modification to the collection
{
SPEventReceiverDefinition def = eventReceivers[i];
if (def.Assembly == asmName && def.Class == className)
{
def.Delete();
}
else
{
i++;
}
}
MessageBox.Show("OK");
}
}
});
}
当然,包含 EventHandler 的程序集(示例中是 ForProgramDeployEventReceiver)必须以部署到 GAC。
每种 event type 都需要单独注册一次。