sum value of selected cells in stringgrid

delphi

Solution

How to get sum of the floating-point values of a selection in TStringGrid ?

For standard Delphi `TStringGrid` for instance this way:

procedure TForm1.Button1Click(Sender: TObject);
var
  Sum: Double;
  Val: Double;
  Col: Integer;
  Row: Integer;
begin
  Sum := 0;
  for Col := StringGrid1.Selection.Left to StringGrid1.Selection.Right do
    for Row := StringGrid1.Selection.Top to StringGrid1.Selection.Bottom do
      if TryStrToFloat(StringGrid1.Cells[Col, Row], Val) then
        Sum := Sum + Val;
  ShowMessage('Sum of the selection is ' + FloatToStr(Sum) + '.');
end;

How to get sum of the floating-point values of a selection (including invisible cells) in TAdvStringGrid ?

Hence you're most probably using `TAdvStringGrid` you can try the following not yet tested or optimized code. So far I found, you can use `AllFloats` property to access all grid cells as float irrespective of hidden columns or rows. Assuming you want to sum continuous selection after you hide a certain column, you may try this code:

procedure TForm1.Button1Click(Sender: TObject);
var
  Sum: Double;
  Col: Integer;
  Row: Integer;
begin
  Sum := 0;
  for Col := AdvStringGrid1.Selection.Left to AdvStringGrid1.Selection.Right do
    for Row := AdvStringGrid1.Selection.Top to AdvStringGrid1.Selection.Bottom do
      Sum := Sum + AdvStringGrid1.AllFloats[Col, Row];
  ShowMessage('Sum of the selection is ' + FloatToStr(Sum) + '.');
end;

Problem

How can I get the sum value of the selected cells or a range in `stringgrid`? Please note that sometimes these cells contain string values! I try `GridCoord`, but it doesn't work good because sometimes there are "hidden columns". ``` procedure TMainShowForm.StgSelectionChanged(Sender: TObject; ALeft, ATop, ARight, ABottom: Integer); var i: Integer; gc: TGridCoord; sum:double; begin for i := 1 to stg.SelectedCellsCount do begin gc := stg.SelectedCell[i - 1]; sum:=sum+stg.floats[(gc.X),(gc.Y)]; end; AdvOfficeStatusBar1.Panels[0].Text:='Sum = '+ formatfloat('#,##0.',sum); AdvOfficeStatusBar1.Panels[1].Text:='Count = '+ inttostr(stg.SelectedCellsCount); end; ```

Original source