开发者

How to Add an event to a list of button at runtime

I am trying to create buttons at runtime. My Question is that How should I add an Event to each of the buttons at runtime mode also?

For example:

Button btn;
int i =0;
int j =0;
List<Button> listBTN = new List<Button>();

private void button1_Click(object sender, EventArgs e)
    {
        btn = new Button();
        btn.Location = new Point(60 + i, 90);
        btn.Size = new Size开发者_JAVA百科(50, 50);
        btn.Name = "BTN";

        listBTN.Add(btn);

        i = i + 50;

        foreach(Button b in listBTN){
        this.Controls.AddRange(new Button[] {b});
        }
    }

How to Add an event to a list of button at runtime


btn.Click += yourMethod;

private void yourMethod(object sender, EventArgs e)
{
    // your implementation
    Button btn = sender as Button;
    if (btn != null)
    {
        //use btn
    }
}

if you want to add the event when you declare the button use:

btn.Click += delegate
{
     //your implementation
};


You can do something like this:

Button btn = new Button();
btn.Name = "BTN" + i.ToString(); //just to be sure you can distinguish between them
btn.Click += new EventHandler(btn_Click);

And add default handler for all buttons:

    void btn_Click(object sender, RoutedEventArgs e)
    {
        Button btn = (Button)sender;
        MessageBox.Show("You have clicked button number " + btn.Name);
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜