简体   繁体   English

从儿童表格访问主表格

[英]Accessing Main Form From Child Form

I have a simple problem: I have a main form in win-forms/c#. 我有一个简单的问题:我在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?? 这可能吗??

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类型):

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). 但是上面的方法很简单,并且可能足以满足您的目的(实际上它一种依赖注入本身的形式)。

Scenario 1: Call a method in Parent Form on click of button in child form. 场景1:单击子窗体中的按钮,在父窗体中调用方法。

Create an Event in Child Form. 在子表单中创建一个Event 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. 场景2:关闭子窗体时,在父窗体中调用方法。

Handle the FormClosed or FormClosing event of Child Form in the Parent form and call the parent's form method inside that. 在父表单中处理子表单的FormClosedFormClosing事件,并在其中调用父表单方法。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM