简体   繁体   English

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

[英]Creating buttons from database table on runtime in Delphi

I want to create buttons from Database on runtime. 我想在运行时从Database创建按钮。 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. 您可以在每次循环迭代时重置i计数器。 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM