josef_skywalker josef_skywalker - 1 month ago 10
C# Question

Assign Keydown event to all textBoxes

I am trying to assign a keyDown event to all textBoxes in one form.

So far my code:

void listenTextBox_KeyDownEvent(Control control)
{
foreach (Control ctrl in control.Controls)
{
if (ctrl is TextBox)
{
TextBox tb = (TextBox)ctrl;
tb.KeyDown += new EventHandler(textBox_KeyDown);
}
else
{
listenTextBox_KeyDownEvent(ctrl);
}
}
}
void textBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
TextBox tb = (TextBox)sender;
MessageBox.Show("Great Enter was hit");
}

}


But I am running in an error which I don't understand:


No overload for 'textBox_KeyDown' matches delegate 'EventHandler'


Any advice?

Answer

Try to change

tb.KeyDown += new EventHandler(textBox_KeyDown);

for

tb.KeyDown += new KeyEventHandler(textBox_KeyDown);
Comments