Search code examples
winformsloopsforeachruntimemdi

Create Cascade Form via MDI at runtime via looping a list


I have a list that I use a foreach loop to create forms. I am trying to get the forms to cascade. I've been trying to use the MDI container and set the parent form if it meets a condition. I would like to know if Child MDI forms can only be created inside the parent and not via a loop.

E.g

List<string> FormNames;
FormNames.add("Cat Group");
FormNames.add("Big Cats")
FormNames.add("Medium Cats")
FormNames.add("Small Cats")

Foreach(string Name in FormNames)
{
  FormA NewForm = new FormA(Name);
  
  if(NewForm.Name == "Cat Group") <--- This sets the ParentForm if conditions are met.
  {
     NewForm.IsMdiContainer = true; 
     NewForm.Layout(MdiLayout.Cascade);
  }
  else
  {
     NewForm.IsMdiContainer = false;
     NewForm.MDIParent = <-----(what do I put here? I can't put NewForm or else it would reference itself. 
  }
  
  NewForm.Show(); 





  

Solution

  • You just need the help of another variable of your Form. Set this variable to be the reference to the NewForm when you build the MDIContainer and then use it when you create the MdiChilds

    List<string> FormNames = new List<string>();
    FormNames.Add("Cat Group");
    FormNames.Add("Big Cats");
    FormNames.Add("Medium Cats");
    FormNames.Add("Small Cats");
    
    Form parent = null;
    foreach (string Name in FormNames)
    {
        Form NewForm = new Form();
        NewForm.Name = Name;
        if (NewForm.Name == "Cat Group") 
        {
            NewForm.IsMdiContainer = true;
            parent = NewForm;
            parent.LayoutMdi(MdiLayout.Cascade);
        }
        else
        {
            NewForm.IsMdiContainer = false;
            NewForm.MdiParent = parent;
            NewForm.Show();
        }
    }
    parent.Show();