Author: Tomas Rutkauskas
I am trying to write a recursive function that will go through all the parents of a
component until it finds the tabsheet that it is on (ie: TEdit -> TGroupBox ->
TTabSheet). Then I would like to get the caption of that tabsheet.
Answer:
Solve 1:
If you walk the tree up - from root - you need recursion, but the opposite way is
linear as each element (control) has only one immediate parent, so recursion would
be nonsense. A code like this should do:
1 function GetParentTabsheet(C: TControl): TTabsheet;
2 begin3 Result := TTabSheet(C.Parent);
4 while (Result <> nil) andnot Result.InheritsFrom(TTabSheet) do5 Result := TTabSheet(Result.Parent);
6 end;
If you really want it recursive:
7 function GetParentTabsheet(C: TControl): TTabsheet;
8 begin9 Result := TTabSheet(C.Parent);
10 if (Result <> nil) andnot Result.InheritsFrom(TTabSheet) then11 Result := GetParentTabsheet(Result);
12 end;
Solve 2:
13 function GetParentTabSheet(Control: TControl): TTabSheet;
14 begin15 while Assigned(Control) andnot (Control is TTabSheet) do16 Control := Control.Parent;
17 Result := TTabSheet(Control);
18 end;
Solve 3:
19 procedure TForm1.Button1Click(Sender: TObject);
20 begin21 ShowMessage(TTabSheet(TGroupBox(Edit1.Parent).Parent).Caption);
22 end;