Manually Adding Event Handlers in VB.NET


office-019

Typically when we write our code, the event handlers get wired up for us using the handles clause.  So we never have to worry about wiring up our event handlers manually.

But what about the case where we want to dynamically add a control to our Windows Form or our ASP.NET page?  For example, add a button.  How would you respond to the button click event?

In CSharp, there is no handles clause, so figuring out how to manually wire up the event handler is simply a matter of inspecting the dotNet code and doing a copy/paste/modify operation in the editor.

The syntax for adding event handlers manually is not that difficult.

AddHandler m_button.Click, AddressOf buttonClickMethod

If you’ve written any threading code, you’ll notice that this looks similar to the code you might have written for that.

The AddHandler statement takes two parameters.  The first is the event we are going to handle–in this case, the click event from the object that m_button is pointing to.


The second parameter is a pointer to a function that will handle the event.  What is unique about this is that it can be a method that is part of the current class, which is what the code above is referencing, or it can be a method in another object, or even a method that is shared in another class.

To reference a method in another object

AddHandler m_button.Click, _
    AddressOf SomeOtherObject.buttonClickMethod

To reference a shared method

AddHandler m_button.Click, _
    AddressOf SomeClass.buttonClickMethod

Which gives us quite a bit of flexibility when we dynamically wire up our events.

Ads by Lake Quincy Media

Other Related Items:

GRAY WITH DARK RED TRIM LAPTOP SLEEVE FOR 17 INCH LAPTOPGRAY WITH DARK RED TRIM LAPTOP SLEEVE FOR 17 INCH LAPTOPThis style of Laptop sleeve is constructed of 5mm thick industrial gray felt, and features a secure flap with a colored inner lining. When closed, the... Read More >
Regular Expressions CookbookRegular Expressions Cookbook

Whether you're a novice or an experienced user, Regular Expressions Cookbook will help deepen your understanding of the tool. You'll learn powerf... Read More >

Lemony Snicket's A Series of Unfortunate EventsLemony Snicket's A Series of Unfortunate EventsIn Lemony Snicket's A Series of Unfortunate Events, you'll follow the Baudelaire orphans as their luck goes from bad to incredibly worse. This treache... Read More >

If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!

Related Post

One Response to “Manually Adding Event Handlers in VB.NET”

DotNetNuke Sponsor

 

Most Valuable Blogger
Sponsor