2013-08-30 37 views
0

我是新的C#我一直在瞎搞到到目前爲止,我已經寫了許多程序在我的追求,但現在我只能堅持一件事發現這種語言,我不能解釋話,但代碼可以說我想要什麼所以在這裏我們去,我知道這是愚蠢的程序,但它僅用於教育目的:dC#全球組件代碼

Private void change() 
     { 
anycontrol.BackColor = Color.Gold; // when this function called the control's BackColor will Change to gold 
     } 
// example 
private void TextBox1_Focused(object sender, EventArgs e) 
{ 
Change(); // this suppose to change the color of the controls which is now textbox1 i want it to work on other controls such as buttons progressbars etc 
} 

現在經過我解釋了我的問題,我可能會問你,如果你能幫助它會讚賞。

+0

不是最好的解釋... 你有什麼問題?你確定你打電話正確嗎? '改變'!='改變'。 C#區分大小寫 – wudzik

+0

我編輯過這個問題,是的,我調用了正確的函數。 – VoVb

+0

把你真正的代碼,因爲這將無法正常工作,嚴重的話,儘量調試,看看是否有異常看看是否有任何異常被拋出等 – wudzik

回答

3

您可以創建需要一個ControlColor作爲參數,從Control(即TextBoxDropDownListLabel等)繼承的方法,以及任何將與這方面的工作:

void SetControlBackgroundColour(Control control, Color colour) 
{ 
    if (control != null) 
    { 
     control.BackColor = colour; 
    } 
} 

在你例如,你可以使用這樣的:

private void TextBox1_Focused(object sender, EventArgs e) 
{ 
    SetControlBackgroundColour(sender as Control, Color.Gold); 
} 

在迴應的意見,然後你可以在將設置背景山坳遞歸方法使用此方法我們的表單上的每個控件:

void SetControlBackgroundColourRecursive(Control parentControl, Color colour) 
{ 
    if (parentControl != null) 
    { 
     foreach (Control childControl in parentControl.Controls) 
     { 
      SetControlBackgroundColour(childControl, colour); 

      SetControlBackgroundColourRecursive(childControl); 
     } 
    } 
} 

,然後在Form1_Load方法調用你Form對象(this)這個函數(假設形式被稱爲Form1):

protected void Form1_Load(object sender, EventArgs e) 
{ 
    SetControlBackgroundColourRecursive(this, Color.Gold); 
} 
+0

你的代碼半幫我,我還是要輸入控件的名稱,有沒有什麼方法可以獲取控件名稱並將其傳遞給ChangeBackgroundColour(Here,Color.Gold);而不是輸入控件名稱? – VoVb

+0

我剛剛把你需要的代碼用來使用'sender'參數。需要注意的是'as'可以產生'null',因此增加了對這種情況下,保護'ChangeBGColour' – weston

+0

感謝名單,現在 – VoVb