sqldelphisortingtclientdatasettdbgrid

Delphi ClientDataSet Sorting by changing IndexName


I've been learning about the ClientDataSet in delphi and how it can help sort my SQL database. The data is showing fine in my TDBGrid and i've enabled sorting by clicking on a header by changing the IndexField of the ClientDataset. I want to make it go descending on sorts sometimes though so have been trying to use 2 IndexNames outlined here https://stackoverflow.com/a/13130816/4075632

However, when I swap the IndexName from DEFAULT_ORDER to CHANGEINDEX, all data in my DBGrid disappears. I'm pretty new to all of this, and I know it will depend on my situation, but what are some of the ways this happens and I will try to troubleshoot them.

I have 1 TSQLConnection connected to TSQLQuery, and that connected to TDataSetProvider, and that connected to my ClientDataSet which leads to a TDataSource to the TDBGrid. Why might the ClientDataSet which is usually fine cause problems when I change its name? Please bear in mind that most of the settings are default because I'm not too sure about these components. Thanks, I hope you can provide some useful help and I'm sorry it may be difficult to se my situation.

Toby


Solution

  • I use the following code to build indexes for a clientdataset:

    Procedure BuildIndices (cds: TClientDataSet);
    var
     i, j: integer;
     alist: tstrings;
    
    begin
     with cds do
      begin
       open;
       logchanges:= false;
       for i:= 0 to FieldCount - 1 do
        if fields[i].fieldkind <> fkCalculated then
         begin
          j:= i * 2;
          addindex ('idx' + inttostr (j), fieldlist.strings[i], [], '', '',  0);
          addindex ('idx' + inttostr (j+1), fieldlist.strings[i], [ixDescending], '', '', 0);
         end;
       alist:= tstringlist.create;
       getindexnames (alist);
       alist.free;
       close;
      end;
    end;
    

    As a result, there is an index 'idx0' for sorting column 0 ascending and 'idx1' for sorting column 0 descending; 'idx2' and 'idx3' for column 1, etc.

    Then, in the grid's OnTitleClick event, I have the following

    procedure Txxx.DBGrid1TitleClick(Column: TColumn);
    var
     n, ex: word;
    
    begin
     n:= column.Index;
     try
      dbgrid1.columns[prevcol].title.font.color:= clNavy
     except
     end;
    
     dbgrid1.columns[n].title.font.color:= clRed;
     prevcol:= n;
     directions[n]:= not directions[n];
     ex:= n * 2;
     if directions[n] then inc (ex);
     with clientdataset do
      try
       disablecontrols;
       indexname:= 'idx' + inttostr (ex);
      finally
       first;
       enablecontrols
      end;
    end;
    

    In each form, I define an array of booleans ('directions'), one element per grid column. These elements track whether a column should be sorted ascending or descending.