2011-11-26 66 views
0

我有一系列嵌套TableLayoutPanel控件,其中每個控件都包含大量TextBox控件。檢測嵌套TableLayoutPanel內的所有文本框的按鍵事件

我覺得爲每個文本框做一個按鍵事件是瘋狂的,所以我想要做的是有一個公共事件方法,然後將事件應用於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和所有其他佈局面板裏面,本身就是一系列PanelSplitContainer和內....我需要點這在我的循環?
  • 或者我遞歸地遍歷主佈局面板中的每個佈局面板?
  • 或者整個想法是錯誤的?!!?

謝謝。

回答

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

而且調用此方法 TableLayoutPanel中