Search code examples
delphilistviewvirtual

Displaying item when LVItemGetCaption is being called with EasyListView?


I am trying to implement virtual data mode with EasyListview

From the demo :

procedure TForm1.AddItems(Count: Integer);
var
  i: Integer;
begin
  // Add items to the listview. Actually the items are added to the first
  // group. This group is created automatically when the first item is added.
  LV.BeginUpdate;
  try
    for i := 0 to Count - 1 do
      LV.Items.AddVirtual;
  finally
    LV.EndUpdate;
  end;
end;

procedure TForm1.LVItemGetCaption(Sender: TCustomEasyListview;
  const Item: TEasyItem; Column: Integer; var Caption: WideString);
begin
  case Column of
    0: Caption := 'Item ' + IntToStr(Item.Index);
    1: Caption := 'Detail ' + IntToStr(Item.Index);
  end;
end;

If I add some items which are string :

procedure TForm1.AddItems(Count: Integer);
var
  i: Integer;
begin
  // Add items to the listview. Actually the items are added to the first
  // group. This group is created automatically when the first item is added.
  LV.BeginUpdate;
  try
    for i := 0 to Count - 1 do
    begin
      LV.Items.AddVirtual.Caption := 'DISPLAY ME ' + IntToStr(i);
    end;
  finally
    LV.EndUpdate;
  end;
end;

How to get and displaying the stored virtual caption(=string) when LVItemGetCaption is being called?

If I get the caption with Caption := LV.Items.Items[Item.Index].Caption ; then Stack overflow.


Solution

  • You must add your data object to the item. E.g.:

    type
      TMyData = class
        Caption: string;
      end;
    
    procedure TForm1.Button1Click(Sender: TObject);
    var
      i: Integer;
      item: TEasyItemVirtual;
      MyData: TMyData;
    begin
      EasyListview1.BeginUpdate;
      try
        for i := 0 to 100 - 1 do
        begin
          MyData := TMyData.Create;
          MyData.Caption := Format('My Item %D',[i]);
          item := EasyListview1.Items.AddVirtual;
          item.Data := MyData;
        end;
      finally
        EasyListview1.EndUpdate;
      end;
    end;
    
    procedure TForm1.EasyListview1ItemGetCaption(Sender: TCustomEasyListview; Item: TEasyItem;
      Column: Integer; var Caption: WideString);
    begin
      case Column of
        0: Caption := TMyData(Item.Data).Caption;
        1: Caption := TMyData(Item.Data).Caption;
      end;
    end;
    

    And don't forget to free your object:

    procedure TForm1.EasyListview1ItemFreeing(Sender: TCustomEasyListview; Item: TEasyItem);
    begin
      if Assigned(Item.Data) then
        Item.Data.Free;
    end;