Accessing Main Form From Child Form

2019-02-13 21:45发布

问题:

I have a simple problem: I have a main form in win-forms/c#. It has a listbox bound to a database.

When I click a button a new form is created.

When I click a button on the child form, I want to call a method that exists in the main form, that updates the list box or alternatively when the child form closes, to call that function.

Is this possible??

回答1:

Scenario 1: Call a method in Parent Form on click of button in child form.

Create an Event in Child Form. Raise that event on some Button Click etc. Subscribe to that event in your Parent Form and call the parent's form method inside that.

Scenario 2: Call a method in Parent Form when Child Form is closed.

Handle the FormClosed or FormClosing event of Child Form in the Parent form and call the parent's form method inside that.

ChildForm frm = new ChildForm();
frm.FormClosed += new FormClosedEventHandler(frm_FormClosed);

void frm_FormClosed(object sender, FormClosedEventArgs e)
    {
        //Call your method here.
    }


回答2:

There are many ways to achieve this, but here's a simple way. In your main form, when you create and show a child form, do it like this:

ChildForm child = new ChildForm();
child.Show(this); // this calls the override that takes Owner parameter

Then, when you need to call a method in the main form from the child form, use code like this (assumes your main form is of type MainForm):

MainForm parent = (MainForm)this.Owner;
parent.CallCustomMethod();

A more complex way would be to use a form of dependency injection, where you would pass in a reference to the parent form (or more properly, to its interface) in the constructor of the child form. But the above way is simple and probably effective enough for your purposes (and it actually is a form of dependency injection itself, sort of).