在VB(.NET)中在运行时动态添加代码

时间:2015-05-06 11:16:26

标签: vb.net button

我想在VB(.NET)中创建一个程序,其中每次单击按钮,一个或多个新按钮被添加到UserForm。这个过程应该无限次地工作。然后按钮应调用一个公共子,交换一个单独的变量,以便代码知道从哪个按钮调用(因此:知道该怎么做)。

我学习了如何使用Button = new Buttoncontrols.add(Button)代码在运行时创建按钮。我还设法使用WithEventsAddHandler将新代码传递给按钮。但到目前为止,我总是需要在程序运行之前准备好代码。即我需要提前知道按钮的名称并准备好代码。

有没有办法动态创建在运行时剪切的代码,指向预先存在的代码?

我会给你一个简单的例子:

WithEvents NewButton01 As New Button
WithEvents NewButton02 As New Button
WithEvents NewButton03 As New Button

Private Sub AddNewButton_Click() Handles AddNewButton.Click

    NewButton01.Location = New Point(10, 10)
    NewButton01.Text = "01"
    Controls.Add(NewButton01)

    NewButton02.Location = New Point(50, 50)
    NewButton02.Text = "02"
    Controls.Add(NewButton02)

    NewButton03.Location = New Point(90, 90)
    NewButton03.Text = "03"
    Controls.Add(NewButton03)

End Sub

Private Sub NewButton01_click() Handles NewButton01.Click
    Call MessageBox(1)
End Sub

Private Sub NewButton02_click() Handles NewButton02.Click
    Call MessageBox(2)
End Sub

Private Sub NewButton03_click() Handles NewButton03.Click
    Call MessageBox(3)
End Sub

Private Sub MessageBox(flag As Integer)
    MsgBox("You activated button number " & flag)
End Sub

正如您所看到的,这是一种非常不专业的编码方式。另外,我想保持创建无限量的按钮数量,因此我无法使用此代码。每次我点击" AddNewButton"我宁愿让VB创建一个新按钮。并编写一个引用Private Sub MessageBox的代码或最终可能的代码。

我是VB.Net的新手,所以请原谅我,如果这些例子包含让你颤抖的东西。

非常感谢你!

1 个答案:

答案 0 :(得分:2)

这样的事情可能有所帮助:

    Private Sub AddNewButton_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim lastButtonPos As Integer = 10
        For i = 1 To 3
            Dim NewButton As New Button
            NewButton.Location = New Point(lastButtonPos, lastButtonPos)
            NewButton.Text = "0" & i.ToString
            NewButton.Name = i.ToString
            AddHandler NewButton.Click, AddressOf Button_click
            Controls.Add(NewButton)
            lastButtonPos = lastButtonPos + 40
        Next

    End Sub

    Private Sub Button_click(ByVal sender As Object, ByVal e As EventArgs)
        Dim clickedButton As Button = CType(sender, Button)
        Dim clickedNumber As Integer = clickedButton.Name
        Call MessageBox(clickedNumber)
    End Sub

    Private Sub MessageBox(flag As Integer)
        MsgBox("You activated button number " & flag)
    End Sub