Rupesh
Rupesh

Reputation: 7906

Add/Remove handler to textbox

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?

Upvotes: 9

Views: 11239

Answers (4)

Piyey
Piyey

Reputation: 471

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.

Upvotes: 7

ColinE
ColinE

Reputation: 70160

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.

Upvotes: 4

Jason Down
Jason Down

Reputation: 22191

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.

Upvotes: 4

JohnIdol
JohnIdol

Reputation: 50137

To remove the event handler you should just do:

tb1.KeyDown -= TextBox_KeyDown;

Upvotes: 2

Related Questions