Handle events for dynamic (run-time) controls - VB.NET


Question

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?

1
1
5/6/2013 10:15:29 PM

Accepted Answer

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.

8
2/12/2009 7:30:19 PM

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon