以ADO数据集相连的DBGrid按单一字段排序通用过程

//适用范围:与ADO数据集相连的DBGrid按单一字段排序
//传入参数:Column(排序字段对应的DBGridColumn),DefaultSort(缺省排序串)
//使用建议:在DBGrid的OnTitleClick中直接调用之。第一次单击某Column标题栏时,按改字段升序排列,连续第二次单击时改为降序,连续第三次单击时,改为缺省方式排序(如PrimaryKey等)
procedure SortDBGrid(Column: TColumn; DefaultSort: string='');
const
  ASCMark: string = '▲';
  DESCMark: string = '▼';
var
  I: integer;
begin
  if not Assigned(Column.Field) then Exit;
  if not Assigned(Column.Field.DataSet) then Exit;
  if not (Column.Field.DataSet is TCustomADODataSet) then Exit;
  if Column.Field.FieldKind <> fkData then Exit;
  for I:=0 to (Column.Collection as TDBGridColumns).Count-1 do
  with (Column.Collection as TDBGridColumns).Items[I].Title do
  begin
    Caption := StringReplace(Caption, ASCMark, '', []);
    Caption := StringReplace(Caption, DESCMark, '', []);
  end;
  try
    with Column.Field.DataSet as TCustomADODataSet do
    begin
      if Sort = Column.FieldName + ' ASC' then
      begin
        Sort := Column.FieldName + ' DESC';
        Column.Title.Caption := Column.Title.Caption + DESCMark;
      end
      else if Sort = Column.FieldName + ' DESC' then
        Sort := Trim(DefaultSort)
      else
      begin
        Sort := Column.FieldName + ' ASC';
        Column.Title.Caption := Column.Title.Caption + ASCMark;
      end;
    end;
  except
    ;//(Column.Field.DataSet as TCustomADODataSet).Sort := '';
  end;
end;

 
posted @ 2008-04-01 17:05  delphi中间件  阅读(392)  评论(0编辑  收藏  举报