delphitlist

How to add items from an SQL query to a TListView


I want to add items from a query into a TListView using a for loop. But I get an error saying 'Too many actual parameters' from the ListViewShifts.Items.Add() line. What is the correct way of adding to the list from a query?

  Qry := TFDQuery.Create(DBConnection);
  Qry.Connection := DBConnection;
  Qry.SQL.Text := 'SELECT Count(10) FROM Bookings WHERE NurseNo=:nurseID;';
  Qry.Params.ParamByName('nurseID').AsInteger := NurseID;
  Qry.Active := True;

  //Fill the list view with the shifts that have the nurses ID
  for Count := 0 to 10 do
  begin
    ListViewShifts.Items.Add(Qry.Fields[Count].AsString);
  end;

Solution

  • You need to consider the following:

    Next basic example shows how to add 10 items in your TListView:

    procedure TMainForm.btnGet(Sender: TObject);
    var
       li: TListItem;
    begin
    
       Qry := TFDQuery.Create(DBConnection);
       Qry.Connection := DBConnection;
       Qry.SQL.Text := 'SELECT TOP(10) FROM Bookings WHERE NurseNo=:nurseID;';
       Qry.Params.ParamByName('nurseID').AsInteger := NurseID;
       Qry.Active := True;
    
       Qry.First; 
       for Count := 1 to 10 do
       begin
          Qry.Next;
          li := ListViewShifts.Items.Add;
          li.Caption := Qry.Fields[0].AsString;
       end;
       (*
       Qry.First;
       while not Qry.Eof do begin
          li := ListViewShifts.Items.Add;
          li.Caption := Qry.Fields[0].AsString;
          Qry.Next;
       end;
       *)
    end;