Recent

Author Topic: [SOLVED] Understanding TstringGrid behavior when adding a line to a sorted grid  (Read 849 times)

EganSolo

  • Sr. Member
  • ****
  • Posts: 380
  Context: TStringGrid sorted on a column.
  UseCase:
       1. Add a row
       2. Initialize Cell[SortedColumn,RowCount-1] to some value V.
       3. Call Cols[SortedColumn].IndexOf(V)
TStringGrid's Behavior:
1 => Appends a row to the bottom of the grid.
2 => Assigns the value to the cell
3 => Performs a binary search against the sort order of the column as it was before the new row was added. As a result, IndexOf might return -1 if the binary search misses V.

I don't have any issue with this behavior, but wanted to confirm that's what will happen in such a use case.
 
« Last Edit: August 05, 2025, 03:12:30 am by EganSolo »

EganSolo

  • Sr. Member
  • ****
  • Posts: 380
Re: Understanding TstringGrid behavior when adding a line to a sorted grid
« Reply #1 on: August 05, 2025, 03:12:05 am »
I've verified that the behavior listed below is correct. Appending to a sorted string grid disrupts the sort order, requiring you to resort again. In other words, when you sort the grid, it's a point-in-time operation that doesn't keep the grid sorted when you modify the rows (or columns) later. You must maintain the sort order in code by sorting the grid again.

cdbc

  • Hero Member
  • *****
  • Posts: 2476
    • http://www.cdbc.dk
Hi
Quote
You must maintain the sort order in code by sorting the grid again
Hmmm... It works  ...but as you may know, QuickSort is not a 'stable' sort algorithm -- it may rearrange the items on every sort --
Thus, I've had better results with making a 'function AppendSorted()' and then either always use that or sort once & then /appendsorted/, that way you'll keep your items in place.
Regards Benny
If it ain't broke, don't fix it ;)
PCLinuxOS(rolling release) 64bit -> KDE6 -> FPC 3.2.2 -> Lazarus 4.0 up until Jan 2025 from then on it's both above &: KDE6/QT6 -> FPC 3.3.1 -> Lazarus 4.99

 

TinyPortal © 2005-2018