MFC - List Control


Encapsulates the functionality of a List View Control, which displays a collection of items each consisting of an icon (from an image list) and a label. It is represented by CListCtrl class. A list control consists of using one of four views to display a list of items.

  • Icons
  • Small Icons
  • List
  • Report

Let us look into a simple example by creating a new MFC dialog based application.

Step 1 − Delete the TODO line and drag one List Control.

Step 2 − In the Properties Window, you will see the different options in View dropdown list.

List Control

Step 3 − Select the Report from the View field.

Step 4 − Add control variable m_listCtrl for List Control.

Add List Control Var

Step 5 − Initialize the List Control in OnInitDialog()

BOOL CMFCListControlDlg::OnInitDialog() {
   // Set the icon for this dialog. The framework does this automatically
   // when the application's main window is not a dialog
   SetIcon(m_hIcon, TRUE);         // Set big icon
   SetIcon(m_hIcon, FALSE);         // Set small icon

   // TODO: Add extra initialization here
   // Ask Mfc to create/insert a column
      0,              // Rank/order of item 
      L"ID",          // Caption for this header 
      LVCFMT_LEFT,    // Relative position of items under header 
      100);           // Width of items under header
   m_listCtrl.InsertColumn(1, L"Name", LVCFMT_CENTER, 80);
   m_listCtrl.InsertColumn(2, L"Age", LVCFMT_LEFT, 100);
   m_listCtrl.InsertColumn(3, L"Address", LVCFMT_LEFT, 80);
   int nItem;

   nItem = m_listCtrl.InsertItem(0, L"1");
   m_listCtrl.SetItemText(nItem, 1, L"Mark");
   m_listCtrl.SetItemText(nItem, 2, L"45");
   m_listCtrl.SetItemText(nItem, 3, L"Address 1");
   nItem = m_listCtrl.InsertItem(0, L"2");
   m_listCtrl.SetItemText(nItem, 1, L"Allan");
   m_listCtrl.SetItemText(nItem, 2, L"29");
   m_listCtrl.SetItemText(nItem, 3, L"Address 2");

   nItem = m_listCtrl.InsertItem(0, L"3");
   m_listCtrl.SetItemText(nItem, 1, L"Ajay");
   m_listCtrl.SetItemText(nItem, 2, L"37");
   m_listCtrl.SetItemText(nItem, 3, L"Address 3");

   return TRUE; // return TRUE unless you set the focus to a control

Step 6 − When the above code is compiled and executed, you will see the following output.

List Control Output