动态使用AddressOf

时间:2014-10-25 22:50:59

标签: vb.net visual-studio-2012 delegates addressof

我在运行时使用以下代码添加按钮以形成:

Private Sub AddNewButton(ByVal btnName As String, ByVal btnText As String)
    Dim myButtons As New VIBlend.WinForms.Controls.vButton

    With myButtons
        .Size = New Size(200, 60)
        .Visible = True
        .Location = New Point(55, 33)
        .Text = btnText
        .Name = btnName
        .Font = New Font("Times New Roman", 12, FontStyle.Bold, GraphicsUnit.Point)
    End With

    AddHandler myButtons.Click, AddressOf btnName & "_Click"

    btnsPanel.Controls.Add(myButtons)

End Sub

代码工作正常,但Vb.net不允许我使用变量AddressOf btnName & "_Click" AddressOf operand must be the name of method分配AddressOf子程序,问题是我不知道哪个按钮是将要创建以及它将调用哪个过程,我想使用变量分配AddressOf过程 是否有可能或者我还有其他选择吗?

3 个答案:

答案 0 :(得分:6)

您可以(并且应该)对所有按钮使用相同的事件处理程序。

AddHandler myButtons.Click, AddressOf btn_Click

您可以通过以下方式获取处理程序中的名称:

Private Sub btn_Click(sender As Object, e As EventArgs)
    Dim button = DirectCast(sender, Button)
    Dim name As String = button.Name ' you can also use the Tag property
End Sub

答案 1 :(得分:3)

你也可以使用closure,我总觉得它非常灵活和可读。

Imports VIBlend.WinForms.Controls

Private Sub AddNewButton(ByVal btnName As String, ByVal btnText As String)
    Dim myButton = New vButton() With
                    {
                        .Size = New Size(200, 60),
                        .Visible = True,
                        .Location = New Point(55, 33),
                        .Text = btnText,
                        .Name = btnName,
                        .Font = New Font("Times New Roman", 
                                 12, FontStyle.Bold, GraphicsUnit.Point)
                    }

    AddHandler myButton.Click, Sub(s, e)
                                   'Do something with Name
                                   MessageBox.Show(myButton.Name)
                                   'Or do something in a instance method
                                   Me.HandleButtonClick(myButton)
                               End Sub

    btnsPanel.Controls.Add(myButton)
End Sub

Private Sub HandleButtonClick(myButton As vButton)
    ' DO something her with myButton
End Sub

答案 2 :(得分:1)

这个问题虽然陈旧,却缺乏直接而完整的答案。这是一个(动态)按钮的完全动态处理程序:

    Dim SubName As String = dr("SubToRun").ToString
    Dim Pareameter1 As String = dr("Pareameter1").ToString
    Dim Pareameter2 As String = dr("Pareameter2").ToString
    Dim Pareameter3 As Int32 = ValPareameter3
    AddHandler btn.Click, Sub(s, e)
                              CallByName(Me, SubName, CallType.Method, Pareameter1, Pareameter2, Pareameter1)
                          End Sub