C#動態創建控件並綁定事件

C#動態創建控件並綁定事件

private void Form1_Load(object sender, EventArgs e)
{
    for (int i = 0; i < 5; i++)
    {
        Button btn = new Button();   //創建對象
        btn.Size = new Size(100, 25);   //大小
        btn.Text = (i + 1).ToString();        //文本
        btn.Location = new Point(i*120,12);     //位置
        btn.Click += new EventHandler(Btn_Click);   //委託事件,綁定全部按鈕點擊事件
        btn.MouseClick += new MouseEventHandler(Btn_MouseClick);    ////委託事件,綁定全部按鈕鼠標點擊事件
        this.Controls.Add(btn);     //添加到窗體
    }
}

public void Btn_Click(object sender, EventArgs e)
{
    Button btn = (Button)sender;    //獲取所點擊的對應的button
    MessageBox.Show(btn.Text);
}

public void Btn_MouseClick(object sender, MouseEventArgs e)
{
    Button btn = (Button)sender;    //獲取所點擊的對應的button
    if (e.Button == MouseButtons.Right)
    {
        //右鍵需執行代碼
        
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章