When/Why would you ever want to use this option? Is there a time when you can use this that you can't use the event directly?
Printable View
When/Why would you ever want to use this option? Is there a time when you can use this that you can't use the event directly?
AddHandler exposes the event..if you dont use that to map an event to a sub routine, it wont fire..it is not like VB6 where you could stick code in:
Sub Button_Click()
but if you are using VS .NET, it does the AddHandler code for you I beleive when you select an event...I think, so that maybe why you where confused by AddHandler and its use...
Thanks for the help.
AddHandler will mostly be used to link events to event handlers for controls that are created at run time.
eg. You want to load controls based on the data in a database. Because there are no control arrays anymore, you need to add event handlers for the controls created at runtime with the AddHandler method.
VB.NET has two ways of mapping events to subroutines. There's AddHandler, and there's the Handles keyword. Check the help files for information on how to use them. I think it's just a matter of preference which one you use, but AddHandler is more flexible, becuase you're setting which Sub handles what event at run time. This means you can set a particular Sub to handle an event, then later unset it (with RemoveHandler), and possibly set it to a different Sub if you want. I've used both of them at one time or another. They both work fine. However, note this warning from Microsoft (by WithEvents they mean the Handles keyword):
Quote:
You can use either approach, but you should not use both WithEvents and AddHandler with the same event.
Thanks for the help guys. I appreaciate your efforts. :)
I have done some reading and found out some additional information... if anyone is interested.
For the most part it does seem to be a matter of preference on which way to go. But it can also effect object lifetime. The event handler will hold a reference to the client, and unless you use RemoveHandler, the objects will remain in memory until the object with the eventsink is freed.