How to reassign event handler at runtime

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
 
N

Nicholas Paldino [.NET/C# MVP]

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;
 
I

Ignacio Machin \( .NET/ C# MVP \)

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top