从MDI父控件访问MDI子控件

时间:2013-02-24 06:43:31

标签: c# winforms textbox

我有一个MDIParent表单,MDIChild表单和名为form1的普通表单,form1继承自MDIChild,而表单一有一个名为textBox1的文本框,以父表单形式我有两个按钮New和Save,当我点击New child form时应该加载,当我点击保存一个消息框时应该弹出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);
}

1 个答案:

答案 0 :(得分:2)

 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());
            }
        }
    }