I have a lot of TextBoxes in my single winform application. I am looking for a way to bind a single event method to all those textboxes when the form loads or in its constructor, so I dont add the event to every single textbox in designer.
In the event, I want to detect the ENTER key and then programmatically click on a button:
private void ApplyFilterOnEnterKey(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
btnApplyFilters_Click(this, null);
}
}
Now the problem is how can I loop over all textboxes in my form and bind them to the above method? My textboxes are everywhere, inside nested tablelayoutpanels or nested normal pannels. How this loop will look like and where should I put it? In form constructor or in load event?!
Instead of subscribing to every TextBox's KeyDown event, you have two other options that I think are better:
Set your button as the default button of the form by setting AcceptButton
property of the form to the button you want to be clicked by pressing Enter key.
Override ProcessDialogKey on your form and check for pressing the Enter key:
protected override bool ProcessDialogKey(Keys keyData)
{
if (keyData == Keys.Enter)
{
// ... do what you want
return true;
}
else
return base.ProcessDialogKey(keyData);
}