2016-08-24 63 views
-1

我有很多TextBox控件。對於每個TextBox控件,我都會得到它們的text_Changed和key_Press事件。正因爲如此,我的Form.cs變得太擁擠。我的問題是,是否有可能讓這個空間更加自由?有些事件只包含一個功能。多個TextChanged和KeyPress事件

示例代碼:

private void txtItem_TextChanged(object sender, EventArgs e) 
{ 
    showButtonSave(); 
} 

private void txtItem_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    showButtonSave(); 
    char ch = e.KeyChar; 
    if (ch == (char)Keys.Enter) 
    e.Handled = true; 
} 

private void txtItem2_TextChanged(object sender, EventArgs e) 
{ 
    showButtonSave(); 
} 

private void txtItem2_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    showButtonSave(); 
    char ch = e.KeyChar; 
    if (ch == (char)Keys.Enter) 
    e.Handled = true; 
} 

回答

1

在您txtItem2你可以去它的屬性,有地方說,ontextchange你應該看到它被設置爲txtItem2_KeyPress變化,要txtItem_KeyPress那麼他們將都使用

private void txtItem_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    showButtonSave(); 
    char ch = e.KeyChar; 
    if (ch == (char)Keys.Enter) 
    e.Handled = true; 
} 
+0

這可能是最簡單的方法和回答我的問題。感謝此 –

+0

請記住,您的命名轉換並不適合此解決方案。因爲該方法說'txtItem'我會使它更通用。除此之外,還要記住,如果您在該方法中執行任何操作,則兩個按鈕都會立即執行代碼。你將能夠使用'sender(object)'來檢測按下哪個按鈕。 – Neil

+0

謝謝你告訴我那個先生。但我認爲這不會影響我想要的流量。但願如此。 –

1

您可以爲每種類型(txtItem_TextChanged/txtItem_KeyPress)創建一個事件,並將其映射到所有文本框。在sender的幫助下,您可以根據需要獲得實際的控制和操作。