Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing the parent Form

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.

like image 872
Gilad Naaman Avatar asked Dec 07 '22 23:12

Gilad Naaman


2 Answers

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

like image 189
tzup Avatar answered Dec 28 '22 23:12

tzup


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.

like image 33
Emond Avatar answered Dec 29 '22 01:12

Emond