调用父表单函数?

JBu*_*ace 1 c# winforms

我有一个带有2个表单的C#窗口程序.基本表单(Form1)具有刷新(RefreshView)视图的功能.单击按钮将调出Form2.单击Form2上的"应用"按钮后,如何调用RefreshViewForm1中存在的函数?两种形式都由用户打开.

Form1代码Form1.cs:

namespace MonitorCSharp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public void RefreshView()
        {
            //refresh code etc
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

表格2 Form2.cs:

namespace MonitorCSharp
{
    public partial class Form2 : Form
    {
        public Form2(String args)
        {
            InitializeComponent();
            form2Text = args;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.Close();
            //I want to refresh here
        }
}
Run Code Online (Sandbox Code Playgroud)

我尝试了各种代码,包括:

((Form1)this.ParentForm).RefreshView();
Run Code Online (Sandbox Code Playgroud)

要调用刷新函数,但到目前为止一切都给了我一个运行时错误.我错过了什么吗?

我没有编译错误.运行时错误是:

A first chance exception of type 'System.NullReferenceException' occurred in MonitorCSharp.exe
An unhandled exception of type 'System.NullReferenceException' occurred in MonitorCSharp.exe
Additional information: Object reference not set to an instance of an object.
Run Code Online (Sandbox Code Playgroud)

Ser*_*rvy 5

父表单可以将事件处理程序附加到它的子FormClosed事件处理程序,以便在关闭时执行代码:

public partial class Form1 : Form
{
    public void Foo()
    {
        Form2 child = new Form2();
        child.FormClosed += (s, args) => RefreshView();
        child.Show();
    }

    public void RefreshView()
    {
        //refresh code etc
    }
}
Run Code Online (Sandbox Code Playgroud)