This post originated from an RSS feed registered with .NET Buzz
by Peter van Ooijen.
Original Post: Handles, AddHandler and RemoveHandler in VB.NET
Feed Title: Peter's Gekko
Feed URL: /error.htm?aspxerrorpath=/blogs/peter.van.ooijen/rss.aspx
Feed Description: My weblog cotains tips tricks and opinions on ASP.NET, tablet PC's and tech in general.
Ãfter a crash course comes sinking in. This post is a rewrite of yesterdays one on events in VB.NET. I will concentrate on VB.NET include Daniel and chi's comment and after that I will return to my beloved C#.
There are several ways to declare events in VB.NET. The usual one is using the handles keyword. As Daniel pointed out this can link an event handling method to multiple events.
PrivateSub MyClick(ByVal sender AsObject, ByVal e As EventArgs) Handles Button1.Click, Button2.Click ListBox1.Items.Add(String.Format("You clicked {0}", CType(sender, Control).Name)) EndSub
This code will run on a click of button1 as well as a click of button2. The coupling of the events and handler is declared in the method signature.
You can also add an event dynamically form code.
PrivateSub MyOtherClick(ByVal sender AsObject, ByVal e As EventArgs) ListBox1.Items.Add("That other click") EndSub
PrivateSub ButtonAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonAdd.Click AddHandler Button2.Click, AddressOf MyOtherClick EndSub
Every time ButtonAdd is clicked it will add another event handler to Button2. When ButtonAdd is clicked 4 times a click of button2 will result in MyClick being executed first after which MyOtherClick is executed four times in a row.
You can also dynamically remove eventhandlers. This is not limited to handlers been set dynamically. This removes the event handler which was set with the handles keyword.
PrivateSub ButtonRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonRemove.Click RemoveHandler Button2.Click, AddressOf MyClick EndSub
Chid pointed out that you do not need to use the WithEvents keyword on an object when it's eventhandlers are set using AddHandler. Reflector shows that this does not make any difference at all. Just like handles, withevents is nowhere to be found in the actual generated code. In fact it all boils down to AddHandler and RemoveHandler which map to CLR functions. In this post I've shown that you can freely mix Handles and AddHandler. In last post Reflector showed that there are some subtltties behind the scenes. These subtleties are enough to make or brake the sinking of COM events. I'm gratefull for VB.NET fixing that for me. And a little sad for C# not doing what I had hoped to do. After all it's eventhandling syntax is imho far less confusing.