【问题标题】:dynamically creating buttons in code in vb2010在vb2010的代码中动态创建按钮
【发布时间】:2013-02-11 21:08:11
【问题描述】:

我在 VB2010 中工作,我想我可以在代码中创建一个按钮数组;但是,我很难单独引用创建的按钮来编码它们的点击事件,以便它们在运行时工作。

任何帮助将不胜感激。我对 vb programmimg 还很陌生,所以放轻松!

【问题讨论】:

    标签: vb.net button addhandler


    【解决方案1】:

    试试这个:

    ' However many buttons you want
    Dim numButtons As Integer = 5
    Dim ButtonArray(numButtons) as Button
    Dim i As Integer = 0
    For Each b As Button in ButtonArray
       b = new button
       AddHandler b.Click, AddressOf Me.ButtonsClick
       b.Tag = "b" & i
       ' You can also set things like button text in here.
       i += 1
    Next
    
    
    Private Sub ButtonsClick(sender As Object, e As System.EventArgs)
        ' sender is the button that has been clicked. You can
        ' do what you'd like with it, including cast it as a Button.
        Dim currButton As Button = CType (sender, Button)
        Select Case currButton.Tag
            Case "b0":
              ' This is the first button in the array. Do things!
            Case "b1":
              ' This is the second button in the array. Do things!
            Case "b2":
              ' Notice a pattern?
    
            '...
    
        End Select
    End Sub
    

    【讨论】:

    • +1 但如果你向他展示关于如何描述Handles Button1.Click, Button2.Click 的按钮点击事件的第二种方法,你将获得更多选票
    【解决方案2】:

    在其中一个按钮单击事件上插入类似 , button2.click 的内容,它将执行相同的操作。

    或者您可能需要查看 addHandler .....

    【讨论】: