How to grow rich in C# the event handler of a class in an inherited class

P

polocar

Hi,
I'm writing a C# program (using Visual Studio 2005 Professional
Edition).
I have defined a class MyPanel in the following way:

class MyPanel : Panel
{
...
}

In this class I have put a btn Button control, and I have defined the
event handler:

btn.Click += new EventHandler(btn_Click);

...

void btn_Click(object sender, EventArgs e)
{
...
}

Then, I have defined another class, inherited from MyPanel:

class MyPanel2 : MyPanel

In this class I would like to enrich the btn_Click event handler (the
code of the base class should be executed anyway), but I don't know
why...
If it were a method, as for example

protected void InitializeControls()
{
...
}

in the inherited class I could write:

protected override void InitializeControls()
{
base.InitializeControls();
...
}

but if I want to enrich an event handler and not a method, how can I
do? (I have tried to add the "protected" keyword in the event
handler definition of MyPanel base class:

protected void btn_Click(object sender, EventArgs e)
{
...
}

but when I go in the inherited class and try to write "protected
override", the methods list the compiler shows me doesn't include
this event handler...

Can you give me any suggestion about that?
Thank you very much
 
M

Marc Gravell

to override, it must first be virtual (e.g. "protected virtual
SomeMethod(blah)"). For use in inheritance, I would also personally
tweak the name to be a bit clearer too.

Marc
 
D

DeveloperX

If you create a method OnButtonClick and make it overridable, then in
the derived class it will be called when ever the event fires in the
base class.

So your base class will wire up the event for the button to fire and
call

protected virtual void OnButtonClick(System.EventArgs e)

The derived class will have
protected override void OnButtonClick(System.EventArgs e)
When the button in the base class is clicked the override version in
the derived class will be called.
If you want to do something in addition to what the base class usually
does call

base.OnButtonClick (e);
after doing your processing in the derived class.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top