Search code examples
delphidelphi-xe

Delphi - Already opened tab in pagecontrol


This is about PageControl with dynamic tabs. I have 5 buttons (Button1, Button2, Button3, Button4, Button5).

I want the following:

  1. Each click on a button will open a new TtabSheet.
  2. When clicked on the same button the 'Ttabsheet' already opened, should be shown again.

How to do this?


Solution

  • I don't know why you really want to have five buttons doing the job of creating the tabs and then selecting them, but this is one of the approaches you can try

    uses System.Generics.Collections;
    
    ...
    
    var
    Newtabsheet: Ttabsheet;
    Tabs: TList<Ttabsheet>;
    Index: array[1..5] of Integer;
    Ex: array [1..5] of Boolean;
    
    implementation
    

    Put this on the Formcreate handler

    procedure TForm6.FormCreate(Sender: TObject);
    begin
    Tabs := Tlist<Ttabsheet>.create;
    for I=1 to 5 do ex[I]:=false;
    end;
    

    And this on each OnClickButton event handler

    procedure TForm6.Button1Click(Sender: TObject);
    begin
    if not(Ex[1])then
      begin
      Newtabsheet := Ttabsheet.Create(PageControl1);
      NewTabSheet.PageControl := PageControl1;
      Newtabsheet.Caption := 'Tab 1';
      Index[1] := Tabs.Count;
      Tabs.Add(Newtabsheet);
      Ex[1] := true;
      end
    else
      begin
      Pagecontrol1.ActivePage := Tabs.List[Index[1]];
      end;
    end;
    
    procedure TForm6.FormClose(Sender: TObject; var Action: TCloseAction);
    begin
    Tabs.Free;
    end;
    

    Remember changing the numbers.

    It is tested on RAD studio Seattle.

    Note: based on david comments I have edited my answer. and for further explanation please see this question