I want to create buttons from Database on runtime. For example I have a table lets say users. I need to create as many buttons as the user table contains.
The following code does that. But I have a problem, it gives me the last button only or it puts all buttons on top of other and I see only last button.
I need to get the buttons one next to other.
procedure TForm1.Button2Click(Sender: TObject);
var
Bt: TButton;
i: Integer;
begin
Query1.First;
while not Query1.Eof do
begin
i:=0;
Bt := TButton.Create(Self);
Bt.Caption := Query1.Fields[0].AsString;
Bt.Parent := Self;
Bt.Height := 23;
Bt.Width := 100;
Bt.Left := 10;
Bt.Top := 10 + i * 25;
i:= i+1;
Query1.Next;
end;
end;
what should I change or add?
You reset the i
counter with every loop iteration. Initialize it once before you enter the loop:
procedure TForm1.Button2Click(Sender: TObject);
var
i: Integer;
Bt: TButton;
begin
Query1.First;
i := 0; // initialize the counter before you enter the loop
while not Query1.Eof do
begin
Bt := TButton.Create(Self);
Bt.Caption := Query1.Fields[0].AsString;
Bt.Parent := Self;
Bt.Height := 23;
Bt.Width := 100;
Bt.Left := 10;
Bt.Top := 10 + i * 25;
i := i + 1;
Query1.Next;
end;
end;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.