这是我开发中使用的一个关于计算cxGrid中某一列(数值型)的最大值、最小值、汇总、统计、平均值,可以供你参考使用。
procedure CalcCxGrid(const dataSet: TDataSet;
const cxGrid: TcxGrid;
const aCalcSelectedData: Boolean;
const FieldName: String;
var SumValue:do
uble;
var CountValue:do
uble;
var MaxValue:do
uble;
var MinValue:do
uble;
var AverageValue:do
uble);
function FieldIsNumber(aField: TField): Boolean;
begin
Result := aField.DataType in
[ ftSmallint, ftInteger, ftWord,
ftFloat, ftCurrency, ftBCD, ftBytes, ftVarBytes, ftAutoInc, ftLargeint,
ftFMTBcd
];
end;
var
ARowIndex, AFieldColumnIndex: Integer;
ARowInfo: TcxRowInfo;
I: Integer;
gridView: TcxGridDBBandedTableView;
tmpValue:do
uble;
begin
SumValue := 0;
CountValue := 0;
MaxValue := 0;
MinValue := 0;
AverageValue := 0;
if (not DataSet.Active) or (DataSet.RecordCount = 0)
or (not Assigned(DataSet.FindField(FieldName)))
or (not FieldIsNumber(DataSet.FieldByName(FieldName))) then
Exit;
AFieldColumnIndex := cxGridFieldIndexByFieldName(cxGrid, FieldName);
if AFieldColumnIndex = -1 then
Exit;
gridView := (cxGrid.ActiveView as TcxGridDBBandedTableView);
// gridView.DataController.GetRowCount
for I := 0 to gridView.DataController.GetSelectedCount - 1do
begin
ARowIndex := gridView.DataController.GetSelectedRowIndex(I);
ARowInfo := gridView.DataController.GetRowInfo(ARowIndex);
tmpValue := StrToFloatDef(VarToStr(gridView.DataController.GetRowValue(ARowInfo, AFieldColumnIndex)), 0);
SumValue := SumValue + tmpValue;
CountValue := CountValue + 1;
if tmpValue > MaxValue then
MaxValue := tmpValue;
if I = 0 then
MinValue := tmpValue
else
if tmpValue < MinValue then
MinValue := tmpValue;
end;
if CountValue <> 0 then
AverageValue := RoundTo(SumValue / CountValue, -2);
end;