Adding and removing eventhandlers

D

Dom

In a datagridview, I sometimes capture the EditBoxShowing event and
then do the following:

TextBox txtEditControl = (TextBox)e.Control;
txtEditControl.KeyPress += new
KeyPressEventHandler(txtEditControl_KeyPress);
base.OnEditingControlShowing(e);

It occurs to be, though, that I just assume the system is creating a
new TextBox each time, one that does not have an eventhandler for the
KeyPress event. Am I just adding multiple eventhandlers to the same
control? If so, is there a way to get rid of them? I tried this ...

foreach (KeyPressEventHandler h in
txtEditControl.KeyPress) { txtEditControl.KeyPress -= h;}

.... but no go.

Dom
 
J

Jeff Johnson

In a datagridview, I sometimes capture the EditBoxShowing event and
then do the following:

TextBox txtEditControl = (TextBox)e.Control;
txtEditControl.KeyPress += new
KeyPressEventHandler(txtEditControl_KeyPress);
base.OnEditingControlShowing(e);

It occurs to be, though, that I just assume the system is creating a
new TextBox each time, one that does not have an eventhandler for the
KeyPress event.

No, you are setting txtEditControl to an EXISTING text box. No new control
is being created*. If the text box has already been wired to that event then
yes, you are creating multiple event handlers unless something in the
compiled code is checking for duplicates (and I have my doubts about that).


*Unless the grid control instantiates one on the fly and destroys it later.
Maybe it does.
 

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