HelloWorld_Always
HelloWorld_Always

Reputation: 1565

why does overriding method executes twice instead of once in c#?

I have a base class and a derived class . The base class has a simple button with a virtual protected button click method.

I am using the ovverride keyword (not using new as i want the buttonclick method in the derived class to override the base class buttonclick method)

However , the code inside the derived class buttonclick method executes twice instead of once

Here is the code example

In the Base Class:

this.ok.Click += new System.EventHandler(this.ok_Click);
    protected virtual void ok_Click(object sender, EventArgs e)
            {
                MessageBox.Show("From the Base class");
            }

In the Derived Class:

 this.ok.Click += new System.EventHandler(this.ok_Click);
 protected override void ok_Click(object sender, EventArgs e)
            {
                MessageBox.Show("From the Derived class");
            }

Upvotes: 0

Views: 1409

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500525

You haven't said what's actually calling the buttonclick method, but I suspect it's an event handler... and I suspect you're subscribing to it in both the subclass and base class constructors. Don't do that - you only need to subscribe once.

(If that's not the case, please show a short but complete example.)

Upvotes: 6

Related Questions