0
votes

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?

2

2 Answers

2
votes

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
    }
}
2
votes

You can also use the Itemchanged Notification but you have to keep in mind, that this event is triggered when an item is selected and deselected.

So you need to examin the items state.

void CAnyDialogClass::OnLvnItemchanged(NMHDR *pNMHDR, LRESULT *pResult)
{
    LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);

    // check if the items state changed to selected.
    if ((pNMLV->uChanged & LVIF_STATE)!=0 && 
        (pNMLV->uOldState & LVIS_SELECTED)==0 && 
        (pNMLV->uNewState & LVIS_SELECTED)!=0)
    {
        // This item is selected now
        ...

Even more precise is to use LVIS_FOCUSED. The user may change the focus of an item by just holding the Ctrl key and using the cursor movement keys.