从MDI父控件访问MDI子控件

本文关键字:控件 MDI 访问 | 更新日期: 2023-09-27 18:00:41

我有一个MDIParent表单、MDIChild表单和一个称为form1的普通表单,form1继承自MDIChild,表单一有一个名为textBox1的文本框,在父表单中,我有两个按钮"新建"answers"保存",当我单击"新建"时,应该加载子表单,当我点击"保存"时,会弹出一个带有textbox1.text值的消息框,问题是弹出的消息框中没有textbox1文本值

我正在使用以下代码在父窗体中加载子窗体。

public partial class MDIParent1 : Form
{
    MdiClient mdi = null;
    string fname;
    public MDIParent1()
    {
        InitializeComponent();
        foreach (Control c in this.Controls)
        {
            if (c is MdiClient)
            {
                mdi = (MdiClient)c;
                break;
            }
        }
    }
}

我过去用下面的代码[点击新按钮]调用加载表单功能

private void ShowNewForm(object sender, EventArgs e)
{
    load_form(new Form1());
}

加载表单功能是

private void load_form(object form)
{
    foreach (Form f in mdi.MdiChildren)
    {
        f.Close();
    }
    if (form == null)
        return;
    ((Form)form).MdiParent = this;
    ((Form)form).Show();
    ((Form)form).AutoScroll = true;
    fname = ((Form)form).Name;
}

我的表格正在加载。。在保存按钮onClick函数中,我调用了名为getdata() 的form1函数

public void getdata()
{
    messageBox.show(textBox1.text);
}

从MDI父控件访问MDI子控件

 public partial class MDIChild : Form
    {
        public virtual string GetMessage()
        {
            return this.Name;
        }    
    }
    public class Form2 : MDIChild
    {
        TextBox textBox1 = new TextBox();
        public override string  GetMessage()
        {
            return textBox1.Text;
        }
    }

    public partial class MDIParent1 : Form
    {
        private MdiClient mdi = null;
        private string fname;
        private MDIChild currentActiveChild;
        public MDIParent1()
        {
            base.InitializeComponent();
            foreach (Control c in this.Controls)
            {
                if (c is MdiClient)
                {
                    mdi = (MdiClient) c;
                    break;
                }
            }
        }
        private void ShowNewForm(object sender, EventArgs e)
        {
            currentActiveChild = new Form2();
            load_form(currentActiveChild);
        }
        public void getdata()
        {
            if (currentActiveChild != null)
            {
                MessageBox.Show(currentActiveChild.GetMessage());
            }
        }
    }