title: Dynamically add code at runtime in VB(.NET)
body: <p>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).</p>
  
  <p>I learned how to create buttons at runtime with the <code>Button = new Button</code> and <code>controls.add(Button)</code> code. I also managed to pass a new code to the button by using <code>WithEvents</code> or an <code>AddHandler</code>. 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. </p>
  
  <p>Is there a way to dynamically create a code snipped at run time that will point to a pre-existing one?</p>
  
  <p>I'll give you a simplyfied example:</p>
  
  <pre><code>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 " &amp; flag)
  End Sub
  </code></pre>
  
  <p>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 <code>Private Sub MessageBox</code> or whatever code it may be in the end.</p>
  
  <p>I am very new to VB.Net, so please forgive me if the examples contains anything that makes you shiver.</p>
  
  <p>And thank you very much!</p>