Thursday, January 1, 2009

Delphi: Iterating through components

The code example below shows how you can iterate through components in a Delphi form or data module, check the type of a hosted component and examine its properties. I wrote this as a unit test because the programmers were forgetting to remove their local connection strings from data objects. In this test we checked that the object has a reference to a DataConnection object and not a data connection string.

This is a fairly trivial example. It is the preferred solution if you want to iterate over a set of specific objects and set properties in a consistent way without having to write repetitive code referencing specific objects.

var
Temp: TComponent;

begin

for i := ComponentCount - 1 downto 0 do
begin
Temp := Components[i];
if (Temp is TADOQuery) then
begin

if Length(TADOQuery(Temp).ConnectionString)>0 then
raise Exception.Create('UnitTest(1): The use of a data connection string is not supported in this model.' + Temp.Name);

if TADOQuery(Temp).Connection = nil then
raise Exception.Create('UnitTest(2): A default connection object should be specified. ' + Temp.Name);

end;
end;



Some notes:

The code TADOQuery(Temp).Connection is shorthand for casting the TComponent object to an TADOQuery object and accessing its property Connection at the same time. A temporary unnamed TADOQuery object is created on the stack and disappears after the code is executed.

ComponentCount is a property that every object has that is derived from TComponent.