Search code examples
c++mfcclistctrl

issue with retrieving current list item text from CListCtrl


I am trying to retrieve the selected list item from CListCtrl. The first item text is retrieved correct. Later on when I go select next, only the previous list item text is retrieved. Below is my event method that is triggered when I select an item from CListCtrl.

example scenario

List(m_RListCtrl) -> Item1, Item2, Item3

First time I click/select Item2. Item2 text displayed in m_EditBox. Next I click Item3. Item2 is still displayed Then I click Item1. Item3 is displayed in the editbox then I click Item2. Item1 is displayed. ... ... ...

event code :

void CRTConfigDlg::OnLvnItemchangedRepoConfigList(NMHDR *pNMHDR, LRESULT *pResult)
{
    CString itemText = L"";

    itemText = m_RListCtrl.GetItemText(m_RListCtrl.GetSelectionMark(), 0);

    m_EditBox.SetWindowText(itemText);
    //UpdateWindow();
}

I have even tried following solution from Get Index of Item Text in MFC CListCtrl. But still the issue was same.

Can you help me to know , where I am going wrong?


Solution

  • You need to iterate through selected items like this:

    int nColumns = m_RListCtrl.GetHeaderCtrl()->GetItemCount();
    POSITION pos = m_RListCtrl.GetFirstSelectedItemPosition();
    while (pos)
    {
        int nItem = m_RListCtrl.GetNextSelectedItem(pos);
    
        for(int i=0; i<nColumns; i++)
        {
            CString sItem = m_RListCtrl.GetItemText(nItem, i);
            // TO DO: do stuff with item text here
        }
    }