Monday, 21 May 2007

Accessing multiple edit Components

I was asked by a friend how he could access all his components without a long and hard to maintain list in the Source Code. He had a number of Edits on his form and he wanted to add all the edits up, knowing the were all set to receive integer values.

Here's how he can do it...


function GetEdits : Integer;
var
i : integer;
comp : TComponent;
begin
result := '';
try
// fMain is the main form.
for i := 0 to fMain.ComponentCount - 1 do
begin
Comp := fMain.Components[i];
if (Comp is TEdit) then // its an edit component
if (Comp as TEdit).Text <> '' then
Result := result + StrToInt((Comp as TEdit).Text);
end;
except
result := -1; // Oops, that edit was not a number
end;
end;