I am working a WinForm Application. I have a couple of forms on it. I want to be able to access my main form from any child form. I was able to do that through a custom button function and capture the Form_Closing event. I have one problem though which I'll explain below.
The code on the main form is as follow:
ChildForm form = new ChildForm(); // Create new Child Form instance
form.Show(); // Show Child form
this.Hide(); // Hide Main form
Using "this.Hide();" means that the main form still exists in memory and is still working, it's just hidden which is what I want.
The code on the child form
MainForm form = new MainForm(); // Create new Main Form instance
form.Show(); // Show Main Form
this.Close(); // Close Child Form
This is all well except on my second code block (Child Form directly above), the first line of code, creates a new instance of the main form. That is my problem, I don't want to create a new instance of that form, I want to show the already existing hidden instance (The main form I hid in the first block of code above).
I tried the following code on the Child form:
this.Parent.Show();
But I got this runtime error message: "System.NullReferenceException was unhandled: Message=Object reference not set to an instance of an object".
I understand what the error means, I just don't the code to create an object reference to that main form or how to reference it in any sort.
Any tips please?
Thanks ahead.
You can make a constructor for your other forms that takes in a window as a parameter
where
MyParent
is a property of the formyou can call this via
new ChildForm(this)
Edit
I just looked, not sure why I can't use a constructor for an
IWin32Window
butShow
has an overload that takes one in which will set theOwner
to a parent formThat should do it. Because these are single thread forms, the function will wait till you close the form before proceeding further.
You can also attach ChildForm closing event to function in MainForm.