2012-11-18 15 views
1

我們來看看下面的代碼,我在其中創建一個按鈕列表。如何管理在運行時創建的WinForms按鈕的委託?

List<System.Windows.Forms.Button> buttons = new List<System.Windows.Forms.Button>(); 

for(int i = 0; i < 5; i++) { 
    buttons.Add( System.Windows.Forms.Button>() ); 
    buttons[i].Name = "button_" + i.ToString(); 
    this.Controls.Add(buttons[i]); 
    buttons[i].Click += new System.EventHandler(this.Bt_windowClick); 
} 

接下來的部分是我困惑的地方。當這個委託被調用時,我想讓它告訴我實際單擊了哪個按鈕。我將如何做到這一點?

void Bt_windowClick(object sender, EventArgs e) 
{ 
    // I would like to get the name of the button that was clicked 
} 

非常感謝您的支持!

回答

4

發件人對象是一個按鈕,它引發了事件。所以,簡單地將它轉換爲Button類型:

void Bt_windowClick(object sender, EventArgs e) 
{ 
    Button button = (Button)sender; 
    // use button 
    MessageBox.Show(button.Name); 
} 
+1

非常感謝lazyberezovsky!它的工作原理:D – TheScholar

相關問題