要用到第三方控件DBGridEh,设置AutoSortMakerting
procedure DgbMainSortMarkingChanged(Sender: TObject);
var
i, j: integer;
IndexFieldName, AFieldName, s: string;
Desc: Boolean;
begin
s := ''; //
for i := 0 to DBGridEh.SortMarkedColumns.Count - 1 do
begin
AFieldName := DBGridEh.SortMarkedColumns[i].FieldName;
case (DBGridEh.SortMarkedColumns[i].Field.FieldKind) of
fkLookup, fkCalculated, fkAggregate: exit;
end;
Desc := DBGridEh.SortMarkedColumns[i].Title.SortMarker = smUpEh;
if Desc then
IndexFieldName := 'i' + AFieldName + 'D'
else
IndexFieldName := 'i' + AFieldName;
j := ADataSet.IndexDefs.IndexOf(IndexFieldName);
if j = -1 then
begin
with ADataSet.IndexDefs.AddIndexDef do
begin
Name := IndexFieldName;
Fields := AFieldName;
//DescFields := AFieldName;
if Desc then
Options := [ixDescending];
end;
end;
s := s + IndexFieldName;
end;
ADataSet.IndexName := s;
end
引入第二种方法
KeyLife富翁笔记 |
作者: hongxing_dl 标题: ClientDataSet探讨(3)--排序 关键字: 分类: 开发经验 密级: 公开 |
ClientDataSet排序
1、简单排序
ClientDataSet1.IndexFieldNames:='排序字段'
2、复杂排序(建立索引)
下面这个过程仅供参考(因为用到三方控件DBGridEh):
procedure TDM1.DsSort(SortColumn: TColumnEh);
var
OldIndex:string;
begin
if (SortColumn.Grid.DataSource=nil) or (SortColumn.Grid.DataSource.DataSet=nil) or (not SortColumn.Grid.DataSource.DataSet.Active) then Exit;
OldIndex:=TClientDataSet(SortColumn.Field.DataSet).IndexName;
if OldIndex<>'' then
begin
TClientDataSet(SortColumn.Field.DataSet).IndexName:='';
TClientDataSet(SortColumn.Field.DataSet).DeleteIndex(OldIndex);
end;
case SortColumn.Title.SortMarker of
smNoneEh,
smUpEh :TClientDataSet(SortColumn.Field.DataSet).AddIndex('px',SortColumn.Field.FieldName,[ixDescending]);
smDownEh:TClientDataSet(SortColumn.Field.DataSet).AddIndex('px',SortColumn.Field.FieldName,[ixPrimary]);
end;
TClientDataSet(SortColumn.Field.DataSet).IndexName:='px';
end;
把上面的过程稍做修改,可用于标准DBGrid
var
ASC:Boolean=True;//是否升序排列
procedure TDM1.DsSort(SortColumn: TColumn);
var
OldIndex:string;
begin
if (SortColumn.Grid.DataSource=nil) or (SortColumn.Grid.DataSource.DataSet=nil) or (not SortColumn.Grid.DataSource.DataSet.Active) then Exit;
OldIndex:=TClientDataSet(SortColumn.Field.DataSet).IndexName;
if OldIndex<>'' then
begin
TClientDataSet(SortColumn.Field.DataSet).IndexName:='';
TClientDataSet(SortColumn.Field.DataSet).DeleteIndex(OldIndex);
end;
case ASC of
Ture :TClientDataSet(SortColumn.Field.DataSet).AddIndex('px',SortColumn.Field.FieldName,[ixDescending]);//已经是升序就按降序排列
else//否则按升序排列
TClientDataSet(SortColumn.Field.DataSet).AddIndex('px',SortColumn.Field.FieldName,[ixPrimary]);
end;{end case}
TClientDataSet(SortColumn.Field.DataSet).IndexName:='px';
ASC:=not ASC;