Passing Data Between 3 Separate WinForms [duplicate]

So the data is first generated on the second child, so on that form we’ll want an event that can be triggered that can provide that data:

public class SecondChildForm : Form
{
    public event Action<MyData> SomethingHappened;

    //Other code, including code that fires the event at some point
}

Then we have the first child which has some method that needs to be called passing in that data:

public class FirstChildForm : Form
{
    public void WhenSomethingHappens(MyData data)
    {
        //Do stuff with data
    }
}

Finally we have the main form that creates both of the forms and wires up the appropriate event handlers:

public class ParentForm : Form
{
    public ParentForm()
    {
        FirstChildForm firstChild = new FirstChildForm();
        SecondChildForm secondChild = new SecondChildForm();

        secondChild.SomethingHappened += firstChild.WhenSomethingHappens;

        //show forms and do other stuff
    }
}

Voila.

Note that using this pattern each child doesn’t know anything about their parent. They expose information needed by the parent through events, and they allow the parent to affect it through public methods, but they don’t know or care which class(es) are using them. The parent does know about it’s child type; it’s appropriate for it to have an instance of the specific child type and to manipulate it’s public members (but not its inner controls, which shouldn’t be public) directly.

Leave a Comment