Visual Basic 2005 for Programmers (2nd Edition)
14.7. CheckedListBox Control
The CheckedListBox control derives from class ListBox and includes a CheckBox next to each item. As in ListBoxes, items can be added via methods Add and AddRange or through the String Collection Editor. CheckedListBoxes imply that multiple items can be selected, and the only possible values for the SelectionMode property are None and One. One allows multiple selection, because CheckBoxes imply that there are no logical restrictions on the itemsthe user can select as many items as required. Thus, the only choice is whether to give the user multiple selection or no selection at all. This keeps the CheckedListBox's behavior consistent with that of CheckBoxes. Figure 14.19 lists some common properties, a common method and a common event of class CheckedListBox.
Common Programming Error 14.1
Event ItemCheck occurs when a user checks or unchecks a CheckedListBox item. Event argument properties CurrentValue and NewValue return CheckState values for the current and new state of the item, respectively. A comparison of these values allows you to determine whether the CheckedListBox item was checked or unchecked. The CheckedListBox control inherits the SelectedItems and SelectedIndices properties from class ListBox. It also includes properties CheckedItems and CheckedIndices, which return information about the checked items and indices. In Fig. 14.20, class FrmCheckedListBoxTest uses a CheckedListBox and a ListBox to display a user's book selections. The CheckedListBox allows the user to select multiple titles. In the String Collection Editor, we added items for some Deitel booksC++, Java, Visual Basic, Internet & WWW, Perl, Python, Wireless Internet and Advanced Java (the acronym HTP stands for "How to Program"). The ListBox (named lstDisplay) displays the user's selections. Figure 14.20. CheckedListBox and ListBox used in a program to display a user selection.
When the user checks or unchecks an item in chklstInput, an ItemCheck event occurs and event handler chklstItem_ItemCheck (lines 520) executes. An If...Else statement (lines 1519) determines whether the user checked or unchecked an item in the CheckedListBox. Line 15 uses the ItemCheckEventArgs property NewValue to determine whether the item is being checked (CheckState.Checked). If the user checks an item, line 16 adds the checked entry to lstDisplay. If the user unchecks an item, line 18 removes the corresponding item from lstDisplay. This event handler was created by selecting the CheckedListBox in Design mode, viewing the control's events in the Properties window and double clicking the ItemCheck event. |