How to find all the components and controls of a delphi form using ComponentCount method?
Sometimes in delphi programming, we require to find all the components and controls of the delphi form at runtime and do something with their properties.
For example, we may require to enable or disable all the buttons of the delphi form at runtime. Traditionally, we can do this by setting the enabled property to false or true for each and every button component on the form one by one. But if we don't know the names of buttons beforehand, or the names of button is assigned at runtime, then how can we set the enabled property at design time? For this, we will need to find all the button components at runtime and assign the enabled property.
ComponentCount method is useful here. ComponentCount Method is used to count all the components present on your delphi form. We will use ComponentCount Method to find and disable all the buttons of the your delphi form at runtime. Here is the simple delphi program to illustrate the concept of ComponentCount Method.
procedure MyForm.DisableAllButtons;
var
i : integer;
begin
try
for i := 0 to ComponentCount - 1 do
begin
if Components[i] is TButton then //Check whether the component is button or anything else
begin
MyForm(Components[i]).Enabled := False;
end;
end;
except
on E : Exception do
begin
ShowMessage('Error occured in function DisableAllButtons: ' + E.Message);
exit;
end;
end;
end;
var
i : integer;
begin
try
for i := 0 to ComponentCount - 1 do
begin
if Components[i] is TButton then //Check whether the component is button or anything else
begin
MyForm(Components[i]).Enabled := False;
end;
end;
except
on E : Exception do
begin
ShowMessage('Error occured in function DisableAllButtons: ' + E.Message);
exit;
end;
end;
end;
Above procedure finds all the button components of the TMyForm delphi class and disables them in single line of code. No need to figure out all the buttons and then disable them one by one.
No comments:
Post a Comment