Sum Amounts in TListView

How can we summarize some SubItems in a TListView? If you look at the picture below,

enter image description here

Fist, fill Col 1 to Col 4 for Group1 and Group2 . The problem is how we can sum SubItems Col 2 and put the result in Col 3 . The picture that I write above is clear, but if I want to explain how to summarize it, then its appearance you summarize the current SubItem ListView with the above SubItem. And for the first SubItem in each group we put the same number as Col 2 .

+4
source share
1 answer

Something like this might do what you want:

 procedure TForm1.Button1Click(Sender: TObject); var I: Integer; Value: Integer; GroupID: Integer; GroupSum: Integer; begin GroupID := 0; GroupSum := 0; for I := 0 to ListView1.Items.Count - 1 do begin if Assigned(ListView1.Items[I].SubItems) and (ListView1.Items[I].SubItems.Count > 0) and TryStrToInt(ListView1.Items[I].SubItems[0], Value) then begin if GroupID <> ListView1.Items[I].GroupID then begin GroupSum := 0; GroupID := ListView1.Items[I].GroupID; end; GroupSum := GroupSum + Value; if ListView1.Items[I].SubItems.Count < 2 then ListView1.Items[I].SubItems.Add(IntToStr(GroupSum)) else ListView1.Items[I].SubItems[1] := IntToStr(GroupSum); end; end; end; 

Well, for those who want to simulate an OP situation, here is the code (just put the list view component on the form and write an event handler):

 procedure TForm1.FormCreate(Sender: TObject); var ListItem: TListItem; ListGroup: TListGroup; ListColumn: TListColumn; begin ListView1.Clear; ListView1.GroupView := True; ListView1.ViewStyle := vsReport; ListColumn := ListView1.Columns.Add; ListColumn.Caption := 'Column 1'; ListColumn.Width := 90; ListColumn := ListView1.Columns.Add; ListColumn.Caption := 'Column 2'; ListColumn.Width := 90; ListColumn := ListView1.Columns.Add; ListColumn.Caption := 'Column 3'; ListColumn.Width := 90; ListGroup := ListView1.Groups.Add; ListGroup.GroupID := 0; ListGroup.Header := 'Group 1'; ListGroup := ListView1.Groups.Add; ListGroup.GroupID := 1; ListGroup.Header := 'Group 2'; ListItem := ListView1.Items.Add; ListItem.GroupID := 0; ListItem.Caption := 'Item 1'; ListItem.SubItems.Add('22'); ListItem := ListView1.Items.Add; ListItem.GroupID := 0; ListItem.Caption := 'Item 2'; ListItem.SubItems.Add('11'); ListItem := ListView1.Items.Add; ListItem.GroupID := 1; ListItem.Caption := 'Item 3'; ListItem.SubItems.Add('94'); ListItem := ListView1.Items.Add; ListItem.GroupID := 1; ListItem.Caption := 'Item 4'; ListItem.SubItems.Add('42'); ListItem := ListView1.Items.Add; ListItem.GroupID := 1; ListItem.Caption := 'Item 5'; ListItem.SubItems.Add('21'); end; 
+6
source

All Articles