delphitlistbox

List of calculated numbers in TListView - RAD Studio, Delphi


Well I have the code that calculates "k" numbers. The "k" is the input from TEdit box. To do it i decided to use the while loop. With each calculation I decrement the "k" so the loop stops when "k" is equal 0. I store each number in the "num" integer variable so it's kind of temporary - "num" is overwritten with each loop route. The clue is I'd like to list the "num" in TListView but I don't know how to do it. I'm the begginer. Any blog, article, YouTube video might be helpful. I don't even know how to ask Google for that haha. Please help me. Finally I'd like to have the list with "k" entries of "num" numbers. Hope you understand.


Solution

  • The simplest way to handle this would be to do something like this:

    procedure TMyForm.FillListView;
    var
      i, k, num: Integer;
      item: TListItem;
    begin
      ListView1.Items.BeginUpdate;
      try
        ListView1.Items.Clear;
        k := StrToInt(Edit.Text);
        for i := 0 to k-1 do
        begin
          num := ...;
          item := ListView1.Items.Add;
          item.Caption := IntToStr(num);
          // set other properties as needed ...
        end;
      finally
        ListView1.Items.EndUpdate;
      end;
    end;
    

    That being said, this situation would be better handled using TListView in virtual mode instead (set its OwnerData property to true). You know from the starting k value how many list items you will need to add, so simply set TListView.Items.Count to that number, and then in the TListView.OnData event you can set the Caption (and other properties) of the provided TListItem as needed.

    var
      Nums: array of Integer;
    
    procedure TMyForm.FillListView;
    var
      i, k, num: Integer;
    begin
      k := StrToInt(Edit.Text);
      if k < 0 then k := 0;
      SetLength(Nums, k);
      for i := 0 to k-1 do
      begin
        num := ...;
        Nums[i] := num;
      end;
      ListView1.Items.Count := k;
      ListView1.Invalidate;
    end;
    
    procedure TMyForm.ListView1Data(Sender: TObject; Item: TListItem);
    begin
      Item.Caption := IntToStr(Nums[Item.Index]);
      // set other properties as needed ...
    end;