whats new ¦  programming tips ¦  indy articles ¦  intraweb articles ¦  informations ¦  links ¦  interviews
 misc ¦  tutorials ¦  Add&Win Game

Tips (1541)

Database (90)
Files (137)
Forms (107)
Graphic (114)
IDE (21)
Indy (5)
Internet / LAN (130)
IntraWeb (0)
Math (76)
Misc (126)
Multimedia (45)
Objects/
ActiveX (51)

OpenTools API (3)
Printing (35)
Strings (83)
System (266)
VCL (242)

Top15

Tips sort by
component


Search Tip

Add new Tip

Add&Win Game

Advertising

28 Visitors Online


 
...find a component by it's name ?
Autor: Thomas Stutz
[ Print tip ]  

Tip Rating (61):  
     


{Instead of writing: / Anstatt so was zu schreiben:}

Edit1.Text := 'Text 1';
Edit2.Text := 'Text 2';
Edit3.Text := 'Text 3';
Edit4.Text := 'Text 4';
{...}
Edit9.Text := 'Text 9';

{...it's easier to write / ...geht's so einfacher:}

{
  Use the forms FindComponent to find a component on the form.
  TypeCast the Result of FindComponent to the TComponent to be able to use it.
}


for i := 1 to do
  
TEdit(FindComponent('Edit'+IntToStr(i))).Text := 'Text' + IntToStr(i);

{or/oder:}

for i:= 1 to do
  
(Findcomponent('Edit'+IntToStr(i)) as TEdit).Text := IntToStr(i);



{
  Another example: find a component on any form with
  a search string like this: 'MyForm10.Edit2'

  Ein anderes Beispiel:
  Eine Komponente auf irgendeiner Form finden mittels einer
  solchen Zeichenfolge: 'MyForm10.Edit2'
}

function FindComponentEx(const Name: string): TComponent;
var
  
FormName: string;
  CompName: string;
  P: Integer;
  Found: Boolean;
  Form: TForm;
  I: Integer;
begin
  
// Split up in a valid form and a valid component name
  
P := Pos('.', Name);
  if P = 0 then
  begin
    raise 
Exception.Create('No valid form name given');
  end;
  FormName := Copy(Name, 1, P - 1);
  CompName := Copy(Name, P + 1, High(Integer));
  Found    := False;
  // find the form
  
for I := 0 to Screen.FormCount - 1 do
  begin
    
Form := Screen.Forms[I];
    // case insensitive comparing
    
if AnsiSameText(Form.Name, FormName) then
    begin
      
Found := True;
      Break;
    end;
  end;
  if Found then
  begin
    for 
I := 0 to Form.ComponentCount - 1 do
    begin
      
Result := Form.Components[I];
      if AnsiSameText(Result.Name, CompName) then Exit;
    end;
  end;
  Result := nil;
end;

procedure TFrom1.Button1Click(Sender: TObject);
var
  
C: TComponent;
begin
  
C := FindComponentEx('MyForm10.Edit2');
  TEdit(C).Caption := 'Hello';
end;




 

Rate this tip:

poor
very good


Copyright © by SwissDelphiCenter.ch
All trademarks are the sole property of their respective owners