Alfie Hillier
Alfie Hillier

Reputation: 49

C# How do I pass a method to base WinForm button click event

I have a WinForm application which has 5 forms. From the main form there are three buttons which each load a form with essentially the same design and layout. For this reason I have created a base form from which these will inherit.

Each of the child forms will have a LoadData button which will be inherited from the base form. What I am trying to do is to call the click event of that button on that base form and execute a different method dependent on what child form is being used. Rather than having the form specific click event on each form.

So essentially I want to do something like this in the child forms. But I have no idea how to do it. Everything I read confuses me.


protected override BaseFormOnClick()
{
    LoadDataSet1
}

I also want to be able to inherit the drag drop event which is on the base form. I am guessing I need to subscribe to it but I cant seem to get it work. So something like this.


public DerivedForm() : base()
{
    base.Drag_Drop_Event(EventArgs.Empty)
}

Just started looking at event handlers and delegates so any help would be greatly appreciated.

Upvotes: 0

Views: 865

Answers (2)

Edson Marcio
Edson Marcio

Reputation: 26

BaseForm:

private void btnOk_Click(object sender, EventArgs e)
{
    SaveUpdates();
}
public virtual void SaveUpdates()
{
}


ChildForm:
public override void SaveUpdates()
{
    MessageBox.Show("Save items");
}

Upvotes: 0

Peter Duniho
Peter Duniho

Reputation: 70671

Please limit your question posts to one question at a time.

For the first one, it should be as simple as declaring in the base class:

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

and then in each derived class, override it:

protected override void button1_Click(object sender, EventArgs e)
{
    // do button stuff here
}

Just subscribe to the base class method for the button's Click event in the base class itself. E.g.:

// Constructor
protected BaseForm()
{
    InitializeComponent();
    button1.Click += button1_Click;
}

In theory, you should be able to make the base class method abstract instead of virtual, but I'm not sure how well the Winforms Designer will accommodate an abstract base class like that.

As always with virtual methods, if you want the base class to do something as well when the button is clicked, you will need to stick with virtual, and include a call to base.button1_Click(sender, e); in the derived class implementations.

Honestly, I feel confident there's a question with an answer already on the site that addresses this, but for the life of me I could not find it.

If you have trouble extrapolating from the simple button case to how to handle drag-and-drop, please ask that as a separate question, showing a minimal, complete example of what you have so far and explaining what specifically you need help with.

Upvotes: 2

Related Questions