Events in classes

A

Alberto

This class inherits from Label and changes the Text when the user makes
double click over it:

class C: Label
{

private void InitializeComponent()
{
this.SuspendLayout();
//
// C
//
this.DoubleClick += new System.EventHandler(this.C_DoubleClick);
this.ResumeLayout(false);

}

private void C_DoubleClick(object sender, EventArgs e)
{
this.Text = "Prueba";
}
}

When I put a control C in a form, nothing happens when the user makes double
click over it. Why?
Thank you.
 
M

Morten Wennevik [C# MVP]

Hi Alberto,

Indeed you forgot to call your initialization code. However, if all you
want to do is to just override the default doubleclick behaviour it is
simpler to just use the 'override' keyword.

public class C : Label
{
protected override void OnDoubleClick(EventArgs e)
{
this.Text = "Prueba";
}
}

When a Control gets an event it usually calls a virtual method called
On<eventname> which contains the event behaviour, by overriding this method
you can override the behaviour.

If you just want to add code to the existing behaviour make a call to
base.On<eventmethod> and pass along any parameters you have.
 

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