Can a eventhandler delegate remove itself from an event without knowing the event?

  • Thread starter Thread starter Torben
  • Start date Start date
T

Torben

For test purposes I attach an event to a control, say a TextBox
TextChanged event. At another time the same event delegate is attached
to some other control, maybe a listbox.

Same event function every where. The event function should happen only
once for that control (and then, maybe again if it is attached to the
control again).

Could I make that deattachment operation general? could the function
find out what event it is attaced? Something like


Event e = ????????;
Eventhandler ThisHandler = ????????;
e -= ThisHandler;

Any suggestions? Thanks in advance!
Best regards
Torben
 
Hi Torben,

Yes, you can deattach the event handler. Standard .NET events when triggered
pass the object that triggered the event as well in the sender parameter.
All you need to do is cast the sender as your control then deatach the event
handler. Check the code below:

private void button2_Click(object sender, System.EventArgs e)
{
Control ctrl = (Control) sender;
ctrl.Click -= new System.EventHandler(this.button2_Click);
}


hope this helps

Fitim Skenderi
 
Hi Fitim
Thank you very much for the answer. I like it, but it would be better if
I didn't have to know the type of event, since this code should work
very generally.

As in yout example:
ctrl.Click -= new System.EventHandler(this.button2_Click);

Here I need to know that the handler is attached to a Click event. What
if the control was a TextBox or something I don't know yet?

I just want to deattach from any event on the control

Best regards
Torben
 
Hi Torben,

To be honest I don't think you can do something like that. The delegates
(events) are just function pointers in a sense, and can have different
parameters. I think the only way for something "truly generic" is to user
Reflection and go through all event handlers and detach the code from the
ones you are interested.

Fitim Skenderi
 
Let's say that you have a common event handler delegate for more than one event. You can declare it separately (ex.):
System.EventHandler commonHandler;
commonHandler= new System.EventHandler(this.CommonHandler);

Associate it:
this.button1.Click += commonHandler;
this.button2.Click += commonHandler;


Remove it from all the controls:
foreach (Control innerControl in this.Controls)
{
System.Reflection.EventInfo[] evinfo = innerControl.GetType().GetEvents();
for (int index=0; index<evinfo.Length; index++)
{
evinfo[index].RemoveEventHandler(innerControl,commonHandler);
}
}
 
Back
Top