Accessing Main Form From Child Form

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-30 08:41:43

问题


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).



来源:https://stackoverflow.com/questions/5443932/accessing-main-form-from-child-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!