Reputation: 3515
I have Main form with list of data inside listBox. On button click I'm opening new form to create new data object (Main form is inactive in background), when new data is submitted listobox inside main form should be populated with that new object.
I was thinking following:
Question is:
If Form1 is created and on some event Form2 is instantiated with showDialog so Form1 is inactive until data is submitted how to find Form1 instance before Form2 is closed?
So again, how to find instance of Form1 class from Form2 class?
Thanks
Upvotes: 14
Views: 35819
Reputation: 2015
After getting the instance of an open form, I needed to call a method from that form, so this worked for me:
if (System.Windows.Forms.Application.OpenForms["Form1"] != null)
{
Form1 form1 = Application.OpenForms["Form1"] as Form1;
form1.yourMethodCall();
}
Upvotes: 0
Reputation: 3589
You can get a reference to any of the application's currently open forms by using the Application.OpenForms
property. Forms
in this FormCollection
can be accessed by index like so:
var form1 = Application.OpenForms[0];
or by the form's Name
property like so:
Form form1 = Application.OpenForms["Form1"];
Hope this helps.
Upvotes: 61
Reputation: 710
if you call
Form1.ShowDialog(this)
then you'll be able to get a reference to the calling form with
this.Owner.Name
in the second form (Form2 in your case)
see http://msdn.microsoft.com/en-us/library/system.windows.forms.form.showdialog.aspx
Upvotes: -1