Search code examples
arraysformsdelphicode-duplication

Can I store formclass in array? (Delphi)


My current code has lots of code repetition and I want to reduce it by using array so I can just loop thru the array and get the class form that I need to create. For each tabsheet created, it will create a form within it. This is my current code:

 var TabSheet := TcxTabSheet.Create(cxPageControl1);
 TabSheet.Caption := 'Page 1';
 TabSheet.PageControl := cxPageControl1;
 cxPageControl1.Properties.ActivePage := TabSheet;

 with TForm1.Create(nil) do begin
   Parent := TabSheet;
   Height := TabSheet.Height;
   Width := TabSheet.Width;
   Anchors := [akLeft, akTop, akRight, akBottom];
   Show;
 end;

 var TabSheet := TcxTabSheet.Create(cxPageControl1);
 TabSheet.Caption := 'Page 2';
 TabSheet.PageControl := cxPageControl1;

 with TForm2.Create(nil) do begin
   Parent := TabSheet;
   Height := TabSheet.Height;
   Width := TabSheet.Width;
   Anchors := [akLeft, akTop, akRight, akBottom];
   Show;
 end;

//and so on ...

So I thought of reducing it by looping thru an array so that I don't have to retype it again and again. Is there a way I could do this in array? Or do anyone have other suggestion. I tried declaring a var fm: TForm at the top then assigned it like fm := TForm1.Create(nil) at each loop but this way, I couldn't access the methods and component defined in TForm1.


Solution

  • You can do it like this:

    type
      TFormClass = class of TForm;
      TFormDef = record
          FormClass : TFormClass;
          Caption   : String;
      end;
    
    const FormDefs : array [0..1] of TFormDef = (
                         (FormClass : TForm1; Caption : 'Page 1'),
                         (FormClass : TForm2; Caption : 'Page 2')
                     );
    
    var
        FormDef  : TFormDef;
        Form     : TForm;
        TabSheet : TTabSheet;
    begin
        for FormDef in FormDefs do begin
            TabSheet             := TTabSheet.Create(Self);
            TabSheet.Caption     := FormDef.Caption;
            TabSheet.PageControl := PageControl1;
            Form                 := FormDef.FormClass.Create(Self);
            Form.Parent          := TabSheet;
            Form.Width           := TabSheet.Width;
            Form.Height          := TabSheet.Height;
            Form.Anchors         := [akLeft, akTop, akRight, akBottom];
            Form.Show;
        end;
        PageControl1.ActivePageIndex := 0;
    end;