TListView中的Sum子项

时间:2012-12-07 18:14:37

标签: delphi delphi-xe3

我们如何在TListView中总结一些SubItem?如果你看下面的图片,

enter image description here

拳头,我们为Col 1Col 4填充Group1Group2。问题是,我们如何对SubItems Col 2求和并将结果放在Col 3中。我在上面发布的图片是清楚的,但如果我想解释如何求和,它有点你将ListView的当前SubItem与上面的SubItem相加。并且,对于每个组中的第一个SubItem,我们将相同的数字设置为Col 2

1 个答案:

答案 0 :(得分:6)

这样的事可能会做你想要的:

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;

那么,对于那些想要模拟OP情况的人来说,这里是一个代码(只需在表单上放置一个列表视图组件并编写事件处理程序):

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;