As someone new to delphi, I am trying to get the following loop which will number 5 buttons to work
For x:=1 to 5 do
begin
button(x).caption:=x;
end;
Can anyone tell my why this doesn't work?
Are the components named Button1 ... Button5? You can't tell it to work on a component name like that. Besides, the subscripting array operator in Delphi is [], not (). Also, you need to convert x to string, if you want to assign it to a Caption property (use IntToStr for this). With that said, here's one way to do it (assuming that the buttons are already created by your form designer)
var
button: array[1..5] of TButton;
x : integer;
begin
button[1] := Button1;
button[2] := Button2;
button[3] := Button3;
button[4] := Button4;
button[5] := Button5;
for x := 1 to 5 do
button[x].Caption := IntToStr(x);
end;
If you want to create buttons on the fly, here's how to do it.
var
button : array[1..5] of TButton;
x : integer;
begin
for x := 1 to 5 do
begin
button[x] := TButton.Create(self);
button[x].Parent := self;
button[x].Left := (x - 1) * 100 + 10;
button[x].Top := 20;
button[x].Caption := IntToStr(x);
end;
end;
Or you could do something like the following
var
x: integer;
begin
for x := 1 to 5 do
TButton(Self.FindComponent('Button' + IntToStr(x))).Caption := IntToStr(x);
end;
Obviously you would have to be sure that buttons were actually named Button1, Button2 etc.