Delphi7 TMS TDBAdvGrid Sort data when column header is clicked

8.4k views Asked by At

I'm a newbie into Delphi and i need an advice.

I'm using a TMS TDBAdvGrid and i need to sort the data when the user is clicking the header of a column. I setup the sort settings of the grid and i write code for the onclicksort event, but it is not working.

The sort settings of the grid:

 SortSettings.Show = True;
 SortSettings.IgnoreBlanks = True;
 SortSettings.BlankPos = blLast;

the onclicksort event:

 try
     try
       if FSortISWorking then
         Exit;
       FSortISWorking := true;

       if ACol < 0 then
       begin
         grid.BeginUpdate;
         grid.SortSettings.Column := ACol;
         Application.ProcessMessages;
         grid.QSort;
         grid.EndUpdate;
       end;
     except on e: Exception do
       begin
         // log the error
       end;
     end; 
     finally
      FSortISWorking := false;  
     end;

The grid is not linked directly to the database. The data is loaded into memory (TClientDataSet) and i need to sort the data only in memory, without another query to the database.

Thank you

2

There are 2 answers

2
Heinrich Ulbricht On BEST ANSWER

I tried your example and this solved the issue for me:

Grid.PageMode := False;
0
RBA On

In order to resolve this problem you must order the dataset behind your grid. here you have how to do this in general:http://delphi.about.com/od/usedbvcl/l/aa042203a.htm.

bellow you have an example:

 procedure TForm1.DBAdvGrid1CanSort(Sender:TObject; ACol: Integer; var DoSort: Boolean); 

 var fldname:string; 
 begin
 DoSort := False; // disable internal sort

 // toggle sort order if
 dbadvgrid1.SortSettings.Direction = sdAscending then
 dbadvgrid1.SortSettings.Direction := sdDescending else
 dbadvgrid1.SortSettings.Direction := sdAscending;

 // get field name of the column
 clicked fldname :=query1.FieldList.Fields[ACol -1].FieldName;

 if pos(' ',fldname)  0 then fldname:= 'biolife.db."'+fldname+'"';

 // add ORDER BY clause to the query
 query1.SQL.Text := 'select * from
 biolife.db ORDER BY '+fldname;

 if dbadvgrid1.SortSettings.Direction =
 sdDescending then query1.SQL.Text :=
 query1.SQL.Text + ' DESC';

 query1.Active := true;
 DBAdvGrid1.SortSettings.Column := ACol; 
 end;

if you want to order your clientdataset here you have how to do it:

http://edn.embarcadero.com/article/29056

best regards,
Radu