Adding and removing eventhandlers

  • Thread starter Thread starter Dom
  • Start date Start date
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
 
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.
 
Back
Top