开发者

How to pass Button.Click into a function?

I have a function that adds eventhandlers to control events. Right now I have several overloads that add events to different types of c开发者_如何学编程ontrols:

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!


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜