Dumbo
Dumbo

Reputation: 14132

How to update a control in MDI parent form from child forms?

I looked to some similar questions but I didn't really get my answer, so I ask again hopefuly someone can explain it.

The situation:

I have a MDI form that has some menues and a status bar and stuff like that. Is the only way of altering text for status bar and doing other things to the parent form is to call it as static? Or if not, can you please give an example for updating (for example) status bar that exist in parent form within the child forms?

Thanks!

Upvotes: 1

Views: 6321

Answers (3)

Veldmuis
Veldmuis

Reputation: 4868

Another option is to use events (you can build these events into a base class and let all your child forms inherit from it):

// Code from Form 1
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        Form2 objForm2 = new Form2();
        objForm2.ChangeStatus += new ChangeStatusHandler(objForm2_ChangeStatus);
        objForm2.Show();
    }
    public void objForm2_ChangeStatus(string strValue)
    {
        statusbar.Text = strValue;
    }
}

// Code From Form 2
public delegate void ChangeStatusHandler(string strValue);
public partial class Form2 : Form
{
    public event ChangeStatusHandler ChangeStatus;

    public Form2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (PassValue != null)
        {
            PassValue(textBox1.Text);
        }
    }
}

Upvotes: 2

Lloyd
Lloyd

Reputation: 2942

The Form class already exposes a property MdiParent ensure the parent forms IsMdiContainer property is set accordingly.

Upvotes: 3

SLaks
SLaks

Reputation: 887957

You need to make the child forms take a parent form instance as a constructor parameter.
The children can save this parameter to a private field, then interact with the parent at will later.

For optimal design, you should abstract the parent from the child through an interface implemented by the parent, containing methods and properties that do what the children need. The children should then only interact with this interface.

public interface IChildHost {
    void UpdateStatusBar(string status);
    //Other methods & properties
}

public partial class ParentForm : IChildHost {
    public void UpdateStatusBar(string status) {
        ...
    }
    //Implement other methods & properties
}

public partial class ChildForm {
    readonly IChildHost host;
    public ChildForm(IChildHost parent) {
        this.host = parent;
    }

}

Upvotes: 3

Related Questions