Add Event at runtime

て烟熏妆下的殇ゞ 提交于 2019-12-13 03:34:51

问题


my method is :

private void button1_Click(object sender, EventArgs e)
    {
        for (int i = 1; i < 10; i++)
        {
            Button btn = new Button();
            btn.Name = "btn" + i.ToString();
            btn.Text = "btn" + i.ToString();
            btn.Click += new EventHandler(this.btn_Click);
            this.flowLayoutPanel1.Controls.Add(btn);
        }
    }
    void btn_Click(object sender, EventArgs e)
    {
           Button btn = (Button)sender;
        if (btn.Name == "btn1")
        {
            this.Text = "stack";
        }
    }

There is a better approach ?


回答1:


The code you used:

btn.Click += new EventHandler(this.btn_Click);

Is the correct code to add the handler. Creating the buttons and adding them to their container looks good.

The only thing I would add is just make sure you are creating the controls on postback too, prior to viewstate being restored, so that the events can actually be called.




回答2:


Or maybe:

private void button1_Click(object sender, EventArgs e)
{
    for (int i = 1; i < 10; i++)
    {
        Button btn = new Button();
        btn.Text = "btn" + i.ToString();
        btn.Tag = i;
        btn.Click += delegate
        {
            if ((int)btn.Tag == 1)
                this.Text = "stack";
        };
        this.flowLayoutPanel1.Controls.Add(btn);
    }
}


来源:https://stackoverflow.com/questions/3903933/add-event-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!