Add event at runtime

my method:

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";
        }
    }

      

Is there a better approach?

0


source to share


2 answers


The code you are using is:

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

      



Correct code to add handler. Creating buttons and adding them to your container looks good.

The only thing I'd like to add is just to make sure that you also create postback controls before restoring the view state so that events can actually be triggered.

+2


source


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);
    }
}

      

+2


source







All Articles