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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With