How can I get form1 to update when I close form2

I want to update form1 when form 2 is closed. I know what to use the Closing Event from form2, but this is where I get lost.

thanks

+3
source share
2 answers

A good way to achieve this is to use a reseller template. Thus, your forms do not need to know about each other. Let the Mediator manage the interaction between the forms so that each individual form can focus on its own responsibilities.

A very rude mediator who would achieve what you want can be implemented like this:

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();
    }
}

, , .

EDIT:

, , , , . , , .

, , .

:

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);
    }
}

:

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);
        }
    }
}
+4

- Form1 Form2 f1.Invalidate(true) 2.

+2

Source: https://habr.com/ru/post/1709450/


All Articles