mercredi 6 mai 2015

Dynamically add code at runtime in VB(.NET)

I want to make a program in VB(.NET) in which per click on a button one or more new buttons are added to the UserForm. This process should work for an infinite number of times. Then the buttons shall call a public sub, handing over an individual variable so that the code knows what button it was called from (thus: knows what to do).

I learned how to create buttons at runtime with the Button = new Button and controls.add(Button) code. I also managed to pass a new code to the button by using WithEvents or an AddHandler. But until now I always need to have the code ready before the program is run. I.e. I need to know the name of the button in advance and have the code prepared.

Is there a way to dynamically create a code snipped at run time that will point to a pre-existing one?

I'll give you a simplyfied example:

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

As you can see, this is a very unprofessional way of coding. Also, I'd like to keep the amount of buttons created infinite, so I can't use this code. I'd rather have VB make a new button each time I click on "AddNewButton" and write a code that refers to Private Sub MessageBox or whatever code it may be in the end.

I am very new to VB.Net, so please forgive me if the examples contains anything that makes you shiver.

And thank you very much!

Aucun commentaire:

Enregistrer un commentaire