You are on page 1of 38

Chapter5

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

Table 5.21 lists noteworthy methods of the CheckedListBox class:


Table 5.21: Noteworthy Methods of the CheckedListBoxClass whichis
Method Description specifieditem
index of the
GetItemChecked Retrieves a value indicating whether or not the
passed as a parameter to this method is checked or not
GetItemCheckState checked list box box
Retrieves the check state of the current item in a checkedlist
a
GetSelected item is selected in
Retrieves a value indicating if the speecified
SetItenChecked
Selects the item at the specified index in a checked list box
SetItenCheckState checked list box
Retrieves the specified check state of an item inna
SetSelected checked list box
Selects or clears the selection for the specified itemin a

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)

CheckedListBoxl. Items. Add ("Mango" True)


201
Chapter5
True)
checkedL is tBOxl. Items. Add("Grapes",
Add("orange", False)
CheckedLis tBoxl. Items .
False)
CheckedL istBoxl, Items. Add("Apple",
("Banana"', True)
CheckedListBOxl, Items. Add
8oxl, I tems .Add("Guava'", False)
CheckedList
End Sub
and then click the Fill items button for
2 Press the F5 key to execute the application the
snippet. as shown in Figure 5.60: result of the coN,
Checked List Box Sarnple

VMango
Grpes
Orange
Aple
Banana
Guva

Lhcheck tems Fnd hecked

Figure 5.60: Displaying a Checked List Box with Items


with items and some of the items, such as
In Figure 5.60, after clicking, the Fill items button the list box filled
Mango, Grapes, and Banana, are selected.
Control
Setting the Check State of Items in the CheckedListBoxchecked list box by passing a value of
items in the
You can use the Setltem Checked mnethod to select or clear application to clear some of the selected tes
True or False, respectively. We use the CheckedListBoxSample
a checked list box.
following code snippet:
3 Double-click the Uncheck items button at design time and add the ByVal e As System. Eventy
obiect,
Private Sub Button2_click (Byval sender As System.
Handles Button2.click
CheckedListBox1. SetItemChecked (1, False)
CheckedListBox1. SetItemChecked (4, False)
End Sub
4 Press the 5 key to execute the application. in
shown
5 Click the Fill items button to fillthe Checked ListBox. Banana, as
and
6 Click the Uncheck items button to uncheck the checked items, such as Grapes
Figure 5.61:
Checied ist Bax Sample

Mango
Grapes
Orange
Aocle
Earnana
Guevs

Fnd Ohecked

Figure 5.61: Deselecting an Item in a Checked List Box


202
Windows Forms Controls-l

RetrievingtheCheck State of Items in the CheckedListBox Control


determine if an item displays a check mark in achecked list box by using the GetltemChecked method,
You can True if the item is selected. For example, in the Checked ListBoxSample application, you can loop
whichreturns
itemsin a checked list box and display the selected items in atext box. Perform thefollowing steps to
the
over all thistask:
complete
Double-click the Find Checked button and add the following code snippet shown in Listing 5.7 to Code
1
Editor:
the Check State of Items in a Checked List Box
Listingg 5.7: Retrieving
Private Sub Button3_Click (ByVal sender As System.object, ByVal e As System.EventArgs)
Handles Button3.Click
Dim intLoopIndex As Integer
Dim strText As String
strText = "Checked Items:
Eor intLoopIndex = 0 To (CheckedListBOx1.Items .Count - 1)
If CheckedLi stBox1. GetItemChecked(intLoopIndex) = True Then
strText &= CheckedListBox1. Items (intLoopIndex).TOString & ""
End If
Next
TextBox1. Text = strText
End Sub
2
Press F5 key to execute the application.
3 Click the Fill iterms button and then click the Find Checked button. The output is shown in Figure 5.62:
Checked List Box Sample

Grapes
Orange
Aople
Barana
Guava

Uhcheck lems Fnd Chedf

Oheckedd tema Mroo Grapes Barana

Figure 5.62: Determining the Items Checked in a Checked List Box


ere is another way for doing the same thing is to loop through the collection returned by the Checkedltems
property, which holds all the checked items, as shown in Listing 5.8:
Listing 5.8: Retrieving Checked Items by Using the Checkedltems Property
Private sub Button2_Click(ByVal sender As System.object, Byval e As System.EventArgs)
Handles Button2.C1ick
CheckedListBox1.SetItemChecked(1, False)
CheckedListBox1. SetItemChecked(4, False)
Dìm strText, strData As String
strText = "checked Items:
For Each strData In CheckedListBoxl.CheckedItems
StrText &= strData &"
Next
End Sub TextBox1. Text = strText
Besicontdaesining theCheckedIt
the
indexes eofmstheeproperty,
selected items
thereinisachecked
also thelist box.
CheckedIndices property, which returns a collection

HandlAn ing the ItemCheck Event of the CheckedListBox Control


ItemCheck event
ltNewValemCheuce.kEvTheentAIndexrgs member providesthe index ofthe item whose check state haschanged andthe NewValue
occurs when there is achange in the check state of an item in a checked list box. The
object passed to the ItemCheck event handler provides two members, Index and

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-!

number of items in the ComboBox control


Retrievethe
4.
Sortthe
iteems in the ComboBox control
ComboBox control
Store objects in the method to
5

6. AddRange add items to the ComboBox control


Usethe
Handlethe TextChanged and SelectedIndexChanged
details
events
8. steps one by one in
lofs perform allthese
the ComboBox Controls
Addling Itemsin
combo box is ahcombination of atext box and a list box. At design time, you can changethe text inthe text box
A
part of the
combo box by changing the Text property, and the items in the list box part by the Items property
(selecting this property in the Properties window opens the String Collection Editor dialog box, as discussed
(for the ListBox control) at design time. You can use the Items. Insert, Items.Add, and Items.AddRange
bods to add items to the list box part of a combo box. Perform the following steps to complete this task:
, Double-click the Fill combo box button at design time and add the following code snippet
shown in Listing
5.10 in Click event of Fill combo box button:
Listing 5.10: Adding Items in a Combo Box
Private Sub Buttonl_Click(ByVal sender As System.object, ByVal e As System. EventArgs)
Handles Buttonl. c1ick
ComboBox1. Items. Clear()
Dim intLoopIndex As Integer
For intLoopIndex = 0 To 20
ComboBox1. Items. Add("Item + intLoopIndex . TOString( )
Next
ComboBox1. Text = "Select one. .."
End Sub
2. Press the F5 key to execute the application.
3. Click the Fill combo box button to fill the ComboBox1 control. The output is shown in Figure 5.64:
Combo Box Sample

Fil combo bax


tem 0
em 1
Lem 2
Get seleced
tem 3
erm 4
lem 5
Iem b
Sort tems Ben 7
tem 8
tem 9
Berm 10O
tem 11
Stong cbjectn tem 12
Bem 13
tem 14
tem 15
tem 15
tem 17
Rem 18
hem 19
20

Figure 5.64: Populating Items in a Combo Box


SetYoutinmight
g thethinkDrop-down Style of the ComboBox Controls
is only one type of combo box, but there are actually three types of combo boxes. You
can select the typethatyoutherewant with the DropDownStyle property of the combo box. The default combo box is a
combination of
not drop a text box
and drop-down list. However, you can also have combo boxes where the list does
a

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

Figure 5.65: Displaying a DropDown Style of Combo Box


user can select items from the li
Simple-Includes a text box and a list, which does not drop doWn. The
Figure 5.66:
or tvpe in the text box, as shown in
6Combo Box Sample

Fcombo bax Select one


tem 0
tem 1
tem 2
Get seleted tem 3
tem 4
tem 5
kem 6
tem 7
Sot tens
tem 8

Song obyects

Style of Combo Box to Simple


by
Figure 5.66: Displaying a Simple property
the DropDownStyle
The Simple drop-down style combo box is created by setting you want to
properties window. is ideal when
drop-down list. This setting
DropDownList- Allows a selection only from the
restrict the input from the user, as shown in Figure 5.67:
Combbo Bax Sanple

combo bax

Get seecded tem


Ben
tem
tem
Sot tens tem

ten 10

Song objecs Pen 1


ten 14
tem 15
tem

Pm T
Ben 19
Borm 20

Figure 5.67: Displaying a DropDownList Style of Combo Box


208
Windows Forms Controls
DropDownList drop-down style combo box is created by setting the DropDownStyle property to
DropDownList,by properties
window.
The
Selected Items of a
Dsplayingthe, selection in a combo box, theComboBox Control
selection appears in the text box of the combo box. It is therefore
make a
Whenyou thetext of the current selection. To do so, you just use the Text property of the combo box. You can
easyto get
the SelectedIndex and Selectedltem properties to getthe index of the selected item and the selected item,
alsouse
respectively. You can displaythe currently selected item of a combo box in a text box by clicking the Get selected
ComboBoxSample application and using the code
snippet specified in Listing 5.11:
buttoninthe Selected Item and Selected Index
5.11: Displayingthe of a Combo Box
Listing
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e AS System.EventArgs)
Handles Button2.click
SelectedIndex > -1 Then
rf ComboBOxl.
pim selectedIndex AsInteger
selectedIndex = ComboBox1.Sel ectedIndex
pim selectedItem Asobject
selectedItem = ComboBox1 .selectedItem
TextBOxl.TextToString
= "selected
()
item text: "& selectedItem. ToString ) &" selected
index: "& selectedIndex.
EndIf
End Sub
Doss the F5 key toexecute the application. Click the Fillcombo box button and then select an item from the
combo box and click the Get selected button. The output is shown in Figure 5.68:
Combo Bax Sample

Rlcombo bax tem 3


tem
tem
Get selected tem
tem
tem 4
em 5

Sort tems tem


tem

Sorng objects

Selected ten text tem 3 Selected ndex 3

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

RetYourievitryng aNumber of Items in the ComboBox Controls


u
hard to make your program user-friendly by allowing a user to add items to a combo box. Howeve,
supposeto índyou
need want to know whether the user has added a particular item to the combo box. In such cases, you
new item. out the number of items present in the combo box and thern traverse through each item to find the
You can get the number of items in a combo box with the Items.Count property. Let's use the
CoListinmgb35.oBf1oo2:xlSoawimnpgle application
Add the to
highlighted
display the total number of items in a combo box.
code snippet:shown in Listing 5.12 in Click event of Buttonl control:
Handles
Displays
PrivateSubButton1.Click the Total Number of Items in a Combo Box
Buttonl_Cclick(Byval sender As System.object, Byval eAs System.Eventargs)
ComboBox1.ASInteger
Dim intLoopIndex Items .ClearO
209
Chapter 5
0 To 20
For intLoopIndex
ComboBOxl. Items , Add("Item " + intLoopIndex..
ToString ())
Next
ComboBoxl. Text "Select one..
box contains "&
Mes sageBox.Show( The combo
EndSub
ComboBoxl.Items.Count &" items.")
Press the F5 key to execute the application. Click the Fill combo box button. The output is sh
Combe ox Sampie
shown inFigurea

The conbe hox contans 21 tems

Figure 5.69: Displaying the Total Number of Items in a Combo Box

Sorting the Items in aComboBox Control


Suppose vou have been newly commissioned to write a guidebook in Visual Basic for azo0. Everything sen
name is stored but they are not present in e
ok, except for one thing that in a combo boxa list of animals
manner. Therefore, you want to sort the combo box items alphabetically. However, the zoo keeps addine ani
because you can leave the work up to b
trading animals all the time. Even so, this should not be a problem Sorted propert d
set the
combo box itself if you set its Sorted property to True (the default is False). Let's combo box. Perform te
to the
ComboBox1, to True. Now, it does not matter in what order you add the items
following steps to complete this task:
1. Double-click the Sort items button and add the following
code snippet in Click event of Button3 control:
object, ByVal e As System. EventArgs)
Private Sub Button3_click (Byval sender As System.
Handles Button3.Click
ComboBox1. Sorted = True
End Sub
2 Press F5 key to execute the application.
button. The output is
shown in Figure 5.70:
3 Cick the Fill combo box button and then click the Sort items
Combo Bax Saple

F combo bax Select one


tem 0
tem 1
Get sleded
tem 11

14

tem 16

9tomg obets

Figure 5.70: Sorting Items in a Combo Box


withallthe
Sorting Objects in the ComboBox Controls placea phoneproperty,
whih
combobox
numberstothe
write
Suppose you have been asked to an employee phone directory program and the
middle of a
names of the enmployee in the 1orm. In this scenario, how will you connect
an ItemData
names? In Visual Basic 6.0 and earlier, each item in alist box and combo box had

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

Fil combo bax Select one


object 0
object 1
Get seleded obyect 2
object 3
object 4
object 5
cbject 6
Sort teS cbject 7
object E

Figure 5.71: Storing Objects in a Combo Box

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

Fl combo bax Select one


object
object
Get seleted object
object 3
object 4
object
object
Sort terns object
object 8

Somg,objecds

Box
Figure 5.72: Storing Objects in a Combo

Handling the TextChanged and SelectedlndexChanged Events meanthat


there aretwoet
combinations
and these
Combo boxes are combinations of text boxes and list boxes,
of input events:
TextChanged event-Occurs when auser types into a text box combo box
box t
part of the
SelectedIndexChanged event-Occurs when a user uses the list
NoTE
combo box.
Unlike standard list boxes. you cannot make multiple selections in a list box ofa
ocaUS
that
onedisplared
The TextChanged Event occurs
similar to the is
same
Whenever a user changes the text in a combo box, a TextChanged event a
combo box, the
text in
when the user types in astandard text box. When the user enters following codesnippet
in the
simultaneously inna text box at the TextChanged event, as shownSystem.Object, Byval e As
Private sub Conbo Box
1_TextChanged (ByVal sender As
SVstem. EventArgs) Handles ComboBox1.TextChanged textbor
the
TextBOx1.Text = ComboBOX1. Text in
item
End Sub
type a neW
Press the F5 key to execute the application, Click the Fill combo box button and
of the combo box. The output is shown in Figure 5.73:

212
Windows Forms Controls-I

Cornbo Boa Sample

Aanbo bau Kogert


en
n
Geded em

em

Sot lens

Satng obyets

Kogert

Figure 5.73: Displaying the TextChanged Event of the Combo Box


Figure 5.73 shows that whatever is typed in the combo box is also displayed in the text box simultaneously.
The SelectedIndexChanged Event
When the selection changes in a combo box, a SelectionChanged event occurs, and youcan use the SelectedIndex
and Selectedltem properties to get the index of the newly selected item and the itemitself. Listing 5.16 shows the
the ComboBoxSample application that is used to report a new selection when a user selects an
code snippet frombox:
item in a combo
Listing 5.16: Handling the SelectedIndexChanged Event of the Combo Box
private sub ComboBOx1_ SelectedIndexchanged (Byval sender As System. object, Byval e As
SVstem.EventArgs) Handles ComboBox1. SelectedIndexchanged
If ComboBoxl.SelectedIndex > -1 Then
TE (ComboBox1. Sel ectedItem.GetType IsGetType(DataItem)) Then
TextBoxl.Text = "The data for the item you selected is: "&
CTVpe (ComboBox1.SelectedItem, DataItem) .GetData()
EndIf
EndIf

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

Sot enas biect


obect

Stong cbyea

The dota fo the iem yoy eiecdedis 5

Figure 5.74: Handling the SelectedindexChanged Event ofa Combo Box

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,

imprploperemertiens,t andmethuseods,theseand formeventconts rofolsthese


in variWiousndows
applicForms
ations. controls, In addition, you have learned how to
213
Chapter 5
atout some other Windows
In the next chapter, vou leamcontrol. Forms controls, such as
CheckBox Control, and ListView
Quick Revise
Explain the Control class.
RadioBulton conth
Q1.
Ans The Control class is the base class for all Windovs Forms
controls. It
such as handling user input through keyboard and mouse and defining
position implements
basic

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

You might also like