How to reassign event handler at runtime

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

My code assigns event handler at runtime:
/*ListView*/ lv.RetrieveVirtualItem += this.MyHandler;

This line can be executed several times with the same list box and different
handlers (to be exact, the same handler coming from different instances of an
object). It appears from debugging that each execution adds a handler
instead of overwriting it. As a result event causes the execution of all old
handlers as well as the new one.
Am I right? If yes, how can I remove the old handlers?
Gregory
 
Gregory,

You will have to hold a reference to the old handler, and then remove
it:

// Store this somewhere.
RetrieveVirtualItemEventHandler oldHandler = ...;

// When adding the event, remove the old handler.
lv.RetrieveVirtualItem -= oldHandler;

// Add the new handler.
lv.RetrieveVirtualItem += this.MyHandler;
 
Hi,

Gregory Khra said:
My code assigns event handler at runtime:
/*ListView*/ lv.RetrieveVirtualItem += this.MyHandler;

This line can be executed several times with the same list box and
different
handlers (to be exact, the same handler coming from different instances of
an
object). It appears from debugging that each execution adds a handler
instead of overwriting it. As a result event causes the execution of all
old
handlers as well as the new one.
Am I right?

Yes, that is the way it works.

You have to call lv.RetrieveVirtualItem -= this.MyHandler; to remove the
handler.
 
Back
Top