0

我正在尝试将信息从子表单传递给父母。我一直在使用我在论坛上找到的以下代码来帮助我:

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

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

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 tempDialog = new Form2(this);
        tempDialog.ShowDialog();
    }

    public void msgme()
    {
        MessageBox.Show("Parent Function Called");
    }

}
}

Form2.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace childform
{
public partial class Form2 : Form
{
    private Form1 m_parent;

    public Form2(Form1 frm1)
    {
        InitializeComponent();
        m_parent = frm1;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        m_parent.msgme();
    }
}
}

哪个有效,一切都很好。麻烦的是,我的程序要求我在 tempDialog 中设置变量,从 Form 1,在 button1_Click 以外的方法中。但是,这些找不到 tempDialog 的实例,因为它在 button1_click 中。

另外,我不能将它移出方法(例如,移入类),因为'this'修饰符不引用 Form1 ...

有什么想法可以从 Form2 中引用 Form1,反之亦然?使用此代码或其他方式?

谢谢

4

3 回答 3

0

You could try researching about MdiParent and Parent properties on the Form object. These allow you to get and set the parent and access their methods if required.

See Parent property and MdiParent property on MSDN for further information.

Hope this helps.

于 2013-05-20T00:02:38.433 回答
0

Depending on your application, if you only ever have one copy of the form that you show and hide in your app, you might just be able to make a singleton static reference. This will only work if you only instantiate the form once however and then use show()/hide() on it to make it dissappear or reappear as required.

public partial class Form2 : Form
{
    public static Form2 Instance;

    public Form2()
    {
        InitializeComponent();
        this.Instance = this;
    }
}

You could then access the form 2 from anywhere by using the code:

Form2.Instance.xxx
于 2013-05-20T00:05:42.650 回答
0

我不知道你的最后评论是什么意思this。在构造函数中创建一个引用Form2并初始化它的字段。然后你可以_form2在其他方法中引用Form1.

public partial class Form1 : Form
{
    private Form2 _form2;
    public Form1()
    {
        InitializeComponent();
        _form2 = new Form2(this);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        _form2.ShowDialog();
    }

}

当复杂性增加时,这种事情会变得难以理解。更好的方法可能是创建Form1Form2引用一些他们都可以操作的公共对象。

于 2013-05-19T23:53:30.833 回答