从子窗体访问主窗体

发布于 2024-10-26 05:08:28 字数 157 浏览 3 评论 0原文

我有一个简单的问题:我在 win-forms/c# 中有一个主窗体。它有一个绑定到数据库的列表框。

当我单击按钮时,会创建一个新表单。

当我单击子窗体上的按钮时,我想调用主窗体中存在的方法,该方法会更新列表框,或者当子窗体关闭时调用该函数。

这可能吗?

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??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冷情妓 2024-11-02 05:08:29

场景 1:在子窗体中单击按钮时调用父窗体中的方法。

在子表单中创建一个事件。在某些按钮单击等上引发该事件。在父表单中订阅该事件并在其中调用父表单方法。

场景2:子窗体关闭时调用父窗体中的方法。

在父表单中处理子表单的 FormClosedFormClosing 事件,并在其中调用父表单的方法。

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

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

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.
    }
旧情别恋 2024-11-02 05:08:28

有很多方法可以实现这一点,但这里有一个简单的方法。在主窗体中,当您创建并显示子窗体时,请执行以下操作:

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

然后,当您需要从子窗体调用主窗体中的方法时,请使用如下代码(假设您的主窗体的类型为 < code>MainForm):

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

一种更复杂的方法是使用依赖注入的形式,您可以在子表单的构造函数中传递对父表单(或更准确地说,对其接口)的引用。但上述方法很简单,并且可能足以满足您的目的(它实际上是依赖注入本身的一种形式)。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文