Search code examples
c++mfclegacy

CListCtrl do action based on selected row values


I have to enable/disable buttons on a dialog based on values in a CListViewCtrl. Based on the selected row. I got this far:

NOTIFY_HANDLER(IDC_LIST, LVN_ITEMCHANGED, OnMyListChange)

// ....

    LRESULT OnMyListChange(int, LPNMHDR pNMHDR, BOOL&)
    {
        NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
        if ((pNMListView->uChanged & LVIF_STATE) 
            && (pNMListView->uNewState & LVIS_SELECTED))
        {
            // enable/disable buttons based on row field value
        }
        return 0;
    }

Lets say I have column1 column2 column3. I need to write a condition based on column2 value in the selected row. Multiple row selection is not a case. Thank you.


Solution

  • There is a method GetItemText. Notice it refers to:

    nItem The index of the item whose text is to be retrieved.

    nSubItem Specifies the subitem whose text is to be retrieved.

    Think of them as row and column. Now, look at the NM_LISTVIEW structure in your handler:

    typedef struct tagNMLISTVIEW {
      NMHDR  hdr;
      int    iItem;
      int    iSubItem;
      UINT   uNewState;
      UINT   uOldState;
      UINT   uChanged;
      POINT  ptAction;
      LPARAM lParam;
    } NMLISTVIEW, *LPNMLISTVIEW;
    

    It too has those properties:

    int    iItem;
    int    iSubItem;
    

    So you should be able to get at the item text and perform what you wanted to do. Example:

    // Get text in column 2 (it might 1 - can't remember if it is zero based indexing)
    CString strValue = m_myList.GetItemText(pNMListView->iItem, 2);
    if(strValue == "DoThis")
    {
        // ...
    }
    

    The above code is not tested!!