Professional Documents
Culture Documents
COntrol.
the CheckedListBox
Let's now learn how to use
Control
Explaining the CheckedListBox of check box and list box control where a ListBox control
The CheckedListBox is a combination allows you to select the list of items through the
check box Control in the left side. It
CheckedListBox class is follow: display
respective check
boxeswi, thty
The inheritance hierarchy of the
System.Object
System. MarshalByRe fobject
System. ComponentModel.Component
System. Windows . Forms. Control
System.Windows.Forms . Listcontrol
System.Windows . Forms .ListBox
System.WindowS. Forms.CheckedListBox
properties, methods. and oo
Similar to other controls, the CheckedListBox control has several
an application.
accessed and customized (optionally) as per the requirements of class:
CheckedListBox
Table 5.20 lists the noteworthv properties of the
ListBoxClass
Table 5.20: Noteworthy Properties of the Checked
Description
Property
CheckedIndi ces Contains the collection of checked indexes in a checked list box
CheckedItems Contains the collection of checked items in a checked list box
should be toggled when the
CheckornClick Retrieves or sets a value indicating if a check box
corresponding item is selected
box
Items
Returnsa collection of items in a checked list
3-D
whether or not check boxes have a flat or
ThreeDCheckBoxes Retrieves or sets a value indicating
appearance multiple
whether the checked list box allows
Multicolumn Retrieves or sets a value indicating
columns or not
selected item in a checked list box
SelectedIndex Retrieves or sets the index of the start Wiu a
collection containing zero-based indices (indexes always
selected items in
SelectedIndices Retrieves a all currently
indices) of
hence, they are also called zero-based
checked list box
checked list box
SelectedItem Retrieves or sets the selected item in a
list box
selected items in a checked checked
SelectedItems Retrieves a collection containing the of the
list box
for the items checked listbox
SelectionMode Retrieves or sets thee current selection mode items in a
or not the
Sorted Retrieves or sets a value indicating whether
should be sorted alphabetically
a checked list box
Text Retrieves the text of the selected item in
200
Windows Forms Controls-l
of
lists noteworthy events the CheckedListBox class:
Table 5.22
Table58.22: Noteworthy Events of the CheckedListBoxClass
Description
Event
Occurs when a user clicks a checked list box
click
ItemCheck
Occurs when the checked state of an item changes in a checked list box
SelectedIndexChanged Occurs when the SelectedIndex property of a Checked ListBox control is changed
in a checked list box by using the Items property. By default, a user has to double-click the
access items
You can box to select the item. However, you can change this default behaviour of the checked list
checked list
itemin the
its CheckOnClick property to True, which allows the user to select an item as soon as it is clicked.
box by setting the selected items in a checked list box by using the CheckedItems and CheckedIndices
You can retrieve
properties. You Can also use the GetItemChecked method to verify whether an item is selected in a checked list
addition, you can use the ItemCheck event to handle the check-state events of an item in a checked list
box. In select or clear items
hox and the SetItemChecked method to
Checked ListBox control supports similarly the check box three states by using the CheckState enumerations:
ne dIndeterminate, and Unchecked. You must set the indeterminate state of the checked list box from the
iebehind file because the user interface does not provide a way for setting this state. To use the three state
check boxes, use the GetltemCheckState and SetltemCheckState methods instead of the GetitemChecked and
Setltem Checked methods.
In a Checked ListBox control, you can add items, set and retrieve the check state of items, and handle the
lemCheck event of the control. You are going to learn how to perform all these actions in an application. Let's
Create an application named CheckedListBoxSample (also available in the CD-ROM), Perform the following task
after creating the application:
1 Set the Text property of the Forml to Checked List Box Sample.
2 Add a checked list box, three buttons, and a text box controls to the Form1. The following is a list of the
captions for the buttons along with a description of the functions they perform in the application:
Fillitems- Fills the checked list box with items
Unchecked items -Clears some of the selected items in a checked list box
Find checked Retrieves the selected items
The text box is used to display the selected items in the checked list box.
We are going to perform the following broad-level steps to create the Checked ListBoxSample application:
3 Add items to the
4
CheckedListBox control
Set the check state of the items in the CheckedListBox control
5
Ketrieve the check state of the items in the CheckedListBox control
Handle the ItemCheck event of the CheckedListBox control
Let's now perform the each step one by
one.
AddiYoung caanItems to the CheckedListBox Control
add items to checked list boxes similarly to add the items to standard list box. As already seen, in a
standard list box, you pass asingle argument to the Items.Add method, that is, the name of the item. However,
Itenmee of a checked ist box. vou can also add another argument (True or False) through code to the
1Add methodthewhile
1. Double-click Fill addine items toat the
items button checked
design list box.
tíme and Perform
add the the following
following stepsshown
code snippet to complete this task:
in Listing 5.6 to
Code Editor:
Listing 5.6: Adding Items to aChecked List Box
Private Button1.CliCk
Hand1es Sub Buttonl_LClick(Byval sender As System.0bject, Byval e As
System.EventArgs)
VMango
Grpes
Orange
Aple
Banana
Guva
Mango
Grapes
Orange
Aocle
Earnana
Guevs
Fnd Ohecked
Grapes
Orange
Aople
Barana
Guava
203
Chapter 5
ComboBox class:
Table 5.25 lists noteworthy events of the
ComboBoxClass
Table 5.25: Noteworthy Events of the
Event Description
DropDoNn Occurs when the drop-down portion of a combo box is displawo:d
DropDoWnClosed Occurswhen the drop-down portion of a combo box is no longer
visible
DropDownStyleChanged Occurs when the DropDownStyle property of a ComboBox control
has
SelectedIndexChanged Occurs when the SelectedIndex property of a ComboBox control has changed
SelectionChangeComnitted changed
Occurs when the selected item has changed and the change appears ina comk
and set the text of the combo box.
You can use the Text property of a combo box to access The
property of combo box control is used to get the index of the selected item. Similar to list boxes, if no items areSelectedlndey
selected, the SelectedIndex value is set to -1. If the first item in the list is selected, the Selected Indas
are
to 0.
Moreover, vou can also use the Selectedltem property to return the selected item from a combo boy T.
Items.Count property returms the number of items present in the combo box. The value of the Items.Coumi
index value is zero-based
property is always one more than the largest possible index value because the
Items.Insert, Items.Clear.
You can also add or delete items in a ComboBox control by using the Items.Add,
Items.AddRange,Items.Remove, or Items. RemoveAt method. Alternatively, you can add and remove items by
using the Items property at design time.
By default, a combo box displays a text box with a hidden drop-down list. The DropDownStyle property
set this property to display the list box of the
determines the style of the combo box to be displayed. You can
combo box in the following combo box styles: and you must click the arron
DropDown-Specifies that the text portion of the combo box is not editable
button to view the drop-down list. This is the default drop-down style. click the arrow button to vie ue
DropDownList-Specifies that the text portion is editable and you must
drop-down list.
Simple-Specifies that the drop-down list is always displayed.
TIP
box.
Todisplay a drop-down list that cannot be edited. use a list box instead of a combo combobox
without
number of items to a item inthe
You can use the BeginUpdate and EndUpdate methods to add a large allow you to search for an the Text
redrawing the control each time an item is added to the list. These methods of list boxes, you Can
use
list that contains a particular search string. Similar to the Text box property
part of a combo bOX.learn how can youThis use
property of a combo box to specify the string displaved in the text CD-ROM) to
. Let's create an application named ComboBoxSample (also available in the
the Form1 to Combo Box
Sample.
forthe
the ComboBox control in your application. Set the Text property offollowing is a list of
the captions
a
application contains combobox, four and a text
buttons, The
box.
buttons along with a description of the functions they perform in the application:
Fill combo box -Fills the combo box with items
Get selected-Gets theitems selected in the combo box
Sort items-Sorts the items in the combo box
Storing objects -Stores objects in the combo box
A text box is used to display the selected items in the combo
boOx.
Perform the following broad-level steps to create the ComboBoxSample applicatiorn:
1 Add items in the ComboBox control
2 Set the drop-down style of the ComboBox
3.
control
Display the selected items of the ComboBox control
206
WindowsForms Controls-!
combo down (the list is always and you have to make sure to provide space for it when you add the
are the box to the form), and another
open,combo boxes, where users can only select items from alist. The following
enumeratiodin:fferent settings for the DropDownStyle property that are also members of the Combo BoxStyle
207
Chapter5
O DropDown-Includes a
drop-down list and a text box. It is the default setting for combo
select from the list or tvpe in the text box, as
shown in Figure 5.65:
Combo Box Sampie
box.bo AuseT o
Rcombe box
tem 0
Get seiected
em
tem 5
tem 6
Sat tems tem 7
tem 8
tem 9
tem 11.
tem 12
Song objects tem 13
tem 14
tem 15
tem 15
tem 17
tem 18
tem 19
tem 20
Song obyects
combo bax
ten 10
Pm T
Ben 19
Borm 20
Sorng objects
Figure 5.68: Displaying the Selected Item and Index of a Combo Box in a Text Box
TIP
You can restrict the input from users so that they are unable to add items to a combo box by setting the DropDown Style
property
box.
ofthe combo box to
DropDownList. In this style of combo boxes, the user cannot typein the text part of the combo
14
tem 16
9tomg obets
210
Windows Forms Controls-!
to
store texxt data for each item. Each item in alist box or combo box is itself an object. We start by
allowedi you and an object to show how you can store additional data for each item in the combo box.
oWn class
creatingour
works, create a new class named Dataltem, and each item that you create in the combo box will
hoOwthis class stores the name of each comnbo box item and some data, and the constructor
Toseeobject ofthis. class. This
for each item in private data members, as shown in Listing 5.13:
le an the name and data
willstore Storing the Name and Data for Each Item ina Combo Box
Listing :
5.13:
Public Class DataItem
Single
Private Data As String
Private Name As
Public Sub New(ByVal NameArgument AS String, Byval value As Single)
Name = NameArgument
Data = Value
End Sub
Overrides Function ToString() As String
Return CStr(Name)
End Function
Public Functi on GetData () As Single
Return Data
End Function
End Class
tng 513, the ToString method of the object class is overridden because this method is called when the
boN needs to display the name of each item. In addition, the GetData method is also added to get the data
nm the objects. When the form is loaded, you can create 21objects of the Dataltem class. For example, the fifth
iom in the combo box will be named Item 5, with an internal value of 5. You can add and place the items in the
combo box by using the Items.Add method. To do this, double-click the Storing objects button and add the code
snippet given in Listing 5.14:
Listing 5.14: Storing Objects Using the Add Method
Private Sub Button4_click (Byval sender As System .object, Byval e As System. EventArgs)
Handles Button4.C1ick
ComboBox1. Items.clear()
Dim Objects (20) AsDataItem
Dim intLoopIndex AsInteger
For intLOopIndex = 0 To 20
objects (intLoopIndex) = NewDataItem ("object "& intLoopIndex,
CSng (intLoopIndex) )
Next
ComboBox1. Items . Add (0bjects (intLoopIndex))
ComboBox1. Text = "Select one. .."
End Sub
ress the F5 key to run the application and click the Storing objects button to store the objects in
control, as shown in Figure 5.71: ComboBox1
Combo Box Sample
211
Chapter5
Method
Using the AddRange Dataltem objects in an array, you
can use
As vou have stored the another way to add these
AddRange method to add all the objects in the
the
or list box. You can use
the following highlighted
shown in Listing 5.15 to the click event
code
Method
array to the of ite
Sorting objects button:ms to a
combo bOx at onccomtgy
Objects by Using the AddRange
Listing 5. 15: StoringButton4_Click(Byval sender AS System.Object, Byval
Private Sub e As
Handles Button4.click
ComboBoxl. Items. ClearO
DataItem
System. EventArgs)
Dim Objects (20) As Integer
Dim intLoopIndex As To 20
0
For intLoopIndex = (intLoopIndex) = NewDataItem ("object "&
objects
CSng (intLoopIndex) ) (intL0opIndex))
intLoopIndex,
Combo8ox1.Items . Add (0bjects
Next
ComboBox1. Text = "Select one. ..
ComboBox1. Items.AddRange (objects)
End Sub
Press the F5 key to execute the application and CClick the Storing objects button. When you execute the code
method, the result is the same, as shown in: e l
using either the Add method or the AddRange
Combo Box Sanple
Somg,objecds
Box
Figure 5.72: Storing Objects in a Combo
212
Windows Forms Controls-I
em
Sot lens
Satng obyets
Kogert
End Sub
In Listing 5.16, when an item in the combo box is selected, you can use the Selectedltem property to getthe
selected object. You can us the GetData method of the selected object to get its stored data (note that the item has
to be cast to an object of the Dataltem class first before it can be displayed in a text box).
Press the F5 key to execute the application. Click the Storing objects button and then select an item from the
combo box. The output is shown in Figure 5.74, which shows the response to aSelectedindexChanged event:
Combo Bax Sample
FA canbo bex
cbyet
eci
Get seiected
Stong cbyea
SurRinthismarchTextchaptyBox,erI, MaskedTextBox, ListBox, CheckedListBox, and ComboBox, This chapter also discussed the
In
you have learned about some standard Windows Forms controls, such as Button, Label, TextBox,
Q2.
(contro) required by the classes that display
the Systenm Windows.Forms namespace.
information to and
the user. The Control SiZe ol
Which method is used to generate the click event of the Control class for a Button
functionalits
a
class is placcedompoinnsie
Ans The Button class has a PerformClick method used to generate the control?
System. Windows Forms Control class, The PerformClick Click event of
method is invoked for buttonl
buttonl. Performclick() as he
What is the RichTextBox control?
fol ows
Q3.
Ans The RichTextBox control is used for displaying, entering, and manipulating rich
is similar to the TextBox control, but it lets you make the text of a RichTextBox text with
control
underlined, change the color of the text, select font design and font sizes. You can bold, italicG, and formattingh
RichTextBox Control to a rich text format (RTF) file, and load the text of a RTF fileiinsave the text of a
a
control. RichTextBoy
Q4. Can we display an image or icon on a Button control?
Ans The Button class consist the Image property,which is used to set an image on the Button control. You
also set the alignment of the image by using the ImageAlign property of the Button clas.
Q5. What is the use of PasswordChar property?
Ans. The Password Char property is used to set the password character to mask original characters entered by
users.
Q6. How can you auto size a button to fit its text?
Ans
The Button control has the AutoSize property, which can be set to true or false. If we set the value of the
AutoSize property to true, then the button control automatically alters its size according to the content
displayed on it.
Q7. What are the three states set in a Check State property of Checkbox?
Ans The three states of the CheckState property are:
O Checked
O Unchecked
Indeterminate
What is the difference between the Add) and Insert) methods of a ListBox control? the
Q8. insert an itemat
Ans. The Add) method simply adds anitem into the list box, whereas the Insert) method
specified index.
Q9. What is the difference between a ListBox control and a ComboBox control? ComboBox
control, whereas with a
Ans. You can only make a selection from a list of items from ListBox
control, the user can make a selection from the list of items as well as can make its own enuy
Q10. What does the DialogResult property of a Button control do? thebuttonis
form when
Ans. The DialogResult property retrieves or sets a value that is returned to the parent
clicked. This property is used to create dialog boxes.
214