Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 871
Rupesh Avatar asked Dec 28 '11 15:12

Rupesh


People also ask

How you can add an event handler?

Right-click the control for which you want to handle the notification event. On the shortcut menu, choose Add Event Handler to display the Event Handler Wizard. Select the event in the Message type box to add to the class selected in the Class list box.

What is the difference between an event handler and an event listener?

Note: Event handlers are sometimes called event listeners — they are pretty much interchangeable for our purposes, although strictly speaking, they work together. The listener listens out for the event happening, and the handler is the code that is run in response to it happening.


3 Answers

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.

like image 152
Piyey Avatar answered Nov 15 '22 16:11

Piyey


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.

like image 44
Jason Down Avatar answered Nov 15 '22 16:11

Jason Down


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.

like image 27
ColinE Avatar answered Nov 15 '22 16:11

ColinE