CListCtrl::SortItems() a bug in the MSDN sample

Looking at a way to sort elements in a CCtrlList, I had a look at the sample given by the MSDN.

That’s the second time in a week I find a mistake in the MSDN. Must be unlucky… The first one concerned the “__cplusplus” preprocessor variable definition. I copied a sampe in which there was 1 “_” instead of two. Obviously, the sample didn’t work.

This time, it’s the sort items sample which is problematic.

Here is the MSDN sample :

// Sort the item in reverse alphabetical order.
static int CALLBACK
MyCompareProc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
{
// lParamSort contains a pointer to the list view control.
CListCtrl* pListCtrl = (CListCtrl*) lParamSort;
CString    strItem1 = pListCtrl->GetItemText(lParam1, 0);
CString    strItem2 = pListCtrl->GetItemText(lParam2, 0);

return strcmp(strItem2, strItem1);
}

void snip_CListCtrl_SortItems()
{
// The pointer to my list view control.
extern CListCtrl* pmyListCtrl;

// Sort the list view items using my callback procedure.
pmyListCtrl->SortItems(MyCompareProc, (LPARAM) pmyListCtrl);
}

(see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_mfc_clistctrl.3a3a.sortitems.asp)

This codes implies that lParam1 and lParam2 contains the index of the items to compare, which is not true since they are the item’s data field, which is not initialized to the index of items.

Moreover, even if you initialize the data of items with the corresponding index, the sort function will work only once, since after the first sort the real item index and the one stored in the data field won’t match anymore…

Leave a Reply

Your email address will not be published. Required fields are marked *