You can see a checkbox list at work in the CheckBoxes example on the CD-ROM, and in Figure 16.1. The checkbox list is on the right, showing the items Cheese, Sausage, Tomato, and Ham. To add items like that to a checkbox list, click the ellipsis ("...") button in the Items property in the Properties window.
Clicking the ellipsis button opens the ListItem Collection Editor, as you see in Figure 16.6. This collection editor works much like other collection editors-to add a new item to the checkbox list control, click the Add button, and fill in its Text (the checkbox's caption), Value (holds optional text associated with the checkbox), and Selected (set this to True to make the corresponding checkbox appear selected initially) properties. You also can add checkboxes to a checkbox list at run time, using the Add method of the control's Items collection.
To determine which items in a checkbox list are checked, you can loop over the items in the control and examine their Selected properties. Here's how that works in the CheckBoxes example on the CD-ROM, which you see at work in Figure 16.1. (You can view the full code for this example in "Creating Checkboxes" in this chapter.) When the user clicks an item in the checkbox list, the SelectedIndex event occurs, and in that event's handler, I loop over the items in the control and display the values of those selected in a text box, this way:
Private Sub CheckBoxList1_SelectedIndexChanged(ByVal sender _ As System.Object, ByVal e As System.EventArgs) Handles _ CheckBoxList1.SelectedIndexChanged Dim LoopIndex As Integer TextBox2.Text = "Filling: " For LoopIndex = 0 To 3 If CheckBoxList1.Items(LoopIndex).Selected Then TextBox2.Text &= _ CheckBoxList1.Items(LoopIndex).Value & " " End If Next End Sub
Tip |
As mentioned in the In Depth section of this chapter, you also can use the SelectedItem or SelectedIndex properties in checkbox lists, but note that these lists can support multiple selections. If multiple items are selected, the SelectedItem and SelectedIndex properties hold the selected item with the lowest index value, and the index value of the selected item with the lowest index value, which tells you nothing about the other selected items. |
Note |
Don't forget-if you want to handle this control's events immediately, you must set its AutoPostBack property to True. |