如何使单个事件处理程序处理所有Button.Click事件? [英] How can I make a single event handler handle ALL Button.Click events?
问题描述
您可以修改VS生成的事件代码上的句柄
子句,以便它可以处理多个控件的相同事件。在大多数情况下,有人可能希望将大部分(而不是全部)按钮点击一次。更改Handles子句:
Private Sub Button3_Click(作为对象的发件人,作为EventArgs)Handles Button1.Click,
Button3.Click,Button4.Click ...
'只需添加额外的额外点击
',您将需要检查发件人以确定哪个被点击
'你的代码这里
End Sub
这也可以动态完成,例如在Load事件(或以前)中创建并添加到表单中的控件:
Private Sub Form1_Load (发件人As Object,e As EventArgs)处理MyBase.Load
AddHandler Button1.Click,AddressOf AllButtonsClick
AddHandler Button2.Click,AddressOf AllButtonsClick
AddHandler Button3.Click,AddressOf AllButtonsClick
End Sub
要将所有按钮切换到同一个事件,你可以循环通过控制集合n(使用Linq):
为每个b按钮在XXXXX.Controls.OfType(Of Button)
AddHandler b.Click,AddressOf MyClickHandler
Next
其中 XXXXX
可能是我
或面板,分组框等 - 无论按钮在哪里。
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?
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
To literately wire all buttons to the same event, you can loop thru the controls collection (uses Linq):
For Each b As Button In XXXXX.Controls.OfType(Of Button)
AddHandler b.Click, AddressOf MyClickHandler
Next
Where XXXXX
might be Me
or a panel, groupbox etc - wherever the buttons are.
这篇关于如何使单个事件处理程序处理所有Button.Click事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!