Accessing the parent Form

20,492

Solution 1

You probably instanciated Form2 from within Form1. After instanciating and BEFORE showing it you could set a property on Form2 that refers to Form1 like this:

Form2 f2 = new Form2();
f2.TheParent = this;
f2.Show();

Of course you have to add the TheParent property to the Form2 class to be able to do that.

Warning: although it is possible this way a better solution might be to create a seperate object that holds all required/shared data andd pass that object to each form in a similar way. This will prevent your code from becoming too coupled.

Solution 2

When the main form instantiates the second form, it could pass a reference to itself to the constructor of the second form.

Thus, the second form will have access to the public members of the first.

EDIT

In the Form1 you instantiate Form2 somewhere and pass it a reference to Form1 in ctor:

Form2 f2 = new Form2(this);

In the class definition of Form2 add a field:

private Form1 m_form = null;

In the constructor of the second form set that field:

public Form2(Form1 f)
{
   m_form = f;
}

Then, everywhere in your Form2 you have access to Form1 through the means of m_form

Share:
20,492
Gilad Naaman
Author by

Gilad Naaman

Updated on September 27, 2020

Comments

  • Gilad Naaman
    Gilad Naaman over 3 years

    I know that the title might seem silly, couldn't think of something better, sorry.

    I have 2 Forms (C#), the main-form holds an instance of the second. Is there a way to.. get access to the running instance of Form1 (The entry point) and to his properties from the instance of form2?

    Everybody tells me to learn OOP. I did, a long long time ago, and I still don"t get it.

  • Gilad Naaman
    Gilad Naaman about 13 years
    Thank you :) That's exactly what I needed to know. I mean, I used the Owner property of the form, but it worked.
  • Emond
    Emond over 11 years
    @IneedHelp - you are correct, I made the property up and unfortunately it already exists. I'll change my answer. Thanks!
  • Brackets
    Brackets almost 7 years
    Why not just write public Form1 m_form;?