阻止GridView的RowDataBound事件响应
由于很多页面中有GridView控件,在某些情况下不想让RowDataBound事件进行事件响应,也就是阻止事件响应函数的执行,如果一个页面一个页面地去gridView.RowDataBound-=OnRowDataBound改动起来将非常麻烦。
还好这些页面都是MasterPage的嵌套页面,因此可以在MasterPage的cs文件中用FindControlRecursive找到GridView
/// <summary> /// 相当于FindControl,同时适用于Page和MasterPage /// </summary> /// <param name="root">开始查找点</param> /// <param name="id">要查找的控件ID</param> /// <returns></returns> public static Control FindControlRecursive(Control root, string id) { if (root.ID == id) return root; foreach (Control Ctl in root.Controls) { Control FoundCtl = FindControlRecursive(Ctl, id); if (FoundCtl != null) return FoundCtl; } return null; }
然后通过反射,找到继承自System.ComponentModel.Component的Events
protected EventHandlerList Events 方法是: Type t = gridView.GetType(); PropertyInfo piEvents = t.GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic);
|
要用EventHandlerList的public void RemoveHandler(object key, Delegate value);删除事件响应,
需要先找到key
FieldInfo fiEventKey = t.GetField("EventRowDataBound", BindingFlags.Static | BindingFlags.NonPublic);
取delegates
Delegate d = ehl[fiEventKey.GetValue(null)];
最后删除
if (d != null) { foreach (Delegate temp in d.GetInvocationList()) { ehl.RemoveHandler(fiEventKey.GetValue(null), temp); } }
完整的代码如下:
// 去掉GridView的RowDataBound事件响应 Type t = gridView.GetType(); PropertyInfo piEvents = t.GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic); EventHandlerList ehl = (EventHandlerList)piEvents.GetValue(gridView, null); FieldInfo fiEventKey = t.GetField("EventRowDataBound", BindingFlags.Static | BindingFlags.NonPublic); Delegate d = ehl[fiEventKey.GetValue(null)]; if (d != null) { foreach (Delegate temp in d.GetInvocationList()) { ehl.RemoveHandler(fiEventKey.GetValue(null), temp); } }