Dumbo
Dumbo

Reputation: 14132

detect keypress event for all textboxes inside a nested TableLayoutPanel

I have a series of nested TableLayoutPanelcontrols which each of them contains lots of TextBox controls.

I think it is insane to make a keypress event for each of the textboxes, So what I am trying to do is to have a common event method and then apply the event for all textboxes on FormLoad event. What I want to do is to see if the user has pressed Enter key in any of those textboxes.

This is my common method (I hope nothing is wrong with it!):

private void ApplyFiltersOnEnterKey(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)13)
    {
        tsApplyFilters_Click(this, null);
    }
}

And I have the following code in Load event of my form:

    //Applying common event for all textboxes in filter options!
foreach (var control in tableCriterias.Controls)
{
    var textBox = control as TextBox;
    if (textBox != null)
        textBox.KeyPress += new KeyPressEventHandler(this.ApplyFiltersOnEnterKey);
} 

Well, maybe you can guess already, the codes above does not work! I can list the problems I can think of:

Thanks.

Upvotes: 0

Views: 1714

Answers (1)

Reza ArabQaeni
Reza ArabQaeni

Reputation: 4908

private void Recursive(TableLayoutPanel tableCriterias)
{
    foreach (var control in tableCriterias.Controls)
    {
        var textBox = control as TextBox;
        if (textBox != null)
            textBox.KeyPress += new KeyPressEventHandler(this.ApplyFiltersOnEnterKey);
        else if(control is TableLayoutPanel)
            Recursive(control as TableLayoutPanel);
    } 
}

And call this method for parent TableLayoutPanel

Upvotes: 2

Related Questions