Найти компонент по имени
Оформил: DeeCo
Автор: http://www.swissdelphicenter.ch
{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 9 do
TEdit(FindComponent('Edit'+IntToStr(i))).Text := 'Text' + IntToStr(i);
{or/oder:}
for i:= 1 to 9 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;
|