Visual Basic如何引用动态创建的按钮

时间:2016-12-30 04:52:59

标签: vb.net

我的代码动态创建40个按钮如果使用发件人单击按钮我可以更改属性但是当我单击其他按钮时如何引用它们

Public Sub loadButtons()


    For i As Integer = 0 To 39

        If i > 19 Then
            gap = i + 10
        Else
            gap = i
        End If
        Dim B As New Button
        Form1.panSeats.Controls.Add(B)

        B.Height = 30
        B.Width = 37
        B.Left = ((i Mod 10) * 47) + 322
        B.Top = ((gap \ 10) * 31) + 114

        B.Text = Chr((i \ 10) + Asc("A")) & i Mod 10 + 1
        B.Tag = i
        Buttons.Add(B.Text, B)
        If isBooked(i) = True Then


            B.BackColor = Color.Red
        Else
            B.BackColor = Color.Orange
        End If
        AddHandler B.Click, AddressOf Form1.Button_Click
    Next

End Sub

我希望能够更改背景颜色B未声明已尝试使用button.tag但无法正常工作

Private Sub btnTestCancel_Click(sender As Object, e As EventArgs) Handles btnTestCancel.Click

    B.BackColor = Color.Orange
End Sub

1 个答案:

答案 0 :(得分:0)

Addhandler语句为所有动态添加的按钮连接事件。 sender对象是被点击的对象,我们只需要将其解包。

AddHandler B.Click, AddressOf btns_Click

Private Sub btns_Click(sender As Object, e As EventArgs) 'no handles clause needed
  Dim btn As Button = DirectCast(sender, Button)
  btn.BackColor = Color.Orange
End Sub