[SOLVED] Understanding TstringGrid behavior when adding a line to a sorted grid lazarus / 31-LCL ---------------------------------------------------------------------- EganSolo · 2025-07-31 23:20 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. ---------------------------------------------------------------------- EganSolo · 2025-08-05 01:12 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 · 2025-08-05 07:40 Hi QuoteYou must maintain the sort order in code by sorting the grid againHmmm... 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