Software & Finance - Monthly Magazine Online

Volume 4 - Issue 3

March 2014

Visual C++ MFC CListCtrl - Multiple Selection Items Iteration


To know about how to add items to MFC list box control in the section – MFC CListBox Adding String. If multiple selection option is enabled, then we need to iterate through all selected items one by one.

 

In OnBnClickedOk() function, CListBox::GetSelCount() is used to get the selection count. GetSelItems(...) is used to get the collection of selected indexes in the listbox. Once we get the selected index collection, we can walk through using a simple for loop and CListBox::GetText(...) function.

 

class CMyTestDlg : public CDialog

{

public:

      CMyTestDlg(CWnd* pParent = NULL);   // standard constructor

      enum { IDD = IDD_MYTEST_DIALOG };

 

protected:

      virtual void DoDataExchange(CDataExchange* pDX);

 

public:

    CListBox m_listBox;

    afx_msg void OnBnClickedOk();

    afx_msg void OnLbnDblclkList1();

};

 

void CMyTestDlg::DoDataExchange(CDataExchange* pDX)

{

    CDialog::DoDataExchange(pDX);

    DDX_Control(pDX, IDC_LIST1, m_listBox);

}

 

 

 

BOOL CMyTestDlg::OnInitDialog()

{

      CDialog::OnInitDialog();

 

      m_listBox.AddString("ONE");

      m_listBox.AddString("TWO");

      m_listBox.AddString("THREE");

      m_listBox.AddString("FOUR");

      m_listBox.AddString("FIVE");

 

      return TRUE;  // return TRUE  unless you set the focus to a control

}

 

void CMyTestDlg::OnLbnDblclkList1()

{

    int row = m_listBox.GetCurSel();

    if(row < 0)

        return;

   

    CString s1;

    m_listBox.GetText(row, s1);

    MessageBox(s1);

}

 

void CMyTestDlg::OnBnClickedOk()

{

    // Works for multiple selection

    int count = m_listBox.GetSelCount();

      int *lp = new int[1025];

           

      int count2 = m_listBox.GetSelItems(1024, lp);

 

      for(int i = 0; i < count2; i++)

      {

                  CString str;

                  m_listBox.GetText(lp[i], str);

                  MessageBox(str);

      }

    OnOK();

}

 

Click here to download the VC++ Project and Executable

 

 

 

CListCtrl multiple selection