views:

447

answers:

2

I need to add an event handler to an inherited control like a datagridview but Visual Studio doesn't allow me. Isn't there a way for an inherited control to fire a base event handler AND the inherited one? in a sequence I specify?

A: 

Events in WinForms typically have a corresponding "On*" method. Simply call that method, and it'll raise the event. If you want to raise "CellClick" for example, call "base.OnCellClick(new DataGridViewCellEventArgs(row, column))".

David Morton
+1  A: 

Your question is unclear. Assuming that you're trying to handle the base class' event in the inherited control, you can override the OnEventName protected virtual method. In the override, make sure to call the base method or the event won't fire.

This method exists (AFAIK) for every event in every control in System.Windows.Forms. If the control you're inheriting does not have this virtual method, you can subscribe to the vent in the constructor.

For example:

class MyButton : Button {
    //First way
    protected override void OnClick(EventArgs e) { 
        base.OnClick(e);    //Without this line, the event won't be fired
        //...
    }


    //Second way
    public MyButton() {
        base.Click += Base_Click;
    }

    void Base_Click(object sender, EventArgs e) {
        //...
    }
}


EDIT:

If you're trying to raise the base class' event, you can call these OnEventName methods.

If the base class doesn't have one, the only way to do it is to declare a new event, and add a handler to the original event from the base class that raises your new event. Note that if you have other code that uses the base class' event, and the evnet is not virtual and doesn't have a raiser method, you're out of luck, unless you can decompile the base clas and find out where the event is raised.

SLaks