Single Instance of Child Forms in MDI Applications

22. February 2010 00:40

C#  1 Comment

In MDI application we can have multiple forms and can work with multiple forms i.e. MDI childs at a time but while developing applications we don't pay attention to the minute details of memory management. Take this as an example, when we develop application say preferably an MDI application, we have multiple child forms inside one parent form. On MDI parent form we would like to have menu strip and tab strip which in turn calls other forms which build the other parts of the application. This also makes our application looks pretty and eye-catching (not much actually). Now on a first go when a user clicks a menu item or a button on a tab strip an application initialize a new instance of a form and shows it to the user inside the MDI parent, if a user again clicks the same button the application creates another new instance for the form and presents it to the user, this will result in the un-necessary usage of the memory. Therefore, if you wish to have your application to prevent generating new instances of the forms then use the below method which will first check if the the form is visible among the list of all the child forms and then compare their types, if the form types matches with the form we are trying to initialize then the form will get activated or we can say it will be bring to front else it will be initialize and set visible to the user in the MDI parent window. The method we are using:

private bool CheckForDuplicateForm(Form newForm)
{
     bool bValue = false;
     foreach (Form frm in this.MdiChildren)
     {
         if (frm.GetType() == newForm.GetType())
         {
             frm.Activate();
             bValue = true;
         }
      }
      return bValue;
}

Usage: First we need to initialize the form using the NEW keyword

ReportForm ReportForm = new ReportForm();

We can now check if there is another form present in the MDI parent. Here, we will use the above method to check the presence of the form and set the result in a bool variable as our function return bool value.

bool frmPresent = CheckForDuplicateForm(Reportfrm);

Once the above check is done then depending on the value received from the method we can set our form.

if (frmPresent)
	return;
else if (!frmPresent)
{
    Reportfrm.MdiParent = this;
    Reportfrm.Show();
}

In the end this is the code you will have at you menu item or tab strip click:

ReportForm Reportfrm = new ReportForm();
bool frmPresent = CheckForDuplicateForm(Reportfrm);
if (frmPresent)
return;
else if (!frmPresent)
{
    Reportfrm.MdiParent = this;
    Reportfrm.Show();
}
Currently rated 3.5 by 4 people

Comments (1)

Yogesh Yogesh
10/28/2011 2:39:15 PM #

Hi , This was a nice post.. But instead of this way of doing we can implement singleton pattern for child forms. Thanks, Yogesh

Add Comment

Visit blogadda.com to discover Indian blogs Computers Blogs