How can I create a dynamic button click event on a

2019-01-01 07:26发布

I am creating one button on a page dynamically. Now I want to use the button click event on that button.

How can I do this in C# ASP.NET?

5条回答
柔情千种
2楼-- · 2019-01-01 07:37
Button button = new Button();
button.Click += (s,e) => { your code; };
//button.Click += new EventHandler(button_Click);
container.Controls.Add(button);

//protected void button_Click (object sender, EventArgs e) { }
查看更多
柔情千种
3楼-- · 2019-01-01 07:38

The easier one for newbies:

Button button = new Button();
button.Click += new EventHandler(button_Click);

protected void button_Click (object sender, EventArgs e)
{
    Button button = sender as Button;
    // identify which button was clicked and perform necessary actions
}
查看更多
人间绝色
4楼-- · 2019-01-01 07:40

Let's say you have 25 objects and want one process to handle any one objects click event. You could write 25 delegates or use a loop to handle the click event.

public form1()
{
    foreach (Panel pl  in Container.Components)
    {
        pl.Click += Panel_Click;
    }
}

private void Panel_Click(object sender, EventArgs e)
{
    // Process the panel clicks here
    int index = Panels.FindIndex(a => a == sender);
    ...
}
查看更多
姐姐魅力值爆表
5楼-- · 2019-01-01 07:49

Simply add the eventhandler to the button when creating it.

 button.Click += new EventHandler(this.button_Click);

void button_Click(object sender, System.EventArgs e)
{
//your stuff...
}
查看更多
长期被迫恋爱
6楼-- · 2019-01-01 07:56

It is much easier to do:

Button button = new Button();
button.Click += delegate
{
   // Your code
};
查看更多
登录 后发表回答