Software & Finance





Visual C++ MFC - CListCtrl - Multiple Selection Items Iteration





We have seen how to add items to MFC list control in the earlier section.

 

If multiple selection option is enabled, then we need to iterate through all selected items one by one.

 

In OnBnClickedOk() function, CListBox::GetFirstSelectedItemPosition() () is used to first selected item. It returns the POSITION value which would further be used in the calls to CListCtrl::GetNextSelectedItem(pos). The return value would be the row id. With the row id, we can use CListCtrl::GetItemText to get the string values in the MFC list control.

 

 


Source Code


class CMyTestDlg : public CDialog

{

 

      enum { IDD = IDD_TEST_DIALOG };

public:

      CListCtrl m_listCtrl;


}

 

 

void CMyTestDlg::DoDataExchange(CDataExchange* pDX)

{

    CDialog::DoDataExchange(pDX);

    DDX_Control(pDX, IDC_LIST1, m_listCtrl);

}

 

BEGIN_MESSAGE_MAP(CMyTestDlg, CDialog)

      ON_WM_SYSCOMMAND()

      ON_WM_PAINT()

      ON_WM_QUERYDRAGICON()

      //}}AFX_MSG_MAP

    ON_NOTIFY(NM_DBLCLK, IDC_LIST1, &CMyTestDlg::OnNMDblclkList1)

END_MESSAGE_MAP()

 

 

void CMyTestDlg::OnNMDblclkList1(NMHDR *pNMHDR, LRESULT *pResult)

{

    int row = m_listCtrl.GetSelectionMark();

    if(row < 0)

        return;

    CString s1 = m_listCtrl.GetItemText(row, 0);

    CString s2 = m_listCtrl.GetItemText(row, 1);

    CString s3 = m_listCtrl.GetItemText(row, 2);

}

 

void CMyTestDlg::OnBnClickedOk()

{

    POSITION pos = m_listCtrl.GetFirstSelectedItemPosition();

    if (pos != NULL)

    {

       while (pos)

       {

            int row = m_listCtrl.GetNextSelectedItem(pos);

            CString s1 = m_listCtrl.GetItemText(row, 0); // Extract Page

            CString s2 = m_listCtrl.GetItemText(row, 1); // Extract Last modified

            CString s3 = m_listCtrl.GetItemText(row, 2); // Extract Priorty

 

            CString msg;

            msg.Format("%d - %s, %s, %s", row + 1, (const char*) s1, (const char*) s2, (const char*) s3);

            MessageBox(msg);

       }

    }

    OnOK();

}

 

Click here to download the Visual C++ Project and Executable

Output