我怎样才能使一个单一的事件处理程序处理所有Button.Click事件? [英] How can I make a single event handler handle ALL Button.Click events?
问题描述
在我的计划,我有9个按键,而我对他们每个人的9间事件处理程序,尽管在每个事件处理程序的code是相同的。它被证明是非常繁琐的改变code为他们所有。是否有可能使一个单一的Button.Click事件处理程序处理该事件Button.Click我所有的按钮?
In my program, I have 9 buttons, and I have 9 separate event handlers for each of them, despite the fact that the code in each event handler is the same. It is proving to be very tedious to change the code for all of them. Is it possible to make a single Button.Click event handler that handles the Button.Click events for all of my buttons?
推荐答案
您可以修改把手
在VS生成的事件code,以便它可以处理条款多个控件相同的事件。在大多数情况下,有人可能希望漏斗大多数,但不是所有的,按钮点击一个过程。要改变Handles子句:
You can modify the Handles
clause on the VS generated event code so that it can process the same event for multiple controls. In most cases, someone might want to funnel most, but not all, button clicks to one procedure. To change the Handles clause:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button1.Click,
Button3.Click, Button4.Click ...
' just add the extra clicks for the additional ones
' you will need to examine "Sender" to determine which was clicked
' your code here
End Sub
此,也可以动态地完成,如将被创建并添加到加载事件的形式(或者其它任何)控制
This can also be done dynamically, such as for controls which are created and added to a form in the Load event (or where ever):
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddHandler Button1.Click, AddressOf AllButtonsClick
AddHandler Button2.Click, AddressOf AllButtonsClick
AddHandler Button3.Click, AddressOf AllButtonsClick
End Sub
要literately线全部按钮,同样的事件,可以循环直通控件集合(使用LINQ):
To literately wire all buttons to the same event, you can loop thru the controls collection (uses Linq):
For Each b As Button In Controls.Controls.OfType(Of Button)
AddHandler b.Click, AddressOf MyClickHandler
Next
这篇关于我怎样才能使一个单一的事件处理程序处理所有Button.Click事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!