簡體   English   中英

將事件添加到動態添加的控件

[英]Add events to controls added dynamically

我正在使用winform app。 我添加了一些動態控件,例如。 Button現在我想向該創建的按鈕添加一個事件,我該如何執行此操作? 也有人可以向我推薦一本C#書,它涵蓋了winform中的所有主題嗎? 謝謝。

// create some dynamic button
Button b = new Button();
// assign some event to it
b.Click += (sender, e) => 
{
    MessageBox.Show("the button was clicked");
};
// add the button to the form
Controls.Add(b);

我完全同意Darin的回答,這是添加動態事件的另一種語法

private void Form1_Load(object sender, EventArgs e)
{
    Button b = new Button();
    b.Click += new EventHandler(ShowMessage);
    Controls.Add(b);
}

private void ShowMessage(object sender,EventArgs e)
{
    MessageBox.Show("Message");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM