Refresh an open form from another open form

2019-09-27 16:48发布

问题:

I want to refresh an already opened form (form1) from another opened form's (form2) button_click(). In form1 I display the data saved by form2 and when form1 is already opened I want it to refresh if new data is saved on form2 in order to display it.

The problem is that I've tried iterating through `Application.Openforms`, but it turns out that it is read-only and I cannot access the form once found and I don't know how to access *form1* from *form2*, since I can't simply find it.

How can I access *form1* from *form2*?

Edit:

Form1 is actually opened from Form2.

The problem with Application.Openforms is that , as I've stated, a read-only list of forms already opened and I cant actually access the forms through it. They simply don't have the methods for it, I sugest you try using Application.OpenForms and look it up if you don't know how it works. Also it's pointless to show what I've already tried because it includes Application.OpenForms, but for the sake of information:

FormCollection of = Application.OpenForms;
                foreach (var f in of)
                {
                    if (f.GetType().ToString() == "Kontrl_Doc.Visualizar")
                    {
                        f.Refresh();
                    }
                }

When I click the button (button_click()) in Form2 it checks if Form1 is open or not. If Form1 isn't open it opens one and if it is than I'd like it to refresh it. Simultaneously, it closes Form2 and opens Form2 again, in order to reset is fields.

What I wan to do is, if the form1 is already opened , it form2 should tell it to refresh the already opened window with the form 1.

回答1:

you can use events. In form2 you place this code

public event Action ReloadForm1;

//on the place where you will reload form1
ReloadForm1();

and in form1 if you have opening form2:

form2.ReloadForm1 += Reload;

//outside method
void Reload()
{
    this.Reload();
}


回答2:

"Form1 is actually opened from Form2" - If this is the case, then just call Refresh using the form variable that you have in Form2. If necessary, make that a private field in the Form2 class or store it in an array for later use.

For example:

(Somewhere in Form2)

Form1 form1 = new Form1();
form1.Show();

(Inside the button click in Form2)

form1.Refresh();


回答3:

Create a void method in form1 and add the components u want to refresh maybe you want to reload a dropdown from db

public void Refresh()
{
  ...
}

then open a dialog of form2 catch the dialog result