Loop through MDI chlids

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

How do I loop through all opened child forms of a MDI parent, and how do I
check weather the child form is of a specific type or not.

/Steffo
 
Here are a few different ways to do it. I personally think
that using a "for" loop is more efficient than using
a "foreach", but it is up to you. The code below is
assuming that you're coding is within the MDI form.
The "MyCustomForm" is just an example of a form that you
may have derived from System.Windows.Forms.Form.

examle:

public class MyCustomForm : System.Windows.Forms.Form
{
}


foreach(Form form in this.MdiChildren)
{
if(form is MyCustomForm)
{
//do your code here
}
}

or

foreach(Form form in this.MdiChildren)
{
if(form == typeof(MyCustomForm))
{
//do your code here
}
}

or

for(int index = 0;index < this.MdiChildren.Length;index++)
{
if(this.MdiChildren[index] is MyCustomForm)
{
//place code here
}
}

or

for(int index = 0;index < this.MdiChildren.Length;index++)
{
if(this.MdiChildren[index] == typeof(MyCustomForm))
{
//place code here
}
}
 
Hi,
Just minor corrections and suggestions.
Here are a few different ways to do it. I personally think
that using a "for" loop is more efficient than using
a "foreach", but it is up to you.

I think you don't have to worry about the efficiency of *foreach* loops. MS
say the will make foreach at least as efficient as *for* loops. Usually if
the application works slow it is not because of using *foreach*. My
suggestion is - use *foreach* whenever you want to.
public class MyCustomForm : System.Windows.Forms.Form
{
}


foreach(Form form in this.MdiChildren)
{
if(form is MyCustomForm)
{
//do your code here
}
}
Usually when you want to filter out forms of some type you want to use them
afterwards.
In this case is better to use *as* instead of *is* because eventually you
will want to cast to that type. All type casting as well as *is* operator do
almost the same amount of work.

If you are going to cast the type my suggestion is

MyCustomForm mcf = form as MyCustomForm;
if(ncf != null)
{
//do something here
}
foreach(Form form in this.MdiChildren)
{
if(form == typeof(MyCustomForm))
{
//do your code here
}
}
I think this is technical mistake the type check has to be
if(form.GetType() == typeof(MyCustomForm))
{

}

the same goes for the example with the *for* loop

B\rgds
100
 
Back
Top