Software & Finance





Visual C++ MFC - CListBox - Get Current Selection





 

We have seen how to add items to MFC list box control in the section – MFC CListBox Adding String.

 

If single selection option is enabled, then it is easy to identify the selected item index by making a single call to CListBox::GetCutSel() function. With this index, we can use CListBox::GetText(...) function to retrieve the string value in the list box.

 


Source Code


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);

}

 

Click here to download the VC++ Project and Executable

 

Output