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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With