让所有按钮做同样的事情?

时间:2014-03-08 07:08:39

标签: vb.net button

我是vb和gui编程的新手。我希望我的表单上的一组按钮在执行某些操作时执行完全相同的操作,例如单击。我在这个问题How do I make buttons do the same thing?中找到了一些方法。根据它,我写了一些代码并且确实有效。

 Private Sub Answers_MouseDown(sender As System.Object, e As System.EventArgs) _
Handles Button1.MouseDown, Button2.MouseDown, Button3.MouseDown
    MessageBox.Show("Hi!")
End Sub

问题是现在我有更多按钮(10个或更多),我不想写像Button1.MouseDown,Button2.MouseDown,Button3.MouseDown等代码。有什么方法可以避免这种情况吗?例如使用arrary?多谢!

2 个答案:

答案 0 :(得分:1)

你拥有的是最短的方法,你需要命名数组中的按钮,这样它就不会更短

任何带有冗余按钮的GUI都不是一个好的GUI。

答案 1 :(得分:1)

将控件添加到Button类型的数组或List中,然后您可以迭代遍历集合,动态添加事件处理程序。然后,您可以通过将发件人转换为按钮来获取单击按钮的实例。

Public Class Form1
    Dim myButtons As List(Of Button) = New List(Of Button)
    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call.
        myButtons.Add(Button1)
        myButtons.Add(Button2)
        myButtons.Add(Button3)
        myButtons.Add(Button4)
        myButtons.Add(Button5)
        myButtons.Add(Button6)
        For Each btn As Button In myButtons
            AddHandler btn.Click, AddressOf myButtonClick 'Add your eventhandlers
        Next

    End Sub

    Private Sub myButtonClick(sender As Object, e As EventArgs)
        Dim btn As Button = DirectCast(sender, Button)
        'Do what ever you need to do to the calling control
    End Sub

End Class
相关问题