Question

How we can sum some SubItems in TListView? If you look at picture in below,

enter image description here

Fist, we fill Col 1 to Col 4 for Group1 and Group2. The problem is, how we can sum the SubItems Col 2 and put the result in Col 3. The picture i post at above is clear, but if i want to explain for how to sum, Its kinda you sum current SubItem of ListView with above SubItem. And, for first SubItem in each group we put same number like Col 2.

Was it helpful?

Solution

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 OP's situation, here's a code (just place a list view component on a form and write the 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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top