在DBGridEh的OnTitleClick事件中
var SortString:String;
begin
if Column.Title.SortMarker = smDownEh then
SortString:= Column.FieldName+ ' ASC'
else
SortString:= Column.FieldName+ ' DESC';
TADODataSet(TDbGridEh(Sender).DataSource.DataSet).Sort:=SortString;
procedure RGrid.SortEx(ACol: Integer);
var bNumberSort:Boolean;
i,j,MinRow:Integer;
MinValueASCii:String;
MinValueNumber,MinValueNumberOld:Real;
begin
//如果内容为空和只有一行,则退出
if RowCount<=FixedRows+1+1 then //只有标题行,合计栏,内容行
Exit;
//如果上次排序的列是本列,则倒转即可
if ACol=iOldSortCol then
begin
ReverseSort;
Exit;
end;
iOldSortCol:=ACol;//标记排过序的列
//增加一行
RowCount:=RowCount+1; //作为缓存
//将合计行的内容放在最后一行
//CopyRow(RowCount-2,RowCount-1);
//检查是否数字列,是则按数字进行排序,否则按字母进行排序
if ChkColIsNumberColumn(ACol) then bNumberSort:=True
else bNumberSort:=False;
//-----------以下按字母排序
if not bNumberSort then
begin
for i:=FixedRows to RowCount-3 do
begin
//将第1行的内容放在倒数第2行
CopyRow(i,RowCount-1);
MinRow:=i;
MinValueAscii:=Cells[ACol,i];
for j:=i+1 to RowCount-3 do
begin
if MinValueAscii>Cells[ACol,j] then
begin
MinRow:=j;
MinValueAscii:=Cells[ACol,j];
end;
end; //end for j
if MinRow<>i then
begin
CopyRow(MinRow,i); //将最小的行放在第一行
CopyRow(RowCount-1,MinRow); //行交换
end;
end; // end for i
end;
//-----------以上是按字母排序
//-----------以下是按数字排序
if bNumberSort then
begin
for i:=FixedRows to RowCount-3 do
begin
//将第1行的内容放在倒数第2行
CopyRow(i,RowCount-1);
MinRow:=i;
if Trim(Cells[ACol,i])='' then
MinValueNumber:=0
else
MinValueNumber:=StrToFloat(Cells[ACol,i]);
for j:=i+1 to RowCount-3 do
begin
if Trim(Cells[ACol,j])='' then
MinValueNumberOld:=0
else
MinValueNumberOld:=StrToFloat(Cells[ACol,j]);
if MinValueNumber>MinValueNumberOld then
begin
MinRow:=j;
MinValueNumber:=MinValueNumberOld;
end;
end; //end for j
if MinRow<>i then
begin
CopyRow(MinRow,i); //将最小的行放在第一行
CopyRow(RowCount-1,MinRow); //行交换
end;
end; // end for i
end;