You need an event system between children and parent, which can be accomplished as follows:
- Create a base class for your child forms that contains an event to be raised when any data on the form is changed. Let's call it
FormChanged
event.
- Add an event to the Parent form to notify all children. Let's call it
ChildFormChanged
event.
- Upon instantiation of each child form, have the parent form subscribe to the
FormChanged
event of the child, AND have the new child form subscribe to the ChildFormChanged
event of the parent form.
- The event handler for the
FormChanged
event in the parent form is just a pass-through function, that in turn raises the ChildFormChanged
event, passing the information received from the child form causing the event to fire.
- The
ChildFormChanged
event can be handled in the base class for child forms via a virtual event handler (to handle generic items) that can be overridden in each child class (to handle specifics of each child form).
I wrote and commented an example app in C# and posted it on Github. Here's the relevant code:
Base child Form:
public event EventHandler<EventArgs> FormChanged;
public virtual void ProcessChange(object sender, EventArgs e)
{
if((sender as Form) != this)
{
//Handle change
}
}
protected void NotifyParent() => FormChanged?.Invoke(this, EventArgs.Empty);
Parent form:
public event EventHandler ChildFormChanged;
public void NotifyAllChildren(object sender, EventArgs e)
=> ChildFormChanged?.Invoke(sender, e);
//Child form creation function
private void createNewFormToolStripMenuItem_Click(object sender, EventArgs e)
{
MDIChildBase newChild = new MDIChild(); //Can be different child forms
newChild.MdiParent = this;
//Parent-child event subscription
newChild.FormChanged += NotifyAllChildren;
ChildFormChanged += newChild.ProcessChange;
newChild.Show();
}
Every child form must call base.NotifyParent();
once any changes occur that you want to propagate to other child forms.