Senin, 22 Juli 2013

How to prevent duplicate child forms in windows forms C#

In my previous post we have create an MDI container form in which we have opened some individual forms called child forms. Each form contains a property MdiParent that is used to get or set the parent form of a particular form.
Form2 obj = new Form2();
obj.MdiParent = this;
obj.Show();

As we know, in MDI container application user opens multiple child forms at a time. Most often when user opens a child form, application opens a new instance of the form, doesn't matter the form is previously opened or not. This is programmer’s job to check if the same form is previously opened then bring that form to front otherwise create a new instance.

To check the instance is null or not we have to write following code in our code behind file of form that will be the child form.
private static Form3 instance;
public static Form3 GetInstance()
{
if (instance == null)
instance = new Form3 ();
return instance;
}

In above code we have defined a new object of type Form3. Each time when we call this method it will check this object whether it is null or not. If this is null it will create a new instance of the form otherwise it simply return that object.

Our next task is to set the value of that instance to null each time user closes that form. Each form has a FormClosing event which occur whenever user closes the form, before the form will closed. We will set the instance to null in this FormClosing event of the form.
Instance = null;

In the MDI parent form replace the above three line of code with the following code:
Form3 obj = Form3.GetInstance();
obj.MdiParent = this;

if (!obj.Visible)
obj.Show();
else
obj.BringToFront();

Through the above code we will use the newly defined method i.e. GetInstance() in place of its constructor. Now when user opens this child form it will check that if that form is visible then it will bring that in front otherwise display the form to user using show method.

Tidak ada komentar:

Posting Komentar