1

我使用以下代码动态生成按钮。我想知道如何以这样的方式编码,如果我单击一个按钮,应该对同一表单中的其他按钮进行一些更改。由于所有按钮都是在循环中生成的,我不知道如何在代码的其他地方调用一个按钮。

   Private Sub random2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)         Handles MyBase.Load
    Dim i As Integer
    For i = 1 To 16
        Dim btn As New Button
        AddHandler btn.Click, AddressOf ClickMe
        btn.Width = 23
        btn.Height = 23
        btn.Text = ""
        btn.Tag = i
        btn.Name = i
        btn.Name = "Button" & i
        flp.Controls.Add(btn)   'flp stand for flow layout panel

    Next
End Sub
Private Sub ClickMe(ByVal Sender As Object, ByVal e As EventArgs)
    Dim btn As Button
    btn = CType(Sender, Button)
   dim str as string = btn.tag
   MsgBox(str)
        End Sub
    End Class
4

1 回答 1

2

您已将所有动态创建的按钮添加到 FlowLayoutPanel 控件集合中。
你会发现它们有这样的语法

Dim btn As Button = TryCast(flp.Controls("name"), Button)
if btn IsNot Nothing then
    btn.Caption = "New Text"
    ....
End If

或者,如果您想要特定索引处的按钮

Dim btn As Button = TryCast(flp.Controls(index), Button)
于 2012-06-11T07:48:38.347 回答