2015-12-20 37 views
1

在我的形式,我有大約36個按鈕和每個我有下面的代碼變更最後按下按鈕屬性C#

 button3.BackColor = Color.DarkGreen; 
     button_click("A1"); 
     button3.Enabled = false; 
     nr_l++; 
     textBox4.Text = Convert.ToString(nr_l); 

這意味着我有這樣的代碼×36次,我想打個方法做到這一點,但我不知道如何改變最後點擊按鈕的特性,我想是這樣的:

private void change_properties() 
    { 
    last_clicked_button.backcolor = color.darkgreen; 
    button_click("A3"); //this is a method for adding A3 to a string, 
    last_clicked_button.enabled = false; 
    nr_l++; 
    textbox4.text = convert.tostring(nr_l); 
    } 

    private void button3_Click(object sender, EventArgs e) 
    { 
    change_properties(); 
    } 

我怎麼能告訴change_properties方法,它應該與BUTTON3工作的情況下,它被點擊?

+1

的'sender'變量有這個信息。例如:'按鈕curButton =(按鈕)發件人;如果(curButton.Name ==「button3」){//這是button3}'。您可以將相同的方法(例如,'private void button_Click(object sender,EventArgs e){}')關聯到所有按鈕的點擊事件,並以這種方式識別給定的按鈕。至少,這似乎是你最後一個問題的答案,因爲你的整個帖子都不太清楚。 – varocarbas

回答

1

您可以將按鈕作爲參數傳遞給方法 -

change_properties(Button lastClickedButton) 

然後用這個參數來完成你想要的。

1

如果你與你的36個按鈕做的是相同的,那麼對於每個Button.Clickevents的(可能在你的designer.cs文件中聲明),它是指一個event handler

this.button1.Click += new System.EventHandler(this.button_Click); //notice the event name is the same 
.... 
this.button2.Click += new System.EventHandler(this.button_Click); //notice the event name is the same 
.... 
this.button36.Click += new System.EventHandler(this.button_Click); //notice the event name is the same 

,然後在事件處理程序,通過使用as Button

private void button_Click(object sender, EventArgs e) 
{ 
    Button button = sender as Button; //button is your last clicked button 
    //do whatever you want with your button. This is necessarily the last clicked 
} 

如果它不是sender對象轉換爲Button類,然後就離開事件處理程序的聲明但讓button作爲輸入您change_properties方法

private void change_properties(Button button) 
{ 
    button.backcolor = color.darkgreen; 
    button_click("A3"); //this is a method for adding A3 to a string, 
    button.enabled = false; 
    nr_l++; 
    textbox4.text = convert.tostring(nr_l); 
} 

private void button1_Click(object sender, EventArgs e) //the name of the event handler is unique per `Button` Control 
{ 
    change_properties(sender as Button); 
    //do something else specific for button1 
} 

.... 

private void button36_Click(object sender, EventArgs e) 
{ 
    change_properties(sender as Button); 
    //do something else specific for button36 
}