TListView groups and items do not appear after clearing and reloading groups and items

StackOverflow https://stackoverflow.com/questions/22359137

  •  13-06-2023
  •  | 
  •  

Question

Delphi XE4 Update 1 and Windows 8.

When I add groups and items to the list view, they are displayed properly. When I then clear the items and groups, and add them again, nothing appears. Surely this is not the intended behavior?

From the DFM:

object lv: TListView
  Left = 24
  Top = 20
  Width = 250
  Height = 225
  Columns = <
    item
      Caption = 'Model'
      Width = 180
    end>
  GroupView = True
  ReadOnly = True
  RowSelect = True
  TabOrder = 0
  ViewStyle = vsReport
end

The code:

procedure TForm1.Button1Click(Sender: TObject);
var
  LListGroup: TListGroup;
  LListItem: TListItem;
begin
  lv.Items.Clear;
  lv.Groups.Clear;

  LListGroup := lv.Groups.Add;
  LListGroup.Header := 'Ford';

  LListItem := lv.Items.Add;
  LListItem.Caption := 'Escape';
  LListItem.GroupID := LListGroup.ID;

  LListItem := lv.Items.Add;
  LListItem.Caption := 'F150';
  LListItem.GroupID := LListGroup.ID;

  OutputDebugString(PChar(Format('lv.Groups.Count=%d', [lv.Groups.Count])));
end;

The first time I click the button, the items appear and they're grouped. The second time, the list view is blank. If I comment out the line that clears the groups, then it works, but the number of groups, all of which are unused but one, grows by 1 each time.

Was it helpful?

Solution

The issue with your code is which you are passing the ID property of the TCollectionItem to the GroupID property of the TListItem and you must use the GroupID property of the TListGroup.

So change this line

  LListItem.GroupID := LListGroup.ID; //here you are passing a wrong id for the group

to

  LListItem.GroupID := LListGroup.GroupID; //This is a valid assignment for the GroupID property
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top