Search code examples
c++winapivisual-c++mfcclistctrl

Search for a item in CListCtrl


I am trying to find the index of a item in CListCtrl with specific data. In my case the data (not the item text) is the unique criterion by which I compare the items.

I tried to use CListCtrl::FindItem, but the function expects LVFINDINFOW* - I don't think it works for me. I also tried to iterate the clistctrl - again unsuccessfully.

Thanks in advance to everyone who gets involved!


Solution

  • When you set the 'data' for an item in a CListCtrl using the SetItemData member function, you are actually setting the lParam field of its associated LVITEM structure, as indicated in the documentation linked above:

    Remarks

    This value is the lParam member of the LVITEM structure, as described in the Windows SDK.

    So, if you want to search for an item with the given data, set the flags member of the LVFINDINFOW structure to LVFI_PARAM , and its lParam field to the data value you're looking for; then call the FindItem function using that structure:

    LVFINDINFOW findInfo;
    LPARAM searchData = 42; // Or whatever you're looking for
    findInfo.flags = LVFI_PARAM;
    findInfo.lParam = searchData;
    int dataPos = myListCtrl.FindItem(-1, &findInfo);
    //...