簡體   English   中英

MFC C ++ CListBox獲取所選項目

[英]MFC C++ CListBox get selected item

首先讓我說,我一直在尋找解決方案已有幾天了...

我正在嘗試獲取ListBox的選定項目。 這是我的代碼:

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

現在,當我嘗試此操作時,我收到一條錯誤消息,提示“參數不正確”

您的代碼看起來不錯,除了錯誤處理。 此外, MessageBox參數看起來不正確。 第一個參數應為HWND類型。 我相信這是您遇到問題的根本原因。 改用MFC標准AfxMessageBox

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

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

如果CListBox處於單選模式,則CListBox :: GetCurSel將返回所選索引。

如果CListBox處於多選模式,則應使用CListBox :: GetSelItems,它將返回索引列表。

您不能混合使用功能。

並始終檢查返回碼(就像其他人已經寫過的一樣)。

如果您已經有一個數據成員MyList(屬於classCListBox):

int nSel = MyList.GetCurSel();
    CString ItemSelected;
    if (nSel != LB_ERR)
    {
        MyList.GetText(nSel, ItemSelected);
    }

CWnd類具有一個MessageBox函數,該函數不需要HWND參數。 但是,是的, AfxMessageBox更加易於使用,並且可以在MFC代碼中的任何位置調用而無需CWnd派生的對象。 還有一個注意事項:如果在MFC代碼中調用WinAPI函數(此處不需要,但是在其他情況下可能是),最好在范圍解析運算符前添加它,以避免任何混淆,錯誤和/或名稱沖突(例如:: MessageBox ...)。

OP代碼中“無效參數”錯誤的一種可能原因是,它在UNICODE構建配置中使用了ANSI字符串文字(“ TEST”)。 在這種情況下,必須使用UNICODE字符串文字(L“ TEST”)或更好一點,使用_T宏(_T(“ TEST”)),以便可以在ANSI和UNICODE配置中進行構建。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM