Handle events for dynamic (run-time) controls - VB.NET
Solution 1
Use AddHandler
e.g.
AddHandler Obj.Ev_Event, AddressOf EventHandler
and when you want to get rid of it (and you should get rid of it when you're done using it)
RemoveHandler Obj.Ev_Event, AddressOf EventHandler
in your case, you might have something like
Dim web as New WebBrowser()
AddHandler web.DocumentCompleted, AddressOf HandleDocumentCompleted
assuming you'd created an event handler called HandleDocumentCompleted
Depending on your needs, you could also use the WithEvents keyword when you declare your webbrowser; see the documentation.
Solution 2
An alternative to using AddHandler
is the declarative events syntax in VB. To use it, you declare the control (as a private member), using the WithEvents
keyword. Then, the Handles
keyword can be used on methods to handle the appropriate events:
Private WithEvents m_WebBrowser As WebBrowser
Private Sub WebBrowser_Navigate(ByVal sender As Object, ByVal e As WebBrowserNavigatedEventArgs) Handles m_WebBrowser.Navigate
MsgBox("Hi there")
End Sub
Private Sub SomeActionThatCreatesTheControl()
m_WebBrowser = New WebBrowser()
End Sub
There are mainly two advantages to this method:
- No need for
RemoveHandler
, - No need to wire all event handlers manually: this is done automatically.
Solution 3
- You will need to use AddHandler and RemoveHandler.
- If you manually add an event through AddHandler be sure to remove it (in an appropriate location) using RemoveHandler.
- Typing "AddHandler NameOfControl." will give a list of available events via intellisense.
- Intellisense, documentation, (or the "error list"), will also give you the "signature" of the event handler.
Private Sub WebBrowser1_Navigate(ByVal sender As Object, ByVal e As WebBrowserNavigatedEventArgs)
End Sub
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
RemoveHandler WebBrowser1.Navigated, AddressOf WebBrowser1_Navigate
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
AddHandler WebBrowser1.Navigated, AddressOf WebBrowser1_Navigate
End Sub
user57175
Updated on June 05, 2022Comments
-
user57175 almost 2 years
I have a WebBrowser control that is created and added to the form during run-time.
How do I connect this control to subroutine that can handle its events at run-time?