Page 1 of 1

Sorting checked columns in TReportListView

Posted: Wed Dec 23, 2020 7:36 pm
by hlohning
Recently I was asked whether it is possible to sort a report listview according to a column containing check boxes while disregarding the state of the check boxes. The default behavior of the TReportListView component includes the checked states in the sorting process - which aggregates all rows with selected check boxes on one end of the list und the non-selected rows on the other end.
reportlistview_sorting.png
reportlistview_sorting.png (11.61 KiB) Viewed 32028 times
If you want to change this behavior you can utilize the event OnBeforeSortExchange. This event is called whenever the sorting algorithm tries to make a comparison during the sorting action. Thus you can influence the way of sorting simply by adjusting the strings to be compared.

The following code shows how to implement this behavior. The parameter InString contains the text to be compared, the variable parameter OutString is the actual text which is used for the comparison. By default OutString is equal to InString. Please note that the state of a checkbox is indicated by the first character: an 'X' indicates a selected cell, a blank indicates a non-selected cell. Thus removing the 'X' changes the behavior in a way that the check box state does no longer influence the sorting.

Code: Select all

procedure TForm1.RepList1BeforeSortExchange(Sender: TObject;
  InString: string; var OutString: string);

begin
if length(Instring) > 1 then
  if (Instring[1] = 'X') then  // replace X by space to avoid sorting the checkboxes
    OutString[1] := ' ';       // if any text to be sorted is available
                               // if no text is available (just a checkbox)
                               // the checkmark is used as a sorting criterion
end;