如何处理点击的可变数量的按钮?

时间:2014-07-13 16:47:40

标签: vb.net

我有一个非常基本的问题,VB.Net中的按钮点击我似乎无法弄明白。

首先,我创建了一个可变数量的按钮并将它们添加到父窗体中。

Private Sub CreateUIObjects()
    For i As Integer = 1 To NumberOfButtons
        Dim button As Button = New Button()
        Me.Controls.Add(button)
    Next
End Sub

我知道可以使用以下代码处理固定数量的按钮

Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Handles Button1.Click, Button2.Click, Button3.Click '... And so on
        Dim b As Button = CType(sender, Button)

End Sub


但是我怎么办不是3,而是可变数量的按钮?

2 个答案:

答案 0 :(得分:0)

你可以使用这样的东西

AddHandler Button1.Click, AddressOf Button_Click

看看http://msdn.microsoft.com/en-us/library/ms172877.aspx

答案 1 :(得分:0)

一些试验

的代码
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    CreateUIObjects(3)
End Sub

Dim myButtonNames As String = "foobar"
Private Sub myButtonsClick(sender As Object, e As EventArgs)
    Dim b As Button = DirectCast(sender, Button)
    Debug.WriteLine(b.Name)
End Sub

Private Sub CreateUIObjects(NumberOfButtons As Integer)
    Static ct As Integer = 0
    For i As Integer = 1 To NumberOfButtons
        ct += 1
        Dim btn As Button = New Button()
        btn.Name = myButtonNames & ct.ToString
        btn.Text = btn.Name
        btn.Location = New Point(ct * 20, ct * 20)
        AddHandler btn.Click, AddressOf myButtonsClick
        Me.Controls.Add(btn)
    Next
End Sub