Link to home
Start Free TrialLog in
Avatar of klompen
klompen

asked on

Creating new TTabSheet dynamically

Hi,

I have a TPageControl in the main form. How do I add a new page (TTabSheet) and its contents dynamically ?

For example, when a user click a button, a new page will be added. The new page will have a TPanel and inside the TPanel will have a TMemo.

Also, the new page can be deleted including all its objects, for example by using a delete button.

Please if someone can show me some codes how to do this.

Thanks.
Avatar of atul_parmar
atul_parmar
Flag of India image

// Add Tab
var
  MyTab : TTabSheet;
begin
  MyTab := TTabSheet.Create(PageControl1);
  PageControl1.InsertControl(MyTab);
  MyTab.PageControl := PageControl1;
  MyTab.Caption := 'MyTab';
  MyTab.TabVisible := True;
end;

// delete tab
var
  MyTab : TTabSheet;
begin
  MyTab := PageControl1.ActivePage;
  MyTab.PageControl := nil;
  MyTab.Free;
end;
Avatar of klompen
klompen

ASKER

I am confuse with "local variable" and "global variable".

If I create the button onclick like this :

procedure TMyForm.Button1Click ....
// Add Tab
var
  MyTab : TTabSheet; // LOCAL ???
begin
  MyTab := TTabSheet.Create(PageControl1);
  PageControl1.InsertControl(MyTab);
  MyTab.PageControl := PageControl1;
  MyTab.Caption := 'MyTab';
  MyTab.TabVisible := True;
end;

Does it "MyTab" only available in the scope of procedure TMyForm.Button1Click ... ???

I want MyTab and its contents available troughout the entire applications.
And one correction to the above code, It does not require
PageControl1.InsertControl(MyTab);
>>I am confuse with "local variable" and "global variable".

The variable is local but the tab will remain there because it is created and associated while button click. The memory allocated for the tabsheet is not deallocated so it will remain there
e.g.
MyTab := TTabSheet.Create(PageControl1);
Avatar of klompen

ASKER

Why is it not deallocated after the procedure finished ?

And how about creating the contents of the tab ?
ASKER CERTIFIED SOLUTION
Avatar of atul_parmar
atul_parmar
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
MyTab is just a pointer, so it is ok if it drops out of scope in the procedure, the object stays alive. however it's owner will free it when it is freed itself
Avatar of klompen

ASKER

So, if I delete a tab, all the contents in that tab will be free-ed (deleted as well) automatically right ?
Yes, atul_parmar's answer is correct.
1 final note in response to the author's last question (don't accept this, just atul_parmar's)
If the components on the Tab have the tab as the owner, (which they are in the example above "MyPanel := TPanel.Create(MyTab);" )
then yes, they will be free-ed when the tab is free-ed