You can try the following function. It returns the count of numeric values found in the current string grid's selection. To declared parameters passed to it returns minimum, maximum and average values from the current selection's numeric values (if there are some):
uses
Math;
function CalcStats(AStringGrid: TStringGrid; var AMinValue, AMaxValue,
AAvgValue: Double): Integer;
var
Col, Row, Count: Integer;
Value, MinValue, MaxValue, AvgValue: Double;
begin
Count := 0;
MinValue := MaxDouble;
MaxValue := MinDouble;
AvgValue := 0;
for Col := AStringGrid.Selection.Left to AStringGrid.Selection.Right do
for Row := AStringGrid.Selection.Top to AStringGrid.Selection.Bottom do
begin
if TryStrToFloat(AStringGrid.Cells[Col, Row], Value) then
begin
Inc(Count);
if Value < MinValue then
MinValue := Value;
if Value > MaxValue then
MaxValue := Value;
AvgValue := AvgValue + Value;
end;
end;
Result := Count;
if Count > 0 then
begin
AMinValue := MinValue;
AMaxValue := MaxValue;
AAvgValue := AvgValue / Count;
end;
end;
Here's a sample usage:
procedure TForm1.Button1Click(Sender: TObject);
var
MinValue, MaxValue, AvgValue: Double;
begin
if CalcStats(StringGrid1, MinValue, MaxValue, AvgValue) > 0 then
Label1.Caption :=
'Min. value: ' + FloatToStr(MinValue) + sLineBreak +
'Max. value: ' + FloatToStr(MaxValue) + sLineBreak +
'Avg. value: ' + FloatToStr(AvgValue)
else
Label1.Caption := 'There is no numeric value in current selection...';
end;
Another chapter is how to get notification when the selection of a string grid changes. There's no event nor virtual method for implementing event like OnSelectionChange
. But that would be topic for another question.