3

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?

1 Answer 1

4

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.