Sort TListBox Items Alphabetically in Delphi 7

4.1k Views Asked by At

I am attempting to trigger a sort on the items within a TListBox control after adding/editing entries.

I see that there is a Sorted property which I've set to true, however, this doesn't dynamically sort the ListBox every time I make a change to the contents. There doesn't seem to be any Sort procedure or function available and calling Update or Refresh does not have the desired effect.

I've reached the stage where I'm considering pulling the contents of the ListBox into a TStringList object, sorting that and then putting everything back into the ListBox again. This seems a bit insane though, surely I am overlooking some better method.

Here's an example of changing an existing item:

 myListBox.Items[myIndex] := newString; // Update Text
 myListBox.Items.Objects[myIndex] := TObject(my_object); // Update associated object

I would expect the control to update to keep things sorted alphabetically but it doesn't.

1

There are 1 best solutions below

6
On BEST ANSWER

The sorted property of a list box is actually backed by the Win32 list box style LBS_SORT. That will sort the list box when a new item is added. But it will not do so when an existing item is modified.

So the easy way to work around this is to set Sorted to True, then, instead of modifying existing values, remove the old value and add the new one. So your code would become:

myListBox.Items.Delete(myIndex);
myListBox.Items.AddObject(newString, TObject(my_object));

And if you think about it, your code would have been doomed to failure if the list box behaved the way you expected it to. Because after you modified the text of the item, if the list was re-sorted then myIndex would no longer refer to the same item.