如何让单个事件处理程序处理所有 Button.Click 事件? [英] How can I make a single event handler handle ALL Button.Click events?

查看:42
本文介绍了如何让单个事件处理程序处理所有 Button.Click 事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我有 9 个按钮,每个按钮都有 9 个单独的事件处理程序,尽管每个事件处理程序中的代码都是相同的.事实证明,更改所有代码的代码非常乏味.是否可以创建一个 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 生成的事件代码上的 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

这也可以动态完成,例如在 Load 事件中(或任何地方)创建并添加到表单的控件:

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

要将所有按钮连接到同一个事件,您可以循环遍历控件集合(使用 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 XXXXX.Controls.OfType(Of Button)
     AddHandler b.Click, AddressOf MyClickHandler
Next

XXXXX 的位置可能是 Me 或面板、分组框等 - 无论按钮在哪里.

Where XXXXX might be Me or a panel, groupbox etc - wherever the buttons are.

这篇关于如何让单个事件处理程序处理所有 Button.Click 事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆