Add/Remove handler to textbox

2019-04-06 17:09发布

问题:

I am adding a handler to textbox using the following code:

private void frmLogin_Load(object sender, EventArgs e)
{
    foreach (Control tb in this.Controls)
    {
        if (tb is TextBox)
        {
            TextBox tb1 = (TextBox)tb;
            tb1.KeyDown += new KeyEventHandler(TextBox_KeyDown);
        }      
    }
}

I am also removing handler using the following code:

private void frmLogin_FormClosed(object sender, FormClosedEventArgs e)
{
    foreach (Control tb in this.Controls)
    {
        if (tb is TextBox)
        {
            TextBox tb1 = (TextBox)tb;
            tb1.KeyDown -= new KeyEventHandler(TextBox_KeyDown);
        }
    }
}

Is the correct way or is there a better alternative?

回答1:

It is good, but you dont need to remove the handler, and adding the handler just put this:

tb1.KeyDown += TextBox_KeyDown;

because new KeyEventHandler(TextBox_KeyDown); is redundant.



回答2:

Your approach is fine. In both the addition and removal of the event handler delegate, you can omit the new KeyEventHandler and surrounding parenthesis around TextBox_KeyDown. These are implied by the compiler (so long as the TextBox_KeyDown method has the expected signature). This is purely a matter of preference of course.



回答3:

Yes, that is entirely correct. However you can use the shorthand notation:

tb1.KeyDown -= TextBox_KeyDown;

Although the effect is exactly the same.

However, it is worth determining whether you really need to remove your event handler? What is the lifecycle of your form and the TextBox? if the form 'owns' the TexBox, i.e. it is longer lived, then you do not need to remove the event handler.



回答4:

To remove the event handler you should just do:

tb1.KeyDown -= TextBox_KeyDown;