Recent

Author Topic: How do I find a form and component by name  (Read 415 times)

Josh

  • Hero Member
  • *****
  • Posts: 1273
How do I find a form and component by name
« on: May 20, 2022, 07:01:21 pm »
Hi

How can I find a component by its name which is on a form by its name.

ie
var frm_name='frm1';  and cmp_name=' pan1';

i have tried code below but the component is not found, the form is found though.
Code: Pascal  [Select][+][-]
  1. function FindFormByName(const AName: string): TForm;
  2. var
  3.   i: Integer;
  4. begin
  5.   for i := 0 to Screen.FormCount - 1 do
  6.   begin
  7.     Result := Screen.Forms[i];
  8.     if (Result.Name = AName) then
  9.       Exit;
  10.   end;
  11.   Result := nil;
  12. end;
  13.  
  14. ...
  15. var frm:tform;
  16.       pnl:tpanel;
  17.  
  18. begin
  19.   frm:=FindFormByName('Frm1');
  20.   if frm<>nil then
  21.   begin
  22.     pnl:=frm.findcomponent('Pan1');
  23.     if pnl=nil then showmessage('Pan1 not found on Frm1')
  24.     else
  25.     begin
  26.        ....
  27.     end;
  28. end;      
  29.  
The best way to get accurate information on the forum is to post something wrong and wait for corrections.

wp

  • Hero Member
  • *****
  • Posts: 11906
Re: How do I find a form and component by name
« Reply #1 on: May 20, 2022, 07:16:01 pm »
You say "the component is not found". I think this is not true since you cannot even compile this code. The return value of FindComponent is TComponent, but you assign this to a TPanel variable. This is rejected by the compiler because a TComponent can be "anything", not necessarily a TPanel. Better to work with a TComponent variable, check whether this is a TPanel and cast the TComponent to a TPanel:
Code: Pascal  [Select][+][-]
  1. var
  2.   frm:tform;
  3.   pnl:tpanel;
  4.   c: TComponent;
  5. begin
  6.   frm:=FindFormByName('Frm1');
  7.   if frm<>nil then
  8.   begin
  9.     c := frm.findcomponent('Pan1');
  10.     if c=nil then
  11.       showmessage('Pan1 not found on Frm1')
  12.     else
  13.     if not (c is TPanel) then
  14.       showmessage('Pan1 found on Frm1, but it is not a TPanel')
  15.     else
  16.     begin
  17.       pnl := TPanel(c);
  18.        ....
  19.     end;
  20. end;

 

TinyPortal © 2005-2018