Question:
I would like to know how to program a Custom Sort procedure on a ListView in Borland’s C++ Builder.
Answer:
Normally, the ListView control will sort items automatically for you. However, it may not sort them in the order you want. For example, alphabetically, “10/1/98” comes before “4/1/98,” but you would probably prefer that these items appear chronologically.
The exact syntax needed to sort items in a custom order depends on your compiler and if you are using application frameworks. Basically, you need to create your ListView control without the LVS_SORTASCENDING
or LVS_SORTDESCENDING
window styles.
Send an LVM_SORTITEMS
message to the control, or use the ListView_SortItems
macro. Either approach requires you to specify the address of a compare function that you must define. The compare function must have the following form:
int CALLBACK CompareFunc(LPARAM lParam1, LPARAMlParam2, LPARAM lParamSort);Windows will call this function with each item to be sorted. The
lParam1
and lParam2
arguments specify the 32-bit values associated with each item being compared. These are the values that you specified in the lParam
member of the LVITEM
structure when you add the items to the list.Your comparison function should return a negative value if the first item comes before the second item, or a positive value if the second item comes before the first item. If the two items are equal, the comparison function should return 0.