2009. szeptember 6., vasárnap

Custom sort a TCheckListBox


Problem/Question/Abstract:

I created a component TMyCheckListBox which inherited from TCheckListBox, and I want to sort the list of items in numeric not alphabetic order. Although I set the Sorted property to True, I cannot sort it in the way I want. I need to have a numeric sort with the Sorted property set to True.

Answer:

The Sorted property calls the built-in capability of the underlying windows control to sort itself alphabetically. In case you need to perform a custom sorting, just turn the Sorted property off, and do the sorting by using TStringList CustomSort method. Below is the sequence of possible steps

Assign listbox's items to the string list. Perform custom sorting by calling the CustomSort method. You should pass a function that compares two strings in the string list as parameter (see example below for details). Move items back to the listbox. Here's an example. It resorts the list's content in custom order:

{This function sorts items in the list}

function CompareStrings(List: TStringList; Index1, Index2: Integer): Integer;
var
  XInt1, XInt2: integer;
begin
  try
    XInt1 := strToInt(List[Index1]);
    XInt2 := strToInt(List[Index2]);
  except
    XInt1 := 0;
    XInt2 := 0;
  end;
  Result: = XInt1 - XInt2;
end;

procedure TForm1.SpeedButton5Click(Sender: TObject);
var
  XList: TStringList;
begin
  XList := TStringList.Create;
  CheckListBox1.Items.BeginUpdate;
  try
    XList.Assign(CheckListBox1.Items);
    XList.CustomSort(CompareStrings);
    CheckListBox1.Items.Assign(XList);
  finally
    XList.Free;
    CheckListBox1.Items.EndUpdate;
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése