I am super newbie and tried to write following code which sets every TEdit.Text
to one mentioned in code
procedure TForm2.Button1Click(Sender: TObject);
var
i : integer;
Edit : TEdit;
begin
for i := 0 to Edit.ComponentCount - 1 do
begin
with Edit.Components[i] do
begin
Text := 'Done';
end;
end;
end;
What am I doing wrong ?
Here are the mistakes that I can see:
Edit
.TEdit
will have zero owned components.Edit.Components[i]
is of type TComponent
which does not have a Text
property. If your code compiles, then Text
is actually that of the form. The lesson you should learn from this point is never to use with
ever again.You should solve this using code like this:
procedure TForm2.Button1Click(Sender: TObject);
var
i: Integer;
Edit: TEdit;
begin
for i := 0 to ComponentCount-1 do begin
if Components[i] is TEdit then begin
Edit := TEdit(Components[i]);
Edit.Text := 'Done';
end;
end;
end;
Note that here we are using ComponentCount
and Components[]
from the form itself. We have removed the evil with
statement. And we have had to cast the component to a reference of type TEdit
, after first using the is
operator to check the type of the component.
This approach will work so long as the form owns all the edits found within it. However, if you create controls dynamically, or if you use frames or parented forms, then this approach, based on ownership via Components[]
will not yield all the controls. In such more complex cases you would need to iterate using the parent/child relationship using ControlCount
and Controls[]
.