MFC C++ CListBox get selected item

11,051

Solution 1

Your code looks OK except error handling. Also MessageBox parameters look incorrect. The first parameter should be of type HWND. I believe that this is the root cause of your problems. Use MFC standard AfxMessageBox instead:

CListBox * pList1 = (CListBox *)GetDlgItem(IDC_LIST1);

int nSel = pList1->GetCurSel();
if (nSel != LB_ERR)
{
    CString ItemSelected; 
    pList1->GetText(nSel, ItemSelected);
    AfxMessageBox(ItemSelected);
}

Solution 2

If the CListBox is in single selection mode, the CListBox::GetCurSel will return the selected index.

If the CListBox is in multi-selection mode, you should use CListBox::GetSelItems which will return a list of indices.

You cannot mix'n'match the functions.

And always check return codes (as others already wrote).

Share:
11,051
Huşȁm Đȁßabñęh
Author by

Huşȁm Đȁßabñęh

Updated on June 14, 2022

Comments

  • Huşȁm Đȁßabñęh
    Huşȁm Đȁßabñęh almost 2 years

    First let me say that I've been searching for a solution for couple of days now...

    I'm trying to get selected item for ListBox. This is my code:

    CListBox * pList1 = (CListBox *)GetDlgItem(IDC_LIST1);
    CString ItemSelected;
    // Get the name of the item selected in the Sample Tables list box 
    // and store it in the CString variable declared above 
    pList1->GetText(pList1->GetCurSel(), ItemSelected);
    MessageBox(ItemSelected, "TEST", MB_OK);
    

    Now when i try this i get an error message saying "The Parameter is incorect"