【问题标题】:Make all the buttons do the same things?让所有按钮做同样的事情?
【发布时间】:2014-03-08 07:08:39
【问题描述】:

我是 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...等这样的代码。有什么方法可以避免这种情况吗?例如使用一个数组?多谢!

【问题讨论】:

    标签: vb.net button


    【解决方案1】:

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

    任何带有多余按钮的 GUI 都不是好的 GUI。

    【讨论】:

    • 谢谢!我需要进行一些拖动。它被设计为识别和拖动以匹配问题。有更好的建议吗?
    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2013-07-19
      • 2016-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 2015-12-14
      相关资源
      最近更新 更多