How to sort listbox by numeric value

Somebody was seeking solution to problem how to sort listbox by
numeric values. I find solution to this problem while I was working
with ownerdrawn listboxes. This example is really nonsense program,
but I think this will show the idea how to make it.

unit SortForm;

interface

uses
  SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
  Forms, Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    ListBox1: TListBox;
    procedure FormCreate(Sender: TObject);
    procedure ListBox1DrawItem(Control: TWinControl;
      Index: Integer; Rect: TRect; State: TOwnerDrawState);
    procedure AddToListBox(Value: integer; Str: string);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.AddToListBox(Value: integer; Str: string);
{ Parameters: Value - integer sort key
              Str   - value inserted in ListBox1 }
begin
  if Value < 0 then
    ListBox1.Items.Add(Format('0%5.5d', [maxint - Abs(Value)]) + Str)
  else
    ListBox1.Items.Add(Format('1%5.5d', [Value]) + Str)
end;

procedure TForm1.ListBox1DrawItem(Control: TWinControl;
  Index: Integer; Rect: TRect; State: TOwnerDrawState);
begin
  { Forget the first 6 chars that is used as a sort key. Copy
    statement works also if String[x] contains only 6 chars,
    ie. key value given but empty Str value in AddToListBox. }
  with TListBox(Control) do
    Canvas.TextRect(Rect, Rect.Left, Rect.Top, Copy(Items.Strings[Index], 7, 255));
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  ListBox1.Sorted := True;
  ListBox1.Style := lbOwnerDrawFixed;
  { Let's add some values for testing... }
  AddToListBox(0, '0');
  AddToListBox(99, '999');
  AddToListBox(-10, '-10');
  AddToListBox(43, '43');
  AddToListBox(-1, '-1');
  AddToListBox(10, '10');
  AddToListBox(1, '1');
end;

end.

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Ari Hirviniemi, Lappeenranta, Finland (ari.hirvini...@ktieto.fi)
All my opinions and comments are personal and have nothing to do
with my employer.