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?
如何在c# ASP.NET中实现这一点?
5 个解决方案
#1
45
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) { }
#2
29
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}
#3
9
Simply add the eventhandler to the button when creating it.
创建时只需将eventhandler添加到按钮中。
button.Click += new EventHandler(this.button_Click);void button_Click(object sender, System.EventArgs e){//your stuff...}
#4
5
It is much easier to do:
这样做要容易得多:
Button button = new Button();button.Click += delegate{ // Your code};
#5
-1
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.
假设您有25个对象,并希望一个进程处理任何一个对象单击事件。您可以编写25个委托或使用一个循环来处理单击事件。
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); ...}
#1
45
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) { }
#2
29
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}
#3
9
Simply add the eventhandler to the button when creating it.
创建时只需将eventhandler添加到按钮中。
button.Click += new EventHandler(this.button_Click);void button_Click(object sender, System.EventArgs e){//your stuff...}
#4
5
It is much easier to do:
这样做要容易得多:
Button button = new Button();button.Click += delegate{ // Your code};
#5
-1
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.
假设您有25个对象,并希望一个进程处理任何一个对象单击事件。您可以编写25个委托或使用一个循环来处理单击事件。
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); ...}