2013-04-07 13 views
1

改變文本框的背景色我有我的表格如下代碼:入境時

private void txt1_Enter(object sender, EventArgs e) 
    { 
     txt1.SelectAll(); 
     txt1.BackColor = Color.LightBlue; 
    } 

    private void txt2_Enter(object sender, EventArgs e) 
    { 
     txt2.SelectAll(); 
     txt2.BackColor = Color.LightBlue;    
    } 

    private void txt1_Leave(object sender, EventArgs e) 
    { 
     txtThermalConductivity.BackColor = Color.White; 
    } 

    private void txt2_Leave(object sender, EventArgs e) 
    { 
     txtThermalConductivity.BackColor = Color.White; 
    } 

有我的窗體上的另一個20個文本框,我想這樣做的一樣。是否有可能將所有進入事件和所有離開事件組合起來,因此我總共有兩個事件而不是44個單獨事件?

回答

1

在您的設計器視圖中,選擇每個文本框並將EnterLeave事件指向每個文件的單個實現。

然後,你可以這樣做:

private void txt_enter(object sender, EventArgs e) { 
    ((TextBox)sender).BackColor = Color.LightBlue; 
} 

private void txt_leave(object sender, EventArgs e) { 
    ((TextBox)sender).BackColor = Color.White; 
} 

而且,不需要SelectAll因爲你設置..不是SelectionColor一個RichTextBox的整個文本框的背景色。

+0

非常感謝! 'SelectAll'用於在輸入每個文本框時選擇所有文本,從而更快地更改輸入。 – Harry 2013-04-07 23:16:07

+0

@哈利噢好吧:) – 2013-04-07 23:16:31

0

是什麼,只要使用類似以下內容:

private void tbLeave(object sender, EventArgs e) { 
((TextBox) sender).BackColor = Color.White; 
} 

的設置控件事件聲明指向此功能。

您也可以爲Leave()事件做同樣的事情。

(只是一個小紙條說,我更喜歡來處理這種事情的客戶端在可能的情況。)

+0

OP沒有聲明這是一個網頁表單。 – 2013-04-07 23:10:34

0

你可以手動添加或遍歷所有文本框的形式(擴展方法在這裏找到GetChildControls

foreach (TextBox textBox in this.GetChildControls<TextBox>()) 
{ 
    textBox.Enter += new EventHandler(TextBox_Enter); 
    textBox.Leave += new EventHandler(TextBox_Leave); 
} 

以上可以從窗體的Load事件中調用。

現在的事件監聽器能像鑄造發件人文本框下面。

private void TextBox_Enter(object sender, EventArgs e) 
{ 
    TextBox txtBox = (TextBox)sender; 
    txtBox .SelectAll(); 
    txtBox .BackColor = Color.LightBlue;    
} 

private void TextBox_Leave(object sender, EventArgs e) 
{ 
    TextBox txtBox = (TextBox)sender; 
    txtBox.BackColor = Color.White; 
}