1

我正在使用以下代码在运行时向窗体添加按钮:

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 子过程AddressOf operand must be the name of method,问题是我不知道要创建哪个按钮以及它将调用哪个过程,我想分配使用变量的 AddressOf 过程是否有可能或者我还有其他选择吗?

4

3 回答 3

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
于 2014-10-25T23:02:21.533 回答
3

你也可以使用一个闭包,我总是觉得它非常灵活和可读。

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
于 2014-10-26T11:56:14.240 回答
2

这个问题虽然古老,但缺乏直接和完整的答案。这是一个(动态)按钮的完全动态处理程序:

    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
于 2017-12-08T10:57:05.693 回答