Wednesday, 24 April 2013

Overriding base form control events

This is something that's bugged me for a while, and each time I do this I hit the same problem before the "Oh Yeah!" moment occurs and I remember what I need to do. This is clearly just a problem in my head; something that isn't intuitive for me in someway.

Inherited forms in a WinForms application : overriding the base form's control events so that the base form's event code is not executed, just the code in the derived form.

It's really very simple and I don't know why I struggle with this every time, but I do. So this Blog entry is an Aide Memoire for me.

1. On the base form, select the control in the form designer and make sure the Modifier is set to Protected
2. On the base form, in the code window, mark the event handler as protected void ...

protected virtual void button1_Click( object sender, EventArgs e)
{

    MessageBox
.Show( "Hello" );
}


3. On the derived form, open the designer and double-click the button to add the button1_Click event code
4. Change the new event to protected override void ...

protected override void button1_Click( object sender, EventArgs e)
{

    MessageBox
.Show( "overridden" );
}


5. In the derived form's designer code, you can see that the derived form has subscribed to the Click event again. This means that the code in the derived form's _click event will get run twice - once when the base form click event calls it, and once when the derived form calls it. The fix is to remove the this.button1.Click += new System.EventHandler(this.button1_Click); line
6. If you need to run the code in the base class, you can do this:

    base .button1_Click(sender, e);

No comments:

Post a Comment