MFC - Tree Control


Advertisements

A Tree View Control is a window that displays a hierarchical list of items, such as the headings in a document, the entries in an index, or the files and directories on a disk. Each item consists of a label and an optional bitmapped image, and each item can have a list of subitems associated with it. By clicking an item, the user can expand and collapse the associated list of subitems. It is represented by CTreeCtrl class.

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

Step 1 − Once the project is created you will see the TODO line, which is the Caption of Text Control. Remove the Caption and set its ID to IDC_STATIC_TXT.

Step 2 − Add a value variable m_strTree for the Static Text control.

Tree Control

Step 3 − From the Controls toolbox, drag the Tree Control.

Drag Tree Control

Step 4 − On the dialog box, click the Tree Control to select it. On the Properties window, set the Has Buttons, the Has Lines, the Lines At Root, the Client Edge and the Modal Frame properties to True.

Step 5 − Add a control variable m_treeCtrl for Tee Control.

Add Tree Control Var

Step 6 − Here is initialization of tree control in OnInitDialog()

BOOL CMFCTreeControlDlg::OnInitDialog() {
   CDialogEx::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
   HTREEITEM hItem, hCar;
   hItem = m_treeCtrl.InsertItem(L"Car Listing", TVI_ROOT);
   hCar = m_treeCtrl.InsertItem(L"Economy", hItem);
   m_treeCtrl.InsertItem(L"BH-733", hCar);
   m_treeCtrl.InsertItem(L"SD-397", hCar);
   m_treeCtrl.InsertItem(L"JU-538", hCar);
   m_treeCtrl.InsertItem(L"DI-285", hCar);
   m_treeCtrl.InsertItem(L"AK-830", hCar);
   hCar = m_treeCtrl.InsertItem(L"Compact", hItem);
   m_treeCtrl.InsertItem(L"HG-490", hCar);
   m_treeCtrl.InsertItem(L"PE-473", hCar);
   hCar = m_treeCtrl.InsertItem(L"Standard", hItem);
   m_treeCtrl.InsertItem(L"SO-398", hCar);
   m_treeCtrl.InsertItem(L"DF-438", hCar);
   m_treeCtrl.InsertItem(L"IS-833", hCar);
   hCar = m_treeCtrl.InsertItem(L"Full Size", hItem);
   m_treeCtrl.InsertItem(L"PD-304", hCar);
   hCar = m_treeCtrl.InsertItem(L"Mini Van", hItem);
   m_treeCtrl.InsertItem(L"ID-497", hCar);
   m_treeCtrl.InsertItem(L"RU-304", hCar);
   m_treeCtrl.InsertItem(L"DK-905", hCar);
   hCar = m_treeCtrl.InsertItem(L"SUV", hItem);
   m_treeCtrl.InsertItem(L"FE-948", hCar);
   m_treeCtrl.InsertItem(L"AD-940", hCar);
   hCar = m_treeCtrl.InsertItem(L"Truck", hItem);
   m_treeCtrl.InsertItem(L"HD-394", hCar);

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

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

Tree Control Output
mfc_windows_controls.htm
Advertisements