2008. március 6., csütörtök

Find the parent TTabSheet of a control


Problem/Question/Abstract:

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:

function GetParentTabsheet(C: TControl): TTabsheet;
begin
  Result := TTabSheet(C.Parent);
  while (Result <> nil) and not Result.InheritsFrom(TTabSheet) do
    Result := TTabSheet(Result.Parent);
end;

If you really want it recursive:

function GetParentTabsheet(C: TControl): TTabsheet;
begin
  Result := TTabSheet(C.Parent);
  if (Result <> nil) and not Result.InheritsFrom(TTabSheet) then
    Result := GetParentTabsheet(Result);
end;


Solve 2:

function GetParentTabSheet(Control: TControl): TTabSheet;
begin
  while Assigned(Control) and not (Control is TTabSheet) do
    Control := Control.Parent;
  Result := TTabSheet(Control);
end;


Solve 3:

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage(TTabSheet(TGroupBox(Edit1.Parent).Parent).Caption);
end;

Nincsenek megjegyzések:

Megjegyzés küldése