单击网格标题排序(转帖)
procedure TForm1.GridTitleSort(Column: TColumn);
var s,cFieldName:string;
i:integer;
DataSet:TDataSet;
procedure setTitle;
var ii:integer;
cStr:string;
c:TColumn;
begin
for ii:=0 to TDBGrid(Column.Grid).Columns.Count-1 do
begin
c:=TDBGrid(Column.Grid).Columns[ii];
cStr:=c.Title.Caption;
if (pos('▲',cStr)=1) or (pos('▼',cStr)=1) then
begin
Delete(cStr,1,2);
c.Title.Caption:=cStr;
end;
end;
end;
begin
setTitle;
DataSet:=Column.Grid.DataSource.DataSet;
if Column.Field.FieldKind=fkLookup then
cFieldName:=Column.Field.KeyFields
else if Column.Field.FieldKind=fkCalculated then
cFieldName:=Column.Field.KeyFields
else
cFieldName:=Column.FieldName;
//=================================AdoDataSet=====================
if DataSet is TCustomADODataSet then begin
s:=TCustomADODataSet(DataSet).Sort;
if s='' then begin
s:=cFieldName;
Column.Title.Caption:='▲'+Column.Title.Caption;
end
else begin
if Pos(cFieldName,s)<>0 then begin
i:=Pos('DESC',s);
if i<=0 then begin
s:=s+' DESC';
Column.Title.Caption:='▼'+Column.Title.Caption;
end
else begin
Column.Title.Caption:='▲'+Column.Title.Caption;
Delete(s,i,4);
end;
end
else begin
s:=cFieldName;
Column.Title.Caption:='▲'+Column.Title.Caption;
end;
end;
TCustomADODataSet(DataSet).Sort:=s;
end
//============================Clientdataset==========================
else if DataSet is TClientDataSet then begin
if TClientDataSet(DataSet).indexfieldnames<>'' then
begin
i:=TClientDataSet(DataSet).IndexDefs.IndexOf('i'+Column.FieldName);
if i=-1 then
begin
with TClientDataSet(DataSet).IndexDefs.AddIndexDef do
begin
Name:='i'+Column.FieldName;
Fields:=Column.FieldName;
DescFields:=Column.FieldName;
end;
end;
TClientDataSet(DataSet).IndexFieldNames:='';
TClientDataSet(DataSet).IndexName:='i'+Column.FieldName;
Column.Title.Caption:='▼'+Column.Title.Caption;
end
else
begin
TClientDataSet(DataSet).IndexName:='';
TClientDataSet(DataSet).IndexFieldNames:=column.fieldname;
Column.Title.Caption:='▲'+Column.Title.Caption;
end;
end;
end;