Achilles Stand
Achilles Stand

Reputation: 67

inheritance between buttons C# - windows form

I have a doubt simple principle in C # windows form. I have two forms: FormA and FormB. The formA has buttonA button with one messagebox => MessageBox.Show ("FormA");

The FormB is inherited from FormA whose buttonA changed so I can write another messagebox => Console.WriteLine ("FormB");

Until then all right, but I need the event of FormB button to run before the button FormA the event, ie: First MessageBox.Show ("FormB") then MessageBox.Show ("FormA");

How do I do that?

Upvotes: 2

Views: 1272

Answers (2)

rufanov
rufanov

Reputation: 3276

Just call event handler of base class from overridden event handler in derived class:

using System;
using System.Windows.Forms;

namespace TestApp
{
    public class FormA : Form
    {
        private readonly Button buttonA;

        public virtual void ButtonAClick(object sender, EventArgs e)
        {
            MessageBox.Show("FormA");
        }

        public FormA()
        {
            this.buttonA = new Button()
            {
                Text = "buttonA",
                Top = 10,
                Left = 10
            };
            this.buttonA.Click += ButtonAClick;
            this.Controls.Add(buttonA);
        }
    }

    public class FormB : FormA
    {
        public override void ButtonAClick(object sender, EventArgs e)
        {
            MessageBox.Show("FormB");
            base.ButtonAClick(sender, e);
        }
    }

    class Program
    {
        public static void Main(string[] args)
        {
            Application.Run(new FormB());
        }
    }
}

Upvotes: 1

nvoigt
nvoigt

Reputation: 77285

You can call the base method by using the base keyword.

Lets assume you have a FormB inheriting from FormA and you have overridden the Button1Click method:

public override void Button1Click(object sender, EventArgs e)
{
   // execute the base class code first
   base.Button1Click(sender, e);

   // call your code specific for B
}

However, using inheritance for this seems strange, maybe if you describe your problem, we can find a better solution than this.

Upvotes: 1

Related Questions