【问题标题】:detect keypress event for all textboxes inside a nested TableLayoutPanel检测嵌套 TableLayoutPanel 内所有文本框的按键事件
【发布时间】:2012-01-07 02:05:40
【问题描述】:

我有一系列嵌套的TableLayoutPanel控件,每个控件都包含很多TextBox控件。

我认为为每个文本框制作一个按键事件是很疯狂的,所以我想做的是有一个通用的事件方法,然后在FormLoad 事件上为所有文本框应用该事件。我想要做的是查看用户是否在这些文本框中按下了Enter 键。

这是我常用的方法(希望没有问题!):

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

我在表单的Load 事件中有以下代码:

    //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);
} 

好吧,也许您已经猜到了,上面的代码不起作用!我可以列出我能想到的问题:

  • tableCriterias 是父 TableLayoutPanel 和所有其他布局面板都在其中,它本身在一系列 Panel SplitContainer 和....我需要在我的循环中指出这个吗?
  • 或者我是否递归循环遍历主布局面板内的每个布局面板?
  • 还是整个想法都错了?!!?

谢谢。

【问题讨论】:

    标签: c# winforms events loops controls


    【解决方案1】:
    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);
        } 
    }
    

    并为parent TableLayoutPanel调用此方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多