Events in classes

  • Thread starter Thread starter Alberto
  • Start date Start date
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.
 
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.
 
Back
Top