通过MDI Parent表单元素访问MDI子表单函数

时间:2013-03-01 14:08:38

标签: c# mdichild mdiparent

我有一个MDIChild表单,名为form1的普通表单继承自MDIChild表单和MDIParent表单,MDIParent顶部有一个工具栏{000}在该工具栏中有一个新按钮,当我点击新按钮时,它会加载父窗体内工具栏下方的form

Form1内有TextBox,当我点击保存按钮时form1的值 应通过调用其函数

显示在TextBox

但问题是我无法访问MessageBox TextBox属性??

我的MDIParent表单代码是

Text

我的form1代码是

 public partial class MDIParent1 : Form
{
   // private int childFormNumber = 0;
    MdiClient mdi = null;
    string fname;



    public MDIParent1()
    {
        InitializeComponent();
        foreach (Control c in this.Controls)
        {
            if (c is MdiClient)
            {
                mdi = (MdiClient)c;
                break;
            }
        }
    }

  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;



    }

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

 private void saveToolStripButton_Click(object sender, EventArgs e)
    {
        if (fname == "Form1")
        {
            Form1 f1 = new Form1();
            f1.show_message();

        }


    }

我的MDIChild表单代码是

public void show_message()
    {
        MessageBox.Show(textBox1.Text);
    }

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

我理解你正在做些什么来访问MDIChild表单数据。试试这个: -

 private void ShowNewForm(object sender, EventArgs e)
    {
        Form childForm = new Form();
        childForm.MdiParent = this;
       // childForm.ContextMenuStrip = contextMenuStrip1;
        //this.contextMenuStrip1.ResumeLayout(false);
        RichTextBox text = new RichTextBox();
        text.Dock = DockStyle.Fill;
        childForm.Controls.Add(text);
        childForm.Text = "Page  " + this.MdiChildren.Count();
        childForm.Show();
    }

    private void OpenFile(object sender, EventArgs e)
    {
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
        openFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
        if (openFileDialog.ShowDialog(this) == DialogResult.OK)
        {
            string FileName = openFileDialog.FileName;
        }
    }
    private void SaveAsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        SaveFileDialog saveFileDialog = new SaveFileDialog();
        saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
        saveFileDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
        if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
        {
            string FileName = saveFileDialog.FileName;
        }
    }