• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 793
  • Last Modified:

CListCtrl sort

Hi, i have a problem with sorting a CListCtrl control which has 3 columns. I have written a callback function that I call with the SortItems function of the CListCtrl, but it doesn't work properly.  Here's the call and the sort function :

// I initialize and add some data in the CListCtrl
int CALLBACK CompareItems(LPARAM   lparam1, LPARAM lparam2,              LPARAM lparamsort)
  CListCtrl* pList = (CListCtrl*) lparamsort;
  CString strItem1 = pList->GetItemText(lparam1,0);
  CString strItem2 = pList->GetItemText(lparam2,0);
  return strcmp(strItem1,strItem2);

Where m_list_codes is the CListCtrl I created with the ressource editor. When I debug, what is wrong is that the function is called with lparam1 and lparam2 that have values like 22932876 or something like that when in fact, they should have the index of a data in the CListCtrl. Is there some conversion I forgot ? Or is it my sort function that is not correct ?  Thanks for your help.
1 Solution

look at the parameter list for the compare items.  lparam and wparam actually are the following

afx_msg int OnCompareItem( int nIDCtl, LPCOMPAREITEMSTRUCT lpCompareItemStruct );

what you want to do, is cast your lparam2 to an LPCOMPAREITEMSSTRUCT like this


then use that struct to determine the return value

here is a copy of the compare items structure

typedef struct tagCOMPAREITEMSTRUCT {
    UINT   CtlType;
    UINT   CtlID;
    HWND   hwndItem;
    UINT   itemID1;
    DWORD  itemData1;
    UINT   itemID2;
    DWORD  itemData2;

based on that data, you need to return a value from that routine for whether the items are equal to, greater than or less than.

–1 Item 1 sorts before item 2.
0 Item 1 and item 2 sort the same.
1 Item 1 sorts after item 2.

progbieAuthor Commented:
I don't really understand why I have to do that, and where the compareitemstruct comes from.  According to msdn documentation on CListCtrl::SortItems, all I'm supposed to have to do is write a compare function (here, I call it CompareItems) that will be called during the sort operation each time the relative order of two list items needs to be compared.  Also, lparam1 and lparam2 are supposed to contain the index of the items to be compared.  What I don't understand is why it is not what it contains.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now