Search code examples
delphivcl

delphi vcl - How do I set the values of a database table in a Label?


I want to view the records of the database table in the frame being created and run time contains Label to display this data

I do not know what the code is The data appears duplicate.

procedure TForm3.Button1Click(Sender: TObject);
var
  cartRow: TFrm;
  lin :SmallInt;
  posX,posY : SmallInt;
  s , id: string;
  i : Integer;
begin
  ScrollBox1.DestroyComponents;
  s := FDQuery1.FieldByName('CountryAr').AsString;
  id:= FDQuery1.FieldByName('CountryID').AsString;
  posX := 0;
  posY := 0;
  for lin := 0 to FDTable1.RecordCount - 1 do
  begin
    cartRow := TFrm.Create(ScrollBox1);
    cartRow.Parent :=ScrollBox1;
    cartRow.Name := '';
    cartRow.Left := posX -1;
    cartRow.Top := posY -1;
    cartRow.Label1.Caption := (s);
    cartRow.Label2.Caption :=(id);
    cartRow.Width := (ScrollBox1.Width) -3;
    cartRow.Height := 35;
    posY := posY + cartRow.Height +1;
  end;
  cartRow.Free;`

image


Solution

  • You have multiple issues in your code. First, you assign the values to s and id once, and then use those same values for every label, ignoring anything in the database after that assignment. Second, you never advance the record pointer in your loop, which means that it will end up in an infinite loop. Third, you're looping through FDTable1 fields, but reading the values from FDQuery1. Fourth, you're unnecessarily using a call to RecordCount instead of a simple while not Eof loop. And finally, you're freeing CartRow when it shouldn't be free'd; you're assigning ScrollBox1 as the owner of the control created, which means the scrollbox will free it when the scrollbox is free'd.

    Something like this will work much better for you:

    procedure TForm3.Button1Click(Sender: TObject);
    var
      cartRow: TFrm;
      posX,posY : SmallInt;
    begin
      ScrollBox1.DestroyComponents;
      posX := 0;
      posY := 0;
      FDQuery1.First;
      while not FDQuery1.Eof do
      begin
        cartRow := TFrm.Create(ScrollBox1);
        cartRow.Parent := ScrollBox1;
        cartRow.Left := posX - 1;
        cartRow.Top := posY - 1;
        cartRow.Label1.Caption := FDQuery1.FieldByName('CountryAr').AsString;
        cartRow.Label2.Caption := FDQuery1.FieldByName('CountryID').AsString;
        cartRow.Width := ScrollBox1.Width - 3;
        cartRow.Height := 35;
        posY := posY + cartRow.Height + 1;
        FDQuery1.Next;
      end;
    end;