Sort DBGrid by clicking a column heading

Well, that seems a bit complicated (if not impossible). I am trying to make my DBGrid sort my data by clicking on the column heading.

The fact is that I (unfortunately) work with Delphi 3, I do not use ADO DataSets, and the query receives many rows, so I can not reopen my TQuery, changing the sentence order byto clicks.

Has someone implemented something like this?

+3
source share
6 answers

This is actually done by sorting the data set, and then the grid reflects the change. This can be done quite easily by creating an index in the dataset field for this column. Of course, this can only be done in a dataset that supports index sorting, for example TClientDataset.

+5
source

In the TDBGrid OnTitleClick method, you can do something like ...

procedure TfmForm1.DBGrid1TitleClick(Column: TColumn);
var
   i: Integer;
begin
   // apply grid formatting changes here e.g. title styling
   with DBGrid1 do
      for i := 0 to Columns.Count - 1 do
         Columns[i].Title.Font.Style := Columns[i].Title.Font.Style - [fsBold];
   Column.Title.Font.Style := Column.Title.Font.Style + [fsBold];

   with nxQuery1 do // the DBGrid query component (a [NexusDB] TnxQuery)
   begin
      DisableControls;
      if Active then Close;
      for i := 0 to SQL.Count - 1 do
         if (Pos('order by', LowerCase(SQL[i])) > 0) then
            //NOTE: ' desc' The [space] is important
            if (Pos(' desc',LowerCase(SQL[i])) > 0) then 
               SQL[i] := newOrderBySQL
            else
               SQL[i] := newOrderBySQL +' desc';
      // re-add params here if necessary
      if not Active then Open;
      EnableControls;
   end;
end;

There are many ways that you could optimize this, I am sure, however, it depends on the capabilities of the components you use. The above example uses a query component, although if you used a table component, you should change the index used instead of the order by clause.

SQL - . , SQL- , " .." SQL, .. "{..}" "//"

+1

Delphi 3 TClientDataset. TQuery IndexName.

0

, : Delphi DBGrid, .

, , TClientDataSet (cds.IndexFieldNames := Column.FieldName OnTitleClick TDBGrid). , , ( , ), , ​​ Express Quantum Grid (, , ).

0

TDBGrid OnTitleClick :

procedure TForm1.DBGrid3TitleClick(Column: TColumn);
var
  cFieldName:string;
begin
  cFieldName:= DBGrid3.SelectedField.FieldName;
  AdoDataset1.Sort:=cFieldName;
end;
0

: (https://www.thoughtco.com/sort-records-in-delphi-dbgrid-4077301)

procedure TForm1.DBGrid1MouseMove(Sender: TObject; Shift: TShiftState; X,
  Y: Integer);
var
 pt: TGridcoord;
begin
 pt:= DBGrid1.MouseCoord(x, y);
 if pt.y=0 then
 DBGrid1.Cursor:=crHandPoint
 else
 DBGrid1.Cursor:=crDefault;
end;

procedure TForm1.DBGrid1TitleClick(Column: TColumn);
var
  cFieldName:string;
begin
  Adotable1.Sort := Column.Field.FieldName;
end;
0

Source: https://habr.com/ru/post/1712902/


All Articles