CListBox MFC class does not have its own way of handling a check box inside the list box. That is why MFC provides another class CCheckListBox which enables a programmer to embed check boxes inside a list box.
CCheckListBox is derived from CListBox with features to support check boxes inside the list box. This is an owner drawn control, because this class internally involves some additional handling of the screen. So before using this CCheckListBox, the Owner Draw style must be set for this class.
This article explains how to use the CCheckListBox class to handle check box inside a list box.
Using CCheckListBox instead of CListbox for adding Check Boxes:
For a programmer who already knows how to use CListBox class, it is a very trivial matter to do this job. It is just a matter of making the CListBox owner draw type and declare the list box variable from CCheckListBox. The following are the brief steps required to make a List box use check boxes.
- Create a MFC Dialog based application with a list box. This sample assumes the application name to be MFC Sample.
- Create the necessary classes required for the dialog box.
- In the Resource Editor –> List Box –> Properties –> Styles tab, set the Owner Draw Property of the List box to Fixed. Check the Has Strings property also.
- Declare a member variable for the list box using Class Wizard –> Member Variables Tab. This will create a variable of type CListBox.
- Open the MFCSampleDlg.h file and modify the CListBox variable declaration as follows.
Existing Declaration for List Box: CListBox variablename;
Modify the declaration for CListBox: CCheckListBox variablename;
- Now the list box can be used normally for adding items. The function CListBox.AddString is available also in CCheckListBox. This can be used to add the strings to the list box.
Using the Check Boxes in CCheckListBox:
Once the control is in place with the proper styles set and the declaration with CCheckListBox, then verifying if an item is Checked or Unchecked is a trivial task. The function CCheckListBox . SetCheck() can be used to check or uncheck an item inside a list box and CCheckListBox . GetCheck() function can be used for retrieving if an item is checked or Unchecked.
GetCheck function returns a integer value. If an item is checked, it returns 1 and 0 if it is unchecked. Similarly SetCheck takes parameter values 0 or 1 for unchecked and checked status respectively. The value 2 is used for an indeterminate state of the list box ( CCheckListBox ) control.