Recent

Author Topic: [SOLVED] Sort DBGrid  (Read 1339 times)

Hansvb

  • Hero Member
  • *****
  • Posts: 894
[SOLVED] Sort DBGrid
« on: June 19, 2022, 01:31:50 pm »
Hi, I want to sort a DBGrid and found this example:
Code: Pascal  [Select][+][-]
  1. https://wiki.lazarus.freepascal.org/Grids_Reference_Page#Sorting_columns_or_rows_in_DBGrid_with_sort_arrows_in_column_header

I works only as long as I sort the same column. When I sort a column and then want to sort another column I get an error.
error:
Code: Pascal  [Select][+][-]
  1. The maximum amount of indexes is reached

How to sort a DBGrid?
« Last Edit: June 20, 2022, 07:48:28 pm by Hansvb »

Hansvb

  • Hero Member
  • *****
  • Posts: 894
Re: Sort DBGrid
« Reply #1 on: June 19, 2022, 01:35:47 pm »
Oeps, found it.

I changed the lines:
Code: Pascal  [Select][+][-]
  1. ASC_IndexName:='ASC_'+Column.FieldName;
  2. DESC_IndexName:='DESC_'+Column.FieldName;

to:
Code: Pascal  [Select][+][-]
  1. ASC_IndexName:='ASC_';
  2. DESC_IndexName:='DESC_';

Now i can sort what ever column I want.

Hansvb

  • Hero Member
  • *****
  • Posts: 894
Re: [SOLVED] Sort DBGrid
« Reply #2 on: February 11, 2026, 07:49:56 pm »
This is an old post but I run into the following. If I use the sort function of the gridreference page then that works fine as long as I retrieve all records. Now I have a query that retrieves data that needs to be exported, so I eventually need all the records. Because retrieving all records is slow, I thought to use PacketRecords:= 100. But then the sorting function no longer works. I get an access violation on the line
Code: Pascal  [Select][+][-]
  1. AddIndex(ASC_IndexName,column.FieldName,[]);
I suspect this is because I only pull part of the data to me and part is still on the server. Is there a way to sort a dbgrid and using PacketRecords? I can not use 'sort by' in the query. I want to be able to sort columns when i click on the title of the dbgrid

Zvoni

  • Hero Member
  • *****
  • Posts: 3315
Re: [SOLVED] Sort DBGrid
« Reply #3 on: February 12, 2026, 08:28:39 am »
Sort the bound Dataset, not the Grid.
See here: https://www.freepascal.org/docs-html/fcl/bufdataset/tcustombufdataset.indexfieldnames.html
Code: Pascal  [Select][+][-]
  1. MyQuery.IndexFieldNames:='FirstName DESC';
  2. MyGrid.Refresh;
Use OnTitleClick of the DBGrid to set Sorting-Field and/Or Direction

IIRC, you have to set IndexFieldNames to empty string, before the hole thing goes out of scope (e.g. closing the Form), otherwise you get an AV (This might even be considered a Bug?)
« Last Edit: February 12, 2026, 08:31:29 am by Zvoni »
One System to rule them all, One Code to find them,
One IDE to bring them all, and to the Framework bind them,
in the Land of Redmond, where the Windows lie
---------------------------------------------------------------------
Code is like a joke: If you have to explain it, it's bad

 

TinyPortal © 2005-2018