I need help solving the problem below.
I am creating a Windows Forms Application with a MDI interface. In my application, I made a class that basically handles all opening / closing of all child forms, let’s call it FManage. In addition, it also checks to see if a form instance is open. If so, it doesn’t let the user open another instance of the form. This is where my issue lies.
When a window is asked to be opened by a user, FManage the following code:
if (frm1 == null)
{
frmOne = new frm1();
frmOne.MdiParent = Main.ActiveForm; //Main is the parent form
}
frmOne.Show();
Now this code works fine when the window is first opened. Say frm1 is closed and asked to be opened again. The code above is executed again, however, frm1 does not equal NULL. I’ve set a break point at the code above in the FManage class and it shows frm1 != null, even though frm1 was closed. I believe the issue is that frm1, since it is stored as a reference in FManage, is not telling FManage it is null. FManage just stores its initial state of the form, similar to a static variable.
I am new to OOP and am really looking for the best way to solve this issue.
My first solution is that before frm1 closes, possibly in the FormClosing event, send a message back to the FManage class to set frm1 to null; however, in order to do this, the frm1 class would need to know about FManage, which right now it doesn’t. FManage knows about frm1, not the other way around. Sharing is not mutual.
Just for reference, frm1 is defined as a method after my class is defined:
public class FManage
{
frmOne frm1;
...
}
Any suggestions on how to solve this issue would be greatly appreciated.
The key to solve your problem is the subclassing of the FormClosing event.
Set an handler for that event just when you open the form.
Then in that event (if you agree to close) set your global var to null.
This will reset correctly your logic to open a new INSTANCE of frmOne.
Don’t confuse frmOne (the class) with frm1 (the instance of frmOne)