Question

I am looking to refresh form1 when form 2 is closed. I know to use a Closing Event from form2, but thats where I get lost.

Thanks

Was it helpful?

Solution

A good way to achieve this is to use the Mediator pattern. In this way your forms don't have to necessarily know about each other. Allow the Mediator to manage the interaction between the forms so each individual form can concentrate on its own responsibilities.

A very crude Mediator that would achieve what you want could be implemented like so:

public class FormMediator
{
    public Form MainForm { private get; set; }
    public Form SubForm { private get; set; }

    public void InitializeMediator()
    {
        MainForm.FormClosed += MainForm_FormClosed;
    }

    void MainForm_FormClosed(object sender, FormClosedEventArgs e)
    {
        SubForm.Refresh();
    }
}

Now your sub form will update whenever the main form is closed, and neither has to know anything about each other.

EDIT:

Ok, so I am going to put this solution out that will get you started, but please note that this is only a rudimentary implementation of a Mediator pattern. I would highly encourage you to read up about that pattern, and design patterns in general in order to gain a better understanding of what is going on.

Again, this is a sample, but it does have some basic error checking and should get you going.

Your form declaration is going to look something like this:

public partial class MainForm : Form
{
    private FormMediator _formMediator;

    public MainForm()
    {
        InitializeComponent();
    }

    public void SomeMethodThatOpensTheSubForm()
    {
        SubForm subForm = new SubForm();

        _formMediator = new FormMediator(this, subForm);

        subForm.Show(this);
    }
}

And the modified implementation of the Mediator would look like this:

public class FormMediator
{
    private Form _subForm;
    private Form _mainForm;

    public FormMediator(Form mainForm, Form subForm)
    {
        if (mainForm == null)
            throw new ArgumentNullException("mainForm");

        if (subForm == null)
            throw new ArgumentNullException("subForm");

        _mainForm = mainForm;
        _subForm = subForm;

        _subForm.FormClosed += MainForm_FormClosed;
    }

    void MainForm_FormClosed(object sender, FormClosedEventArgs e)
    {
        try
        {
            _mainForm.Refresh();
        }
        catch(NullReferenceException ex)
        {
            throw new InvalidOperationException("Unable to close the Main Form because the FormMediator no longer has a reference to it.", ex);
        }
    }
}

OTHER TIPS

One solution is to pass a reference of Form1 to Form2 in the constructor and just call f1.Invalidate(true) on the closing event of Form2.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top