QuantumGrid - fazer um ClientDataSet ordenar quando ordena a cxGrid

Top  Previous  Next

Problema

Ordeno campos da cxGrid (multiplos, ascendente e descendente) e o ClienteDataSet continua sem ordem, quando faço um Tb.First, while not EOF... não percorro os registros na mesma sequencia que me aparece na grid.

Solução

Crie um indice em runtime com os mesmos campos que estão ordenados no grid:

// este evento é da cxGrid

procedure TForm1.DadosDataControllerSortingChanged(Sender: TObject);

var

  I: Integer;

  S, lsDesc, nome: String;

  O: TIndexOptions;

begin

  O := [];

  // percorre os campos "ordenados" da grid

  for I := 0 to Dados.SortedItemCount - 1 do

  begin

    // adiciona a var "S"

    S := mRot.IfThen(I = 0, Dados.SortedItems[I].DataBinding.FilterFieldName, S + ';' + Dados.SortedItems[I].DataBinding.FilterFieldName);

    // se for descendente coloca em lsDesc

    if Dados.SortedItems[I].SortOrder = soDescending then

    begin

      O := [ixDescending];

      if lsDesc = '' then

        lsDesc := Dados.SortedItems[I].DataBinding.FilterFieldName

      else

        lsDesc := lsDesc + ';' + Dados.SortedItems[I].DataBinding.FilterFieldName;

    end;

  end;

 

  // cria um indice de nome diferente do anterior - isso é importante, se for o mesmo nome o Delphi

  // não indexará, apenas usará o anterior

  Nome := FormatDateTime('NNSSZZZ', Now);

  // limpa indices atuais

  Tb.IndexDefs.Clear;

  // adiciona o indice que criamos

  Tb.IndexDefs.Add(Nome, S, O);

  Tb.IndexDefs[Qy.IndexDefs.Count-1].DescFields := lsDesc;

  // ativa o bicho

  Tb.IndexName := Nome;

  // aqui temos o client ordenado igual a cxGrid

end;