Home > Enterprise >  Need help solving a issue in listbox
Need help solving a issue in listbox

Time:06-21

I'm still learning c mfc and my question is: how can I get the CurSel of 2 listbox as the number, then add them and print the result? the result displays a weird 659998896 number instead of 2. What have I done wrong here?

BOOL CEngravingCalculatorDlg::OnInitDialog(){
    CListBox* emplistbox1 = static_cast<CListBox*>(GetDlgItem(IDC_LIST1));
    emplistbox1->AddString(L"1");
    emplistbox1->SetCurSel(0);

    CListBox* emplistbox3 = static_cast<CListBox*>(GetDlgItem(IDC_LIST3));
    emplistbox3->AddString(L"1");
    emplistbox3->SetCurSel(0);
    }

void CEngravingCalculatorDlg::OnBnClickedButton1()
{
   CListBox* emplistbox1 = static_cast<CListBox*>(GetDlgItem(IDC_LIST1));
   CListBox* emplistbox3 = static_cast<CListBox*>(GetDlgItem(IDC_LIST3));
   int num1 = emplistbox1->GetCurSel();
   int num2 = emplistbox3->GetCurSel();
   int equal = num1   num2;
   CString str;
   str.Format(_T("%d", equal));
    GetDlgItem(IDC_Display)->SetWindowTextW(str);
}

CodePudding user response:

_T is a macro that takes only a single parameter. Because of a typo, you've given it two parameters. The second one is ignored and effectively lost. This means your format call is only getting a single parameter, and you're seeing undefined behavior. Fix it with:

str.Format(_T("%d"), equal);

P.S. This means your error had absolutely nothing to do with the listbox.

CodePudding user response:

See this snippet. GetCurSel() is used to get the cursor position and not the content. Use GetText() to get the content of the Listbox.

void CEngravingCalculatorDlg::OnBnClickedButton1()
{
    CListBox* emplistbox1 = static_cast<CListBox*>(GetDlgItem(IDC_LIST1));
    CListBox* emplistbox3 = static_cast<CListBox*>(GetDlgItem(IDC_LIST3));
    int num1 = emplistbox1->GetCurSel();
    int num2 = emplistbox3->GetCurSel();

    CString ItemSelected1, ItemSelected2;
    if (num1 != LB_ERR && num2 != LB_ERR)   {
        emplistbox1->GetText(num1, ItemSelected1);      
        emplistbox3->GetText(num2, ItemSelected2);      

        int equal = atoi(CStringA(ItemSelected1).GetString())   atoi(CStringA(ItemSelected2).GetString());
        CString str;
        str.Format(L"%d", equal);
        SetDlgItemText(IDC_Display, str);
    }

}
  • Related