从子窗体访问主窗体 [英] Accessing Main Form From Child Form

查看:58
本文介绍了从子窗体访问主窗体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题:我在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.

这可能吗?

推荐答案

方案1:单击子窗体中的按钮,然后在父窗体"中调用方法.

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

在子窗体中创建一个 Event .在某些按钮单击"上引发该事件.在父表单"中订阅该事件并在其中调用父表单的方法.

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.

方案2:关闭子窗体后,在父窗体中调用方法.

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

在父表单中处理子表单的 FormClosed FormClosing 事件,并在其中调用父表单的表单方法.

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

这篇关于从子窗体访问主窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆