MFC List Box Control Example
#include <afxwin.h>
#define ID_ADDBUTTON 1000
#define ID_DELETEBUTTON 1001
#define ID_AMENDBUTTON 1002
#define ID_EDIT 1003
#define IDC_LIST1 1004
class CSimpleApp : public CWinApp
{
public:
BOOL InitInstance();
};
class CMainFrame : public CFrameWnd
{
public:
CMainFrame();
afx_msg void wAddButtonOnClick();
afx_msg void wDeleteButtonOnClick();
afx_msg void wAmendButtonOnClick();
afx_msg void wListBoxChange();
DECLARE_MESSAGE_MAP()
// Child controls
CButton wAddButton;
CButton wDeleteButton;
CButton wAmendButton;
CEdit wEdit;
CListBox wListBox;
};
BOOL CSimpleApp::InitInstance()
{
m_pMainWnd = new CMainFrame();
m_pMainWnd->ShowWindow(m_nCmdShow);
return TRUE;
}
CMainFrame::CMainFrame()
{
Create(NULL,
TEXT("MFC List Box Example"),
WS_OVERLAPPEDWINDOW,
CRect(25,25,410,250));
// Create list box
wListBox.Create(WS_CHILD | WS_VISIBLE | LBS_STANDARD,
CRect(10,10,300,110),
this,
IDC_LIST1);
// Add initial items
wListBox.AddString(TEXT("Apple"));
wListBox.AddString(TEXT("Orange"));
wListBox.AddString(TEXT("Pear"));
// Create edit control
wEdit.Create(WS_CHILD | WS_VISIBLE | WS_BORDER,
CRect(10,110,300,140),
this,
ID_EDIT);
// Create buttons
wAddButton.Create(TEXT("Add"),
BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE,
CRect(10,150,70,180),
this,
ID_ADDBUTTON);
wDeleteButton.Create(TEXT("Delete"),
BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE,
CRect(80,150,140,180),
this,
ID_DELETEBUTTON);
wAmendButton.Create(TEXT("Amend"),
BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE,
CRect(150,150,220,180),
this,
ID_AMENDBUTTON);
}
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
ON_BN_CLICKED(ID_ADDBUTTON, wAddButtonOnClick)
ON_BN_CLICKED(ID_DELETEBUTTON, wDeleteButtonOnClick)
ON_BN_CLICKED(ID_AMENDBUTTON, wAmendButtonOnClick)
ON_LBN_SELCHANGE(IDC_LIST1, wListBoxChange)
END_MESSAGE_MAP()
CSimpleApp MFCApp1;
// Add an item to the list box
afx_msg void CMainFrame::wAddButtonOnClick()
{
CString strText;
wEdit.GetWindowText(strText);
if (!strText.IsEmpty())
{
int index = wListBox.AddString(strText);
wListBox.SetCurSel(index);
wEdit.SetWindowText(TEXT(""));
}
}
// Delete the selected item
afx_msg void CMainFrame::wDeleteButtonOnClick()
{
int index = wListBox.GetCurSel();
if (index != LB_ERR)
{
wListBox.DeleteString(index);
wEdit.SetWindowText(TEXT(""));
}
}
// Amend the selected item
afx_msg void CMainFrame::wAmendButtonOnClick()
{
CString strText;
wEdit.GetWindowText(strText);
int index = wListBox.GetCurSel();
if (!strText.IsEmpty() && index != LB_ERR)
{
wListBox.DeleteString(index);
wListBox.InsertString(index, strText);
wListBox.SetCurSel(index);
wEdit.SetWindowText(TEXT(""));
}
}
// Display the selected list box item in the edit control
afx_msg void CMainFrame::wListBoxChange()
{
int index = wListBox.GetCurSel();
if (index != LB_ERR)
{
CString strText;
wListBox.GetText(index, strText);
wEdit.SetWindowText(strText);
}
}