How to use FindComponent function in Delphi XE2?
Following is the code snippet which will show you how to use FindComponent in Delphi XE2?
procedure TClass1.UseFindComponent(FieldName : string);
var
aComponent :TComponent;
begin
try
aComponent := Form1.FindComponent(FieldName);
if aComponent <> nil then
begin
if (aComponent IS TEdit) then
begin
(aComponent AS TEdit).Clear;
(aComponent AS TEdit).Enabled := false;
(aComponent AS TEdit).Tag := 0;
end;
end;
except
on E : Exception do
begin
ShowMessage('Error occurred in function UseFindComponent: ' + E.Message);
exit;
end;
end;
end;
var
aComponent :TComponent;
begin
try
aComponent := Form1.FindComponent(FieldName);
if aComponent <> nil then
begin
if (aComponent IS TEdit) then
begin
(aComponent AS TEdit).Clear;
(aComponent AS TEdit).Enabled := false;
(aComponent AS TEdit).Tag := 0;
end;
end;
except
on E : Exception do
begin
ShowMessage('Error occurred in function UseFindComponent: ' + E.Message);
exit;
end;
end;
end;
Explanation: FindComponent function is used to find out the components present on a given form. In the above code, UseFindComponent function accepts the name of a component (it may be the name of textfield, button, dropdown etc.). Then it finds that component on Form1. If that component is a text field, it sets the properties (like Clear, Enabled, Tag) to that text field on runtime. Same you can do with buttons, labels or dropdowns.