VB.Net 2005: event handlers

k3n51mm

Active member
Joined
Mar 7, 2007
Messages
40
Programming Experience
3-5
I have a form that must assign different handlers to a button's click event depending on a variable set elsewhere.

Each time the screen is loaded, I need to explicitly set the state of the button: its image, tooltiptext, and of course its click event handler. It's a huge complication (4*3*2 times - all the possible combinations) to have to keep track of and remove all existing handlers explicitly before assigning the correct handler for the current context.

QUESTION: How can I remove all handlers from an event without having to refer to them explicitly, so I can assign the correct one and know it will fire correctly?
 
Look up the AddHandler function, for a start...

ps, this is typically wher we would use ploymorphism to solve.. One generic parent type.. many child types. Variosu buttons are associated with one or another child type. They all have a DoStuff() method that is called, and the differing action depends on which class implementation is used,, That way one handler can do everything,,,
 
Thanks for the reply. I found DoStuff() in another forum, and I thought it must be some inside joke. Are you telling me it's real? If so, it's undocumented, so there's that...right?
 
Thanks for the reply. I found DoStuff() in another forum, and I thought it must be some inside joke. Are you telling me it's real? If so, it's undocumented, so there's that...right?

http://en.wikipedia.org/wiki/Polymorphism_(computer_science)


Make a parent class
Make as many children as you need to have different behaviours
All child behaviours are done by the overridden DoStuff()
Call the DoStuff() method anything you like
Create a Dictionary(Of Object, PolymorphicParentClass) [note, i use Object and not Button because it simplifies the event handler code below]
Add each button to the dictionary like this: myDictionary.Add(buttonX, New WhicheverChildPolymorphicClassDoesThisButtonsAction)

Each button has the same handler code:

VB.NET:
Sub generic_Click(sender as Object, e as WhateverEventArgs) Handles <all the buttons clicks go here>

  myDictionary(sender).DoStuff()

End Sub

Now, whichever child is associated with the button now, is called upon to DoStuff()

If you want to swap the actions, simply associate the button with a new child action:

myDictionary(buttonX) = New DifferentWhicheverChildPolymorphicClass



If you can tell a little more about your actual problem you are trying to solve, and not the problem youve hit with your imagined solution, then I can be more specific with the help
 
You can only do that internally in your own classes (not inherited/button class for instance), but it would rarely be justified... cjards suggestion about polymorphism could be it.
 
Back
Top