tags:

views:

45

answers:

2

I have a function that adds eventhandlers to control events. Right now I have several overloads that add events to different types of controls:

Public Sub AddEventHandler(Button, ButtonEvent) 'adds event handling for Button.Click
public Sub AddEventHandler(LinkButton, ButtonEvent)'adds event handling for LinkButton.Click

The problem is I want to write a function that is more robust like:

Public sub AddEventHandler(Control, EventToHandle, ControlEvent)

where

EventToHandle is the parameter representing Button.Click or whatever event that Button has associated with it.

Any suggestions guys? Thanks!

A: 

The right way is probably done using reflection. A simpler way, however, would be to do something like this.

(Code is in C#, but conversion is pretty trivial.)

private void AddEventHandler(Control c, Event e){
    if(c is LinkButton){
        ((LinkButton)c).Click += e;
    }
    else if(c is Button){
         ((Button)c).Click += e;
    }
    /* etc */
}

If you sometimes want to do an event that isn't "Click" you could pass a string representing the event name as a third argument and wrap it thusly:

if(what_event == "Click"){
    if(c is LinkButton){
        ((LinkButton)c).Click += e;
    }
    /* etc */
}
else if(what_event == "SelectedIndexChanged"){
    if(c is DropDownList){
        ((DropDownList)c).SelectedIndexChanged += e;
    }
    /* etc */
}

Sucks but it works and might be more compact than what you have now.

Sorpigal
This isn't the way I'd like to go...every time I want to handle a new event or control I have to add code...
Achilles
+1  A: 

You still can do something like this:

private void Subscribe<TControl>(TControl control, Action<TControl, EventHandler> subscriber, EventHandler handler)
{
    subscriber.Invoke(control, handler);
}

And using:

   Subscribe(this, (control, handler) => control.Load += handler, LoadHandler);

But I don't think it is better then actually subscribing to the event.

Andrew Bezzub
+ for last line. Seems like one of those good ideas until you get into the details. This will just confuse any other programmers that have to look at your code.
Greg