Nesta função quando o usuário clica na coluna a função cria um índice temporário no ClientDataSet.
A chamada da função tem que ser colocada no evento OnTitleClick da DBGrid conforme exemplo abaixo.
procedure TfrmForm1.DBGrid1TitleClick(Column: TColumn);
begin
Grid_Ordena_e_PintaTitulo(DBGrid1, column, ClientDataSet1);
end;
//
// Código fonte da Função
//
function Grid_Ordena_e_PintaTitulo(xGrid: DBGrids.TDBGrid; Column: TColumn; CDS: TClientDataSet): boolean;
const
idxDefault = 'DEFAULT_ORDER';
var
strColumn: string;
bolUsed: Boolean;
idOptions: TIndexOptions;
I: Integer;
VDescendField: string;
begin
Result := false;
if not CDS.Active then exit;
strColumn := idxDefault;
// Se for campo calculado não deve fazer nada
if (Column.Field.FieldKind = fkCalculated) then exit;
// O índice já está em uso
bolUsed := (Column.Field.FieldName = cds.IndexName);
// Verifica a existência do índice e propriedades
CDS.IndexDefs.Update;
idOptions := [];
for I := 0 to CDS.IndexDefs.Count - 1 do
begin
if cds.IndexDefs.Items[I].Name = Column.Field.FieldName then
begin
strColumn := Column.Field.FieldName;
// Determina como deve ser criado o índice, inverte a condição ixDescending
case (ixDescending in cds.IndexDefs.Items[I].Options) of
True: begin
idOptions := [];
VDescendField := '';
end;
False: begin
idOptions := [ixDescending];
vDescendField := strColumn;
end;
end;
end;
end;
// Se não encontrou o índice, ou o índice já esta em uso...
if (strColumn = idxDefault) or bolUsed then
begin
if bolUsed then
CDS.DeleteIndex(Column.Field.FieldName);
try
CDS.AddIndex(Column.Field.FieldName, Column.Field.FieldName, idOptions, VDescendField, '', 0);
strColumn := Column.Field.FieldName;
except
// O índice esta indeterminado, passo para o padrão
if bolUsed then strColumn := idxDefault;
end;
end;
for I := 0 to xGRID.Columns.Count - 1 do begin
if Pos(StrColumn, xGrid.Columns[I].Field.FieldName) <> 0 then
xGrid.Columns[I].Title.Font.Color := clBlue
else
xGrid.Columns[I].Title.Font.Color := clWindowText;
end;
try
CDS.IndexName := strColumn;
except
CDS.IndexName := idxDefault;
end;
result := true;
end;
Espero ter ajudado, um grande abraço a todos !!