This example inherits the built-in CheckedListBox control and extends its functionality. If you are not familiar with this control, it works just like a normal ListBox control except that selected items are indicated with a check in a check box at the front of the item, rather than by highlighting the item.
To extend the functionality of this control, the example includes the creation of a property called MaxItemsToSelect. This property holds a maximum value for the number of items that a user can select. The event that fires when a user checks an item is then monitored to determine whether the maximum has already been reached.
If selection of another item would exceed the maximum number, then the selection is prevented, and an event is fired to let the consumer form know that the user has tried to exceed the maximum limit. The code that handles the event in the form can then do whatever is appropriate. In this case, a message box is used to tell the user that no more items can be selected.
The DefaultValue, Description, and Category attributes are placed on the MaxItemsToSelect property to coordinate with the IDE.
Here is the step-by-step construction of our example:
1. Start a new Windows Control Library project in Visual Studio and name it MyControls. In the Solution Explorer, select the UserControl1.vb file, right-click it, and delete it.
2. Select Project O Add New Item, and select the item template called Custom Control. Name the item LimitedCheckedListBox.
3. Click the button in the Solution Explorer to show all files for the project. Bring up the file LimitedCheckedListBox.Designer.vb, which is found by clicking the plus sign next to LimitedCheckedListBox.vb. (If you don't see a plus sign next to LimitedCheckedListBox.vb, click the Show All Files button at the top of the Solution Explorer.)
4. At the top of the LimitedCheckedListbox.Designer.vb code, look for the line that reads as follows: Inherits System.Windows.Forms.Control
5. Change that line to the following:
6. Close LimitedCheckedListbox.Designer.vb and open LimitedCheckedListBox.vb in the Code Editor. Add the following declarations at the top of the code (before the line declaring the class):
This enables you to utilize the attributes required from the System.ComponentModel namespace.
7. The code for LimitedCheckedListBox.vb will contain an event for painting the control. Since you are not using a control that draws its own surface, delete that event. (It won't hurt to leave it, but you don't need it.)
8. Begin adding code specifically for this control. First, implement the MaxItemsToSelect property. A module-level variable is needed to hold the property's value, so insert this line just under the class declaration line:
Private _nMaxItemsToSelect As Integer = 4
9. Create the code for the property itself. Insert the following code into the class just above the line that says End Class:
Description("The maximum number of items allowed to be checked")> Public Property MaxItemsToselect() As Integer Get
Return _nMaxItemsToselect End Get set(ByVal Value As Integer) If Value < 0 Then
Throw New ArgumentException("Property value cannot be negative") Else
_nMaxItemsToselect = Value End If End set End Property
This code sets the default value of the MaxItemsToselect property to 4, and sets a description for the property to be shown in the Properties window when the property is selected there. It also specifies that the property should appear in the Behavior category when properties in the Properties window are sorted by category.
10. Declare the event that will be fired when a user selects too many items. The event is named MaxItemsExceeded. Just under the code for step 9, insert the following line:
Public Event MaxItemsExceeded(sender As Object, e As EventArgs)
11. Insert code into the event routine that fires when the user clicks on an item. For the CheckedListBox base class, this is called the ItemCheck property. Open the left-hand drop-down box in the code window and select the option LimitedCheckedListBox Events. Then, select the ItemCheck event in the right-hand drop-down box of the code window. The following code will be inserted to handle the ItemCheck event:
Private sub LimitedCheckedListBox_ItemCheck(ByVal sender As Object, ByVal e As system.Windows.Forms.ItemCheckEventArgs) _ Handles Me.ItemCheck
Code snippet from LimitedCheckedListBox
12. The following code should be added to the ItemCheck event to monitor it for too many items:
Private sub LimitedCheckedListBox_ItemCheck(ByVal sender As Object, ByVal e As system.Windows.Forms.ItemCheckEventArgs) _ Handles MyBase.ItemCheck If (Me.CheckedItems.Count >= _nMaxItemsToSelect) _ And (e.NewValue = CheckState.Checked) Then RaiseEvent MaxItemsExceeded(Me, New EventArgs) e.NewValue = CheckState.Unchecked End If
Code snippet from LimitedCheckedListBox
13. Build the project to create a DLL containing the LimitedCheckedListBox control.
14. Add a new Windows Application project to the solution (using the File O Add Project O New Project menu) to test the control. Name the new project anything you like. Right-click the project in the Solution Explorer, and select Set as Startup Project in the pop-up menu. This will cause your Windows application to run when you press F5 in Visual Studio.
15. Scroll to the top of the controls in the Toolbox. The LimitedCheckedListBox control should be there.
16. The Windows Application project will have a Forml that was created automatically. Drag a LimitedCheckedListBox control onto Forml, just as you would a normal list box. Change the
CheckOnClick property for the LimitedCheckedListBox to True (to make testing easier). This property was inherited from the base CheckedListBox control.
In the Items property of the LimitedCheckedListBox, click the button to add some items. Insert the following list of colors: Red, Yellow, Green, Brown, Blue, Pink, and Black. At this point, your Windows Application project should have a Form1 that looks something like Figure 15-2.
Bring up the code window for Form1. In the left-hand drop-down box above FiGURE 15-2 the code window, select LimitedCheckedListBoxl to get to its events.
Then, in the right-hand drop-down box, select the MaxItemsExceeded event. The empty event will look like the following code:
Private Sub LimitedCheckedListBox1_MaxItemsExceeded(
ByVal sender As System.Object, e As System.EventArgs) _ Handles LimitedCheckedListBoxl.MaxItemsExceeded
Code snippet from LimitedCheckedListBox
Insert the following code to handle the event:
MsgBox("You are attempting to select more than " & LimitedCheckedListBoxl.MaxItemsToSelect & " items. You must uncheck some other item " & " before checking this one.")
20. Start the Windows Application project. Check and uncheck various items in the list box to verify that the control works as intended. You should get a message box whenever you attempt to check more than four items. (Four items is the default maximum, which was not changed.) If you uncheck some items, then you can check items again until the maximum is once again exceeded. When finished, close the form to stop execution.
21. If you want to check the serialization of the code, look at the designer-generated code in the partial class for Form1 (named LimitedCheckedListBox.Designer.vb), and examine the properties for LimitedCheckedListBoxl. Note that there is no line of code that sets MaxSelectedItems. Remember that if you don't see the partial class in the Solution Explorer, then you'll need to press the Show All button at the top of the Solution Explorer.
22. Go back to the Design view for Form1 and select LimitedCheckedListBox1. In the Properties window, change the MaxSelectedItems property to 3.
23. Return to the partial class and look again at the code that declares the properties for LimitedCheckedListBox1. Note that there is now a line of code that sets MaxSelectedItems to the value of 3.
24. Go back to the Design view for Form1 and select LimitedCheckedListBox1. In the Properties window, right-click the MaxSelectedItems property. In the pop-up menu, select Reset. The property will change back to a value of 4, and the line of code that sets the property you looked at in the last step will be gone.
These last few steps showed that the DefaultValue attribute is working as it should.
Was this article helpful?