Visual C++ MFC - CListCtrl - Get Current Selection
We have seen how to add items to MFC list control in the earlier section. If single selection option is enabled, then it is easy to identify the selected item by making a single call to CListBox::GetSelectionMark(). It returns the index / row number of the selected item. With the row id, we can use CListCtrl::GetItemText to get the string values in the MFC list control.
Source Code
class CSiteMapDlg : public CDialog
{
enum { IDD = IDD_TEST_DIALOG };
public:
CListCtrl m_listCtrl;
}
void CMyTestDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_LIST1, m_listCtrl);
}
BEGIN_MESSAGE_MAP(CMyTestDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_NOTIFY(NM_DBLCLK, IDC_LIST1, &CMyTestDlg::OnNMDblclkList1)
END_MESSAGE_MAP()
void CMyTestDlg::OnNMDblclkList1(NMHDR *pNMHDR, LRESULT *pResult)
{
int row = m_listCtrl.GetSelectionMark();
if(row < 0)
return;
CString s1 = m_listCtrl.GetItemText(row, 0);
CString s2 = m_listCtrl.GetItemText(row, 1);
CString s3 = m_listCtrl.GetItemText(row, 2);
}
Click here to download the Visual C++ Project and Executable
Output
|