it took me ages to find it. i googled "add controls at runtime" and not one single result gave me the intstructions on how to add code to the controls. kinda useless with no code, ehh? all results only told me how to add the control, that's it. well, this result is different. i will teach you firstly how to add controls at runtime, then how to apply code to them at runtime


firstly, add the controls:

create a new windows forms application
then double click on the form and type this:

Dim mybutton As New Button
        mybutton.Name = "button1"
        mybutton.Location = New Point(20, 20)
mybutton.text = "click me"
        Me.Controls.Add(mybutton)
        With mybutton
            AddHandler .Click, AddressOf button1_click
        End With

now run it. do you have a button on the form? if yes, excellent. if not, you made a mistake. try again

now how to add code? you may have noticed that when you double click on any control, it says private sub button1_click(blah, blah, blah) Handles button1.click
where it says handles button1.click is what determines when the code executes under what event for what control (in this case the click event for the button1). this won't work when adding code at runtime.

did you notice in the above example i added a with event, and addHandler? this is what creates the handler (same as Handles button1.click)

now we add the code for the runtime control

private sub button1_click()
MsgBox("you have added code and a control at runtime!")
end sub

above, the addressOf button1_click tells the program to execute the sub button1_click when the button is clicked on (as determined by .click)


but i know what you're thinking! your thinking "why would we even BOTHER doing this at runtime? isn't it easier to do it at design-time in the first place?"

yes it is, providing your not writing a plugin. plugins are code based, not GUI (also reffered to as WYSIWYG). to update existing forms using plugins, you need to use this method.

Dani AI

Generated

Nice starter from — creating controls at runtime and wiring events is exactly the technique you want for variable UIs or plugin-style extensions. Two practical clarifications that were missing in the thread: the event-handler signature must match the event delegate, and dynamic controls must be created/removed on the UI thread and disposed when no longer needed.

Dim btn = New Button With {.Text = "Run", .Location = New Point(12, 12), .Tag = "plugin42"}
AddHandler btn.Click, Sub(s As Object, e As EventArgs)
                          Dim b = DirectCast(s, Button)
                          MessageBox.Show("Clicked: " & CStr(b.Tag))
                      End Sub
Me.Controls.Add(btn)

If you prefer AddressOf, the target must be declared like Private Sub Handler(sender As Object, e As EventArgs) so the signatures match. When removing controls remember RemoveHandler (if you attached a named handler) and call Dispose to avoid leaks — keeping dynamic controls in a List or Dictionary makes cleanup simple. If controls are created from a background thread use Invoke/BeginInvoke to add them on the form thread; otherwise the control may not show or will throw cross-thread exceptions.

On the "add code at runtime" side: is correct that you cannot magically patch compiled VB source inside the running assembly. Common, safer patterns are (a) ship plugins as separately compiled assemblies that implement a known interface and load them with reflection or MEF, or (b) run untrusted plugins out-of-process (as hinted) and communicate via IPC for isolation. More advanced options include on-the-fly compilation (CodeDOM/Roslyn) or scripting engines, but those add security and maintenance considerations.

Troubleshooting checklist: verify parent.Controls.Add was called on the correct container, the control Location lies inside the client area, the control is Visible and Enabled, and the handler signature matches the event delegate.

Recommended Answers

All 6 Replies

You can't add code at runtime because VB code has to be compiled. However, it is still very useful to be able to add controls at runtime. For example, I wrote a version of Scattergories last summer. The number of players can vary from game to game so it is convenient to be able to generate controls for the input and display for the players at runtime. If you have an application that uses external programs you could add buttons at runtime to link to these tools. The buttons can all use the same handler but invoke different programs depending on what the user entered when the tool was added.

Yea so its basically like compiling new code but from external side of the Original app if im right

Right. And that can't be done from inside your application.

Yea like firefox uses separate app for its plugins

But it uses almost 100 mb to do it :icon_lol:
Epic fail :icon_mrgreen:

or maybe its just container that might make the odds better but still 100 mb not right :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.