简体   繁体   English

为按钮单击事件动态添加处理程序

[英]Dynamically add handler for a button click event

How can I add a handler for the click event of every single generated button?如何为每个生成的按钮的单击事件添加处理程序?

For example:例如:

Button btn = new Button();
btn.ID = "delete_" + i.ToString();

btn.Click += degerate
{
     callFunction(i);
};

Whenever I try pressing the button, it'll only affect calling the function for the last inserted click event.每当我尝试按下按钮时,它只会影响调用最后插入的点击事件的函数。 Any suggestions for a fix?有什么修复建议吗?

Within the loop you used to declare your buttons, use the following snippet:在用于声明按钮的循环中,使用以下代码段:

button.Click += new EventHandler(<funcName>);

Don't forget that "funcName" must match the EventHandle delegate.不要忘记“funcName”必须与 EventHandle 委托相匹配。

Then all your buttons will share the same Event Code, but each event is bound to it's own button.然后你所有的按钮将共享相同的事件代码,但每个事件都绑定到它自己的按钮。

You can access all info of each button, by casting the sender as the specific object type you're using, for example:您可以通过将发件人转换为您正在使用的特定对象类型来访问每个按钮的所有信息,例如:

Button btn = (Button)sender;
btn.ID = <new value>;

If the code you have above all gets executed every time you want to add a click handler, you are creating a brand new button object each time.如果每次您想要添加点击处理程序时都执行您最重要的代码,那么您每次都在创建一个全新的按钮对象。 Because it is a totally new object, it knows nothing about the click handlers attached to older buttons.因为它是一个全新的对象,所以它对附加到旧按钮上的点击处理程序一无所知。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM