Icon Searching and Sorting DataSets

The TDataSet component provides several methods for searching and sorting the rows present in the underlying dataset, as well as properties for obtaining information about the active sort.

Sorting the Rows
To sort the rows in a dataset, use the Sort method. To specify the columns to sort, assign the desired value to the TDataColumn SortDirection property in the order that reflects the column order of the desired sort. Use the TDataSet SortCaseInsensitive property to specify that the sort should be case-insensitive, and the SortLocaleInsensitive property to specify that the sort should be locale-insensitive. The default value for both properties is False.

The following example sorts the Products dataset based upon descending list price:

begin
   with Products do
      begin
      Columns['ListPrice'].SortDirection:=sdDescending;
      Sort;
      end;
end;

Once a sort has been established, the TDataSet Sorted will return True and the dataset will automatically keep the rows sorted accordingly as rows are inserted, updated, or deleted. The TDataColumn SortIndex property can be examined to determine where a column resides in the active sort. To clear an existing sort, simply assign a value of sdNone to the SortDirection property of all sorted columns.

Searching for a Row
The TDataSet Find method allows you to search the rows in the dataset for a particular set of column values. If there is a sort active on the dataset, then it will be used for satisfying the Find operation if the ColumnsToSearch, CaseInsensitive, and LocaleInsensitive parameters for the Find method match the active sort. For example, the following example sorts the Products dataset by the ProductID column and then executes a case-insensitive Find operation on the ProductID column for the 'PEN-BP-12PK' product ID:

begin
   with Products do
      begin
      Columns['ProductID'].SortDirection:=sdAscending;
      SortCaseInsensitive:=True;
      Sort;
      if Find(['ProductID'],['PEN-BP-12PK'],False,True) then
         Result:=True
      else
         Result:=False;
      end;
end;

Pass True as the third NearestSearch parameter to the Find method in order to perform a search for the row with the column values that are nearest to the specified Find values.
Image