在Delphi中运行时从数据库表创建按钮

时间:2013-07-06 10:23:03

标签: delphi

我想在运行时从Database创建按钮。 例如,我有一个表让我们说用户。 我需要创建与用户表包含的一样多的按钮。

以下代码执行此操作。但我有一个问题, 它只给我最后一个按钮,或者它把所有按钮放在另一个按钮上面,我只看到最后一个按钮。

我需要将按钮放在另一个旁边。

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;

我应该更改或添加什么?

1 个答案:

答案 0 :(得分:4)

每次循环迭代都会重置i计数器。在进入循环之前初始化它一次:

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;