An event handler can be removed with the following code in the button click event.
Button btn = new Button();
this.Controls.Add(btn);
btn.Click += (o, x) =>
{
Button b = o as Button;
FieldInfo eventclick = typeof(Control).GetField("EventClick", BindingFlags.Static | BindingFlags.NonPublic);
object eventValue = eventclick.GetValue(b);
PropertyInfo events = b.GetType().GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);
EventHandlerList eventHandlerList = (EventHandlerList)events.GetValue(b, null);
eventHandlerList .RemoveHandler(eventValue, eventHandlerList [eventValue]);
MessageBox.Show("Test");
};
But I want to remove the event handler from the vgridcontrols CellValueChanged event. What do I have to write for “EventClick” in the following?
FieldInfo eventclick = typeof(Control).GetField(
"EventClick",
BindingFlags.Static | BindingFlags.NonPublic);
You cannot reliably remove an event handler from an event unless you already have an “equal” delegate you can use with
-=in the normal way.Getting fields with reflection and hacking around at them is a clear violation of encapsulation and makes your code extremely fragile. I would strongly recommend against doing it.
It’s not clear what you mean by “vgridcontrols” (
DataGridView?) but whatever solution you come up with is bound to be implementation-specific – and that implementation could easily change with the next version of whatever it is.Instead, put time into coming up with a design where either you don’t need to remove the event handler at all, or you keep a reference to the handler and can remove it in the normal way.