If you do not use the MDI to implement a main form to open more than one subform,
To open one (only one) other form (subform) from one form (the main form)
Parent form: MainForm
public partial class Mainform:form
{
............
private void Menuitem1_load (Object Sender,eventargs e)
{
ChildForm child1=childform.create ();
Child1.show ();
Child1. Focus ();
}
//......
}
Child form: ChildForm
public partial class Childform:form
{
.....
static ChildForm child;
public static ChildForm Create ()
{
if (child==null)
Child=new ChildForm ();
return to child;
}
......
}
After the F5 runs, it does realize the functions mentioned above. However, when the handle form closes, when you want to open the subform again, when you click the menu item, an exception occurs: ObjectDisposedException was unhandled.
What is this for??
This involves the C # garbage collection issue:
Garbage collection is. NET Run-time Library. The garbage collector manages all managed objects, all of which require managed data. NET languages, including C #, are constrained by the runtime's garbage collector. The garbage collector can determine the best time to run garbage collection and automatically garbage collection. One of the products of garbage collection, however, is that C # objects are not deterministic. As a result, the object child has been destroyed, but is not null, resulting in a ObjectDisposedException exception when accessed.
What to do??
Method: The resources of the child should be recycled thoroughly.
There are two ways:
Method One:
To modify the constructor of a subform
Public ChildForm ()
{
//.........
This. Disposed+=new System.EventHandler (form_disposed)
}
Then the handler function for the event form_disposed
private void Form_disposed (Object Sender,eventargs e)
{
Child=null;
}
Method Two:
The onclosed method of rewriting ChildForm
Protected void onclosed (EventArgs e)
{
Base. Onclosed (e);
Child=null;
}
Of course, there may be other ways, and you will be interested to add. In addition to the improper description of the place, please advise, in the next grateful.