A TreeView can sort items automatically, or you can control sorting manually. Manual sorting can be alphabetic by label text, or you can implement a user-defined sort to define your own criteria. The SortType property controls the way items are sorted. Its values are of the enumerated datatype grSortType.
Automatic alphabetic sorting To enable sorting by the text label, set the SortType property to Ascending! or Descending!. Inserted items are sorted automatically.
Manual alphabetic sorting For more control over sorting, you can set SortType to Unsorted! and sort by calling the functions in Table 8-5.
Use this function |
To do this |
---|---|
InsertItemSort |
Insert an item at the correct alphabetic position, if possible |
Sort |
Sort the immediate children of an item |
SortAll |
Sort the whole branch below an item |
If users will drag items to organize the list, you should disable sorting.
Sorting by other criteria To sort items by criteria other than their labels, implement a user-defined sort by setting the SortType property to UserDefinedSort! and writing a script for the Sort event. The script specifies how to sort items.
PowerBuilder triggers the Sort event for each pair of items it tries to reorder. The Sort script returns a value reporting which item is greater than the other. The script can have different rules for sorting based on the type of item. For example, level 2 items can be sorted differently from level 3. The TreeView is sorted whenever you insert an item.
This sample script for the Sort event sorts the first level by the value of the Data property and other levels alphabetically by their labels. The first level displays composers chronologically, and the Data property contains an integer identifying a composer’s century:
//Return values
//-1 Handle1 is less than handle2
// 0 Handle1 is equal to handle2
// 1 Handle1 is greater than handle2
TreeViewItem tvi1, tvi2
This.GetItem(handle1, tvi1)
This.GetItem(handle2, tvi2)
IF tvi1.Level = 1 THEN
// Compare century values stored in Data property
IF tvi1.data > tvi2.Data THEN
RETURN 1
ELSEIF tvi1.data = tvi2.Data THEN
RETURN 0
ELSE
RETURN -1
END IF
ELSE
// Sort other levels in alpha order
IF tvi1.Label > tvi2.Label THEN
RETURN 1
ELSEIF tvi1.Label = tvi2.Label THEN
RETURN 0
ELSE
RETURN -1
END IF
END IF