Upload
parmenas
View
226
Download
0
Embed Size (px)
Citation preview
8/9/2019 Visual basic tutorial 6
1/25
8/9/2019 Visual basic tutorial 6
2/25
• Che"$edListBo# * has a list of chec)boxes inside a ListBox.
• Com%oBo# * has a &rop&o'nStyle property that affects how the control wor)s.
o &rop&o'nStyle &rop&o'n * includes a TextBox and ListBox together,
you can type new items into the TextBox portion of the control, and the controldoes not consume %ery much space on the form. The list drops down whenyou clic) the drop-down arrow.
o &rop&o'nStyle Simple * you can type text into the TextBox at the top of
the ComboBox control * the list displays in a ListBox format and the you canscroll up and down the listing.
o &rop&o'nStyle &rop&o'nList * a ComboBox with no textbox into which
to type new items. As you type a letter, the control automatically searches forthe first item in the listing that begins with that letter. The listing drops downwhen you clic) the drop-down arrow.
ListBox, Chec)edListBox, and ComboBox controls+
• Automatically ha%e a verti"al s"roll %ar added by 'B when the list is too large to
display all items on the form.
• /a%e a Sorted property that will automatically sort the list when set to (rue.
ListBox controls display the )ame property at design time * you cannot delete it, but thename does not appear at run time. Also, if items are added to the control the nameproperty disappears at design time.
ComboBox controls display the (e#t property. At run time they display the appropriate%alues so don0t worry about what they display at design time.
(he Items Colle"tion
The list of items that display one of these controls is called a "olle"tion.
•
The collection is accessed through the Items property.• The $tems collection has properties and methods to ma)e it easy to add items,
remo%e items, and refer to indi%idual items.
• The items in the list are num%ered beginning with the number 0. A list of *0 items
has the items numbered 0 through +.
Filling the List
$f the list of items %aries, the best way to fill a list is to read the list into the control0s $temscollection from a database table * you will learn to do this in a later chapter in your studies.
$f the list of items ne%er changes or does not change much, you can add items at designtype by clic)ing on the Items property shown in this figure * a String Colle"tion ,ditor window will open and you type the items into the editor window.
1tart 'B and open the Ch07VBUniversity pro&ect that you copied earlier. 1et the StartupForm in Myro!e"t to ,mployee and open the form.
8/9/2019 Visual basic tutorial 6
3/25
#ote that the form is missing two Com%oBo# and one ListBo# control * add the controlswith control names as indicated.
2roperty settings for the controls+
• (itleCom%oBo#+
o &rop&o'nStyle * &rop&o'nList
o Items Colle"tion list items+
2rofessor
Associate 2rofessor Assistant 2rofessor
Lecturer
o Sorted property * (rue
• &epartmentCom%oBo#+
o ropown1tyle - &rop&o'n
o $tems Collection list items+
Accounting
3conomics 4 "inance
C5$1
5anagement 4 5ar)etingo Sorted property * (rue
• ,mployeeListBo#+
o Sorted property * (rue
The form has a menu strip control with the following menu entries.
"ile Count3xit
3mployee Add 3mployee 6eset 3mployee
---------------------------------- Clear 3mployee List isplay 1elected 3mployee
epartment Add epartment Count epartments
6emo%e epartment 6emo%e At epartment
/elp About
Chec) and set the form0s (a% -rder .
6un the pro&ect * test that the ComboBox controls ha%e appropriate lists as specified by youat design time.
Coding ListBox and ComboBox Controls
Items./dd Method
The Items./dd method is used to add an item to a list or ComboBox at run time.
8/9/2019 Visual basic tutorial 6
4/25
3xample commands to add a new faculty listing to the ,mployeeListBo# and newdepartments to the &epartmentCom%oBo# controls are shown below+
Dim NewEmployeeNameString As String = "Mary Sumner"Dim NewDepartmentNameString As String = "Chemistry"
'This adds a literal value.Employeeist!o.#tems.Add$"Mary Sumner"%
'This adds a value &rom a Tet!o ontrol.Employeeist!o.#tems.Add$EmployeeNameTet!o.Tet%
'This adds a value &rom a string memory varia(le.Employeeist!o.#tems.Add$NewEmployeeNameString %
'The #tems.Add method wor)s &or Com(o!oes in the same&ashion.'This adds a new department name using a literal value.DepartmentCom(o!o.#tems.Add$"Chemistry"%
'This adds a value &rom the tet property o& the Com(o!oontrol.DepartmentCom(o!o.#tems.Add$DepartmentCom(o!o.Tet%
'This adds a value &rom a string memory varia(le.DepartmentCom(o!o.#tems.Add$NewDepartmentNameString%
(as$ *: Code the Clic) e%ent sub procedure for the /dd &epartment menu item.
• Add the %alue typed into the &epartmentCom%oBo# control0s (e#t property to the
Items collection of the ComboBox control.
• Chec) to ensure that the (e#t property is not the empty string.
*rivate Su( AddDepartmentToolStripMenu#tem+Cli)$!y,al sender AsSystem.-(et/ !y,al e As System.EventArgs% 0andles AddDepartmentToolStripMenu#tem.Cli) 'Add department tet property to Com(o!o listing
'i& not the empty string #& DepartmentCom(o!o.Tet 12 String.Empty Then '-) to add DepartmentCom(o!o.#tems.Add$DepartmentCom(o!o.Tet% Else 'Cannot add Message!o.Show$"3ou must type a new department name."/"Name Missing Error"/ Message!o!uttons.-4/ Message!o#on.Error% DepartmentCom(o!o.5ous$% End #& End Su(
$n the abo%e, if the (e#t property is not the empty string, the (e#t property %alue isadded to the $tems collection. The code does not handle the insertion of duplicatedepartment name items * you will learn to write code to pre%ent this error later in thischapter.
(as$ 1: Code the Clic) e%ent sub procedure for the /dd ,mployee menu item.
•
Create a string %ariable named )e',mployeeString.• 1tore to the string %ariable the concatenated %alue of the
,mployee)ame(e#tBo#.(e#t 4 (itleCom%oBo#.(e#t 4&epartmentCom%oBo#.(e#t 4 Salary(e#tBo#.(e#t * separate each entry with acomma and blan) space.
• Add the string %alue to the ,mployeeListBo# control.
8/9/2019 Visual basic tutorial 6
5/25
• Clear the rest of the form and set the focus to the ,mployee)ame(e#tBo# in order
to prepare for entering the next employee7s information
*rivate Su( AddEmployeeToolStripMenu#tem+Cli)$!y,al sender As System.-(et/ !y,al e As System.EventArgs% 0andles AddEmployeeToolStripMenu#tem.Cli) '!uild the string to add Dim NewEmployeeString As String = EmployeeNameTet!o.Tet 6
"/ " 6 TitleCom(o!o.Tet 6 "/ " 6 DepartmentCom(o!o.Tet 6 "/ " 6SalaryTet!o.Tet
'Add string to ist!o Employeeist!o.#tems.Add$NewEmployeeString%
'Clear the &orm 7 ready to add another employee EmployeeNameTet!o.Clear$% TitleCom(o!o.Seleted#nde = 78 DepartmentCom(o!o.Seleted#nde = 78 SalaryTet!o.Clear$%
'Set &ous EmployeeNameTet!o.5ous$% End Su(
Items.Insert Method
$f you do not sort a list, you can use the Items.Insert method to specify exactly where withinan $tems collection to add a new item. 8ou do this by specifying the number position in thecollection * this is also called the index position of the new item.
This will add the item Chemistry as the %ery first item in the department ComboBox controlhowe%er, if the Sorted property is (rue, then specifying the location will not ha%e any effect.
DepartmentCom(o!o.#tems.#nsert$9/ "Chemistry"%
$f the ListBo# or Com%oBo# control is sorted, then the Insert method appears to wor)exactly as the /dd method * the new item is added at the location specified, but then controlthen immediately resorts the listing.
Items.Clear Method
The Items.Clear method will remo%e the contents of a list or ComboBox.
DepartmentCom(o!o.#tems.Clear$%
(as$: Code the Clic) e%ent sub procedure for the Clear ,mployee List menu item.
• eclare a dialog result %ariable and display a message box that as)s the system user
if they want to 9Clear employee listing29 * capture their response to the %ariable.
• The message box will display 3es and )o buttons * ma)e )o the default button with
the MessageBo#&e4aultButton.Button1 parameter.
• $f the response is 3es, then clear the ListBox control.
*rivate Su( ClearToolStripMenu#tem+Cli)$!y,al sender As System.-(et/ !y,al e As System.EventArgs% 0andles ClearToolStripMenu#tem.Cli) ':se response varia(le to apture user response
8/9/2019 Visual basic tutorial 6
6/25
Dim ;esponseDialog;esult As Dialog;esult = Message!o.Show$"Clear employee listing 3
8/9/2019 Visual basic tutorial 6
7/25
':nselet title and department Com(o!o ontrols and 'set Tet property to empty string TitleCom(o!o.Seleted#nde = 78 DepartmentCom(o!o.Seleted#nde = 78 TitleCom(o!o.Tet = String.Empty DepartmentCom(o!o.Tet = String.Empty
':nselet the urrently seleted &aulty mem(er in the
ist(o Employeeist!o.Seleted#nde = 78
';eset &ous to the employee name Tet!oEmployeeNameTet!o.5ous$%
End Su(
In5Class ,#er"ise
(as$ *: Code the Clic) e%ent sub procedure for the &isplay Sele"ted Fa"ulty menu item.
• se a message box to display the current selected item from the ,mployeeListBo#
control.
*rivate Su( DisplaySeletedToolStripMenu#tem+Cli)$!y,al sender
As System.-(et/ !y,al e As System.EventArgs% 0andles DisplaySeletedToolStripMenu#tem.Cli) ':se message(o to display seleted employee #& Employeeist!o.Seleted#nde = 78 Then Message!o.Show$"3ou must selet an employee mem(er todisplay."/ "No Seletion Error"/ Message!o!uttons.-4/ Message!o#on.Error% Else Message!o.Show$Employeeist!o.Seleted#tem.ToString/"Current seletion"/ Message!o!uttons.-4/ Message!o#on.#n&ormation% End #&
End Su(
(as$ 1: Code the Clic) e%ent sub procedure for the eset ,mployee menu item as shownearlier.
Items.Count roperty
The Items.Count property stores a number e;ual to the number of items in a list orComboBox $tems collection.
• The %alue of Items.Count is always < more than the maximum allowable
Sele"tedInde# %alue.• $f there are = items in a list, then Sele"tedInde# possible %alues are > through ?, but
Items.Count e;uals =.
se this property to display the number of items in a list.
8/9/2019 Visual basic tutorial 6
8/25
*rivate Su( CountDepartmentsToolStripMenu#tem+Cli)$!y,al sender As System.-(et/ !y,al e As System.EventArgs% 0andles CountDepartmentsToolStripMenu#tem.Cli) 'Display a message (o with the ount o& the num(er o&departments Dim MessageString As String = "Num(er o& departments " 6DepartmentCom(o!o.#tems.Count.ToString$% Dim TitleString As String = "Count o& Departments"
Message!o.Show$MessageString/ TitleString/ Message!o!uttons.-4/ Message!o#on.#n&ormation% End Su(
Items.emove/t and Items.emove Methods
To remo%e an indi%idual item from a list, specify either the index or text of the item.
• Items.emove/t method * remo%es an item by specifying the index position.
• Items.emove method * remo%es an item by specifying the item name.
The emove/t method fails if an item has not been selected for remo%al because the %alueof Sele"tedInde# 5* and you cannot remo%e a non-existent item * this throws anexception+ /rgument-ut-4ange,#"eption.
:hen the emove method is used and an item has not been selected for remo%al, themethod simply does nothing.
';emoves the &irst item &rom the listDepartmentCom(o!o.#tems.;emoveAt$9%
';emoves the item aording to the value o& #nde#ntegerDepartmentCom(o!o.#tems.;emoveAt$#nde#nteger%
';emove the urrently seleted item DepartmentCom(o!o.#tems.;emoveAt$DepartmentCom(o!o.Seleted#nde%
';emove item (y name where the item name is stored 'to the Seleted#tem property o& the Com(o!oDepartmentCom(o!o.#tems.;emove$DepartmentCom(o!o.Seleted#te m%
In5Class ,#er"ise(as$ *: Code the Clic) e%ent sub procedure for the &epartment menu, Count&epartments menu item.
• isplay the current number of departments to a message box.
*rivate Su( CountDepartmentsToolStripMenu#tem+Cli)$!y,al sender As System.-(et/ !y,al e As System.EventArgs% 0andles CountDepartmentsToolStripMenu#tem.Cli)
8/9/2019 Visual basic tutorial 6
9/25
'Display a message (o with the ount o& the num(er o&departments Dim MessageString As String = "Num(er o& departments " 6DepartmentCom(o!o.#tems.Count.ToString$% Dim TitleString As String = "Count o& Departments" Message!o.Show$MessageString/ TitleString/ Message!o!uttons.-4/ Message!o#on.#n&ormation% End Su(
(as$ 1: Code the Clic) e%ent sub procedure for the &epartment menu, emove&epartment menu item.
• se the $tems collection emove method.
• se a message box to as) the system user to confirm to remo%e the selected
department as shown here.
*rivate Su( ;emoveDepartmentToolStripMenu#tem+Cli)$!y,al sender As System.-(et/ !y,al e As System.EventArgs% 0andles ;emoveDepartmentToolStripMenu#tem.Cli) 'Delare dialog result varia(le Dim ;esponseDialog;esult As Dialog;esult = Message!o.Show$";emove the seleted department"/ ";emove "/MessageBoxButtons.YesNo, MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2)
If ResponseDialogResult = Windows.o!"s.DialogResult.Yes#$en
%Re"o&e t$e selected depa!t"ent &rom the listing DepartmentCom(o!o.#tems.;emove$DepartmentCom(o!o.Seleted#tem% 'This net line o& ode lears the Tet 'property o& the Com(o!o this is automati '&or the ;emove method/ (ut not &or the last 'item in a list. DepartmentCom(o!o.Tet = String.Empty End #& End Su(
(as$ 8: Code for the Clic) e%ent sub procedure for the &epartment menu, emove /t&epartment menu item.
• se the $tems collection emove/t method.
• se a message box to as) the system user to confirm to remo%e the selected
department.
• se a Try-Catch bloc) to trap the possible /rgument-ut-4ange,#"eption that
will be thrown if an item is not selected. isplay a message box li)e the one shownin this figure.
8/9/2019 Visual basic tutorial 6
10/25
*rivate Su( ;emoveAtDepartmentToolStripMenu#tem+Cli)$!y,al sender As System.-(et/ !y,al e As System.EventArgs% 0andles ;emoveAtDepartmentToolStripMenu#tem.Cli) 'Try to remove the department i& one is seleted Try 'Delare dialog result varia(le Dim ;esponseDialog;esult As Dialog;esult = Message!o.Show$";emove the seleted department"/ ";emove "/ Message!o!uttons.3esNo/ Message!o#on.>uestion/ Message!oDe&ault!utton.!utton?% #& ;esponseDialog;esult = @indows.5orms.Dialog;esult.3es
Then ';emove the seleted department &rom the listing DepartmentCom(o!o.#tems.;emoveAt$DepartmentCom(o!o.Seleted#nde% 'This net line o& ode lears the Tet 'property o& the Com(o!o this is automati '&or the ;emove method/ (ut not &or the last 'item in a list. DepartmentCom(o!o.Tet = String.Empty End #& Cath e As Argument-ut-&;angeEeption Message!o.Show$"3ou must selet a department to
remove."/ "No Seletion @as Made"/ Message!o!uttons.-4/ Message!o#on.Error% End Try End Su(
ListBo# and Com%oBo# ,vents
Code can be written for se%eral e%ents of ListBoxes and ComboBoxes. These include+
• Sele"tedInde#Changed ,vent. @ccurs when a system user ma)es a new selection
for a list or ComboBox.
• (e#tChanged ,vent. As a system user types characters into the TextBox portion of
a ComboBox, this e%ent is triggered for each character typed. ListBoxes do not ha%ethis e%ent.
• ,nter ,vent. :hen a list or ComboBox recei%es focus, this e%ent occurs.
• Leave ,vent. :hen a list or ComboBox loses focus, this e%ent occurs.
In5Class ,#er"ise
(as$: Code the Leave e%ent.
• $n the ob&ect drop-down ComboBox, select &epartmentCom%oBo# as shown in the
figure below.
• #ext select the Leave e%ent from the eclarations (property, method and e%ent!
drop-down ComboBox.
8/9/2019 Visual basic tutorial 6
11/25
• Code the Leave e%ent to add the %alue that is typed into the (e#t property of
&epartmentCom%oBo# to the $tems collection of &epartmentCom%oBo# .
*rivate Su( DepartmentCom(o!o+eave$!y,al sender As -(et/ !y,al e As System.EventArgs% 0andles DepartmentCom(o!o.eave 'Store Com(o!o Tet property value to #tems olletion DepartmentCom(o!o.#tems.Add$DepartmentCom(o!o.Tet%End Su(
• #ote that this code enables adding dupli"ate values as well as blan) %alues. Later
you will learn how to pre%ent this from happening.
• Test the code.
• After testing, delete the Lea%e e%ent code.
Loops
Loop structures enable you to execute a series of 'B statements o%er and o%er. Aniteration is a single execution of the loop.
There are two types of loops+
• Condition5"ontrolled. $n 'B, these are &o Loops * loops that execute o%er and
o%er until a specific condition occurs. $n 'B.#3T, these are &o Loops.
• Count5"ontrolled. $n 'B, these are For9)e#t Loops * loops that execute for a
specified number of times.
(he Boolean &ata (ype
A Boolean %ariable has a %alue of either (rue or False.
• se a Boolean %ariable to control the stopping condition for a loop.
• The de4ault value for a declared Boolean %ariable is False. 1ome programmers
explicitly set the %ariable to False when it is declared to ma)e it clear that the starting%alue for a loop search is initially false.
• An example of declaring a Boolean is+
Dim 5ound!oolean As !oolean = 5alse
Do Loops
&o Loops can execute the coding statements within the body of the loop either+
• until a condition is met that causes the loop to terminate (stop executing!,
• while a condition is met that causes a loop to continue executing.
8/9/2019 Visual basic tutorial 6
12/25
&o Loops can ha%e the "ondition test (termed the stopping "ondition! at either the top or bottom of a loop, and can use either a hile or Until option to test the condition.
Condition at (op o4 Loop ; hile Logi". The following loop executes while the stoppingcondition FoundBoolean is False.
Dim 5ound!oolean As !oolean = 5alseDo @hile 5ound!oolean = 5alse
'Coding statements to eeute. 'Code to searh &or some value #& ,alue#s5ound = True Then 5ound!oolean = True Else #nde#nteger = 8 End #&oop'Control trans&ers here a&ter the loop &inishes.
Condition at (op o4 Loop ; Until Logi". This loop wor)s li)e the one abo%e, but usesUntil logic. The loop executes until the stopping condition FoundBoolean is (rue. These
are the mirror image of each other. se the approach that you li)e best.
Dim 5ound!oolean As !oolean = 5alseDo :ntil 5ound!oolean = True 'Coding statements to eeute. 'Code to searh &or some value #& ,alue#s5ound = True Then 5ound!oolean = True Else #nde#nteger = 8 End #&oop
'Control trans&ers here a&ter the loop &inishes.
Condition at Bottom o4 Loop ; hile Logi". This next loop will always execute the bodyof the loop at least one time because the stopping condition is not tested until the end of theloop.
Dim 5ound!oolean As !oolean = 5alseDo
'Coding statements to eeute. 'Code to searh &or some value
#& ,alue#s5ound = True Then 5ound!oolean = True Else #nde#nteger = 8 End #&oop @hile 5ound!oolean = 5alse'Control trans&ers here a&ter the loop &inishes.
8ou can also test for an Until condition at the bottom of a o Loop.
Sear"hing a ListBo# or Com%oBo#
As was noted earlier, one of the problems with adding new departments to the&epartmentCom%oBo# control is that you can end up with duplicate departments *uplicates can occur when adding items to any ComboBox.
1earch coding procedures re;uires the following concepts+
8/9/2019 Visual basic tutorial 6
13/25
• :hen adding items, /CC-U)(I)
8/9/2019 Visual basic tutorial 6
14/25
6un the pro&ect and test the system by adding a new department (2hilosophy!, a duplicatedepartment (Accounting!, and a blan) department %alue.
For…Next Loops
A For9)e#t loop is a "ount5"ontrolled loop * the code executes a set number of timesbased on a loop inde#.
• A loop inde# is a numeric %ariable (usually integer or single!.
• The loop index is initialied to a starting value. The starting %alue in the code below
is *.
• After each execution of the loop, the loop index is changed (made larger or smaller!
by the step %alue. The step %alue in the example below is 1. The 1tep %alue isoptional - if it is not specified, it is automatically assumed to be *.
• The loop terminates when the loop index e#"eeds the ending value. The ending
value below is =.
This example merely illustrates the mechanics of coding a count-controlled loop.
*rivate Su( CountToolStripMenu#tem+Cli)$!y,al sender As System.-(et/ !y,al e As System.EventArgs% 0andles CountToolStripMenu#tem.Cli) Dim #nde#nteger As #nteger 5or #nde#nteger = 8 To F Step ? '*rint some output so you an see the 'loop ounting as it loops around. Countist!o.#tems.Add$#nde#nteger.ToString% Net #nde#nteger 'Control trans&ers to here when the loop ends
Message!o.Show$"5inished Counting"%
End Su(
@ther example For9)e#t statements+
5or #nde#nteger = ? To 899 Step
5or #nde#nteger = Start,alue#nteger To End,alue#nteger Step #nrement#nteger
5or #nde#nteger = 9 To $DepartmentCom(o!o.#tems.Count 7 8%
5or #nterest;ateDeimal = 9.9FD To 9.?FD Step 9.9FD
5or !a)wards#nde#nteger = 89 To 9 Step 78
In5Class ,#er"ise
(as$ *. Counting For'ard
• Add a ListBox to the form named CountListBo#, and a menu item under the "ile
menu named Count.
• Add the code to the Count menu item0s Clic) e%ent shown in the abo%e example.
• Try different %alues for the ending %alue and step increment.
8/9/2019 Visual basic tutorial 6
15/25
(as$ 1. Counting Ba"$'ard
5odify the code for the "ile-Count menu to count bac)wards from to < by
8/9/2019 Visual basic tutorial 6
16/25
'Control trans&ers here when the outer loop ends
,#it Statement
The ,#it For statement is used to exit a For...)e#t loop before the ending %alue is reached.3xample+
5or #nde#nteger = 8 To 89 #& #nputTet!o.Tet = String.Empty Then '!lan) input Message!o.Show$"#nput is invalid"% Eit 5or End #& '-ther statements to proess i& the input is valid Net #nde#nteger
There are also ,#it &o and ,#it hile and ,#it I4 statements. "or the most part, using any,#it statement is unnecessary if your code is constructed properly.
Selecting Control Entries
Sele"ting a (e#tBo# ,ntry
This techni;ue enables you to highlight all data typed into a TextBox control whene%er theapplication user tabs to the control or selects the control with the computer mouse. TheTextBox ,nter e%ent combined with the Sele"t/ll method highlights text.
*rivate Su( EmployeeNameTet!o+Enter$!y,al sender As -(et/ !y,al e As System.EventArgs% 0andles EmployeeNameTet!o.Enter 'Selet eisting tet values EmployeeNameTet!o.SeletAll$%End Su(
Sele"ting a ListBo# or Com%oBo# ,ntry
8ou can highlight text in a list or ComboBox. :e0%e seen this already. 1imply store thenumeric index %alue of the desired item to the Sele"tedInde# property of the list orComboBox.
Employeeist!o.Seleted#nde = #nde#nteger
Coding a (e#tChanged ,vent
3xpand the sie of the form for your Ch> pro&ect * you will find that the form already has aTextBox named Fruit(e#tBo# and a ListBox named FruitListBo# as shown in this figure.
8/9/2019 Visual basic tutorial 6
17/25
This sub procedure shows code for the (e#tChanged e%ent for the Fruit(e#tBo# control *whene%er a character is typed into the TextBox, it triggers a search for a matching %alue inthe FruitListBo#.
*rivate Su( 5ruitTet!o+TetChanged$!y,al sender As System.-(et/ !y,al e As System.EventArgs% 0andles 5ruitTet!o.TetChanged
'#nitialiHe varia(les to ontrol the searh Dim #nde#nteger As #nteger = 9 Dim 5ound!oolean As !oolean = 5alse Dim ist#temString As String
'Start the searh Do @hile Not 5ound!oolean And #nde#nteger 15ruitist!o.#tems.Count 'Compare the value in the Tet!o to the ist!o #tems ist#temString =5ruitist!o.#tems$#nde#nteger%.ToString.To:pper #& ist#temString.Starts@ith$5ruitTet!o.Tet.To:pper%
Then '&ound a &ruit name that starts with the Tet typedthus &ar 5ruitist!o.Seleted#nde = #nde#nteger 5ound!oolean = True Else #nde#nteger = 8 End #& oop
#& 5ound!oolean = 5alse Then Message!o.Show$"That &ruit is not in the list."/ "Not
5ound"/ Message!o!uttons.-4/ Message!o#on.Elamation% End #& End Su(
In5Class ,#er"ise
(as$ *: 1electing a TextBox 3ntry
• Add a TextBox control named Fruit(e#tBo# and a ListBox control named
FruitListBo# to the form.
• 1et the ListBox Sorted property to (rue.
•
Add some fruit items to the $tems collection for the fruit ListBox.• se the Sele"t/ll method as shown earlier to test your ability to highlight text in the
fruit ListBox control.
• Type a %alue in the TextBox, then tab around the form until the TextBox is again
selected * it should highlight the text in the control.
8/9/2019 Visual basic tutorial 6
18/25
*rivate Su( 5ruitTet!o+Enter$!y,al sender As -(et/ !y,al e As System.EventArgs% 0andles 5ruitTet!o.Enter 'Selet eisting tet values 5ruitTet!o.SeletAll$%End Su(
(as$ 1: 1electing a List or ComboBox 3ntry
• se the code shown abo%e to search for a %alue in the FruitListBo# as you type the
name of a type of fruit into the Fruit(e#tBo#.• Test the code.
ValidData Function
:hen an application uses menu controls, you will find that menu items do not ha%e aCausesValidation property. An alternati%e approach to %alidating data is to code a functionthat returns a %alue of (rue if data is %alid or a %alue of False if data is not %alid.
Coding Valid&ata Fun"tionThe Valid&ata function shown here demonstrates how to enforce business rules about thedata. Typical rules include+
• A data %alue cannot be missing from a TextBox control.
• An item must be selected from a ComboBox control (with &rop&o'nStyle
&rop&o'nList!.
• An item must be selected or a data %alue entered for a ComboBox control (with
&rop&o'nStyle &rop&o'n!.
• A TextBox that must store numeric data contains numeric data.
• A %alue in a TextBox that is numeric is within a specific legal range of %alues, such as
greater than ero.
*rivate 5untion ,alidData$% As !oolean 'Assume data is not valid ,alidData = 5alse Dim MessageString/ TitleString As String
#& EmployeeNameTet!o.Tet.Trim = String.Empty Then '!usiness rule I8 7 Name annot (e missing MessageString = "Employee name is missing." TitleString = "Employee name error" Message!o.Show$MessageString/ TitleString/ Message!o!uttons.-4/ Message!o#on.Error%
EmployeeNameTet!o.5ous$% EmployeeNameTet!o.SeletAll$%
Else#& TitleCom(o!o.Seleted#nde = 78 Then '!usiness rule I? 7 Title must (e seleted '&rom the list provided in the Com(o!o MessageString = "Title was not seleted." TitleString = "Title error" Message!o.Show$MessageString/ TitleString/ Message!o!uttons.-4/ Message!o#on.Error% TitleCom(o!o.5ous$%
Else#& DepartmentCom(o!o.Tet.Trim = String.Empty Then '!usiness rule IB 7 Department must (e seleted 'or typed into the Tet property o& the Com(o!o MessageString = "Department name was not seleted orentered." TitleString = "Department Name error"
8/9/2019 Visual basic tutorial 6
19/25
Message!o.Show$MessageString/ TitleString/ Message!o!uttons.-4/ Message!o#on.Error% DepartmentCom(o!o.5ous$%
Else#& #sNumeri$SalaryTet!o.Tet% = 5alse -rElse Deimal.*arse$SalaryTet!o.Tet/Jlo(aliHation.Num(erStyles.Curreny% 1= 9D Then '!usiness rule I 7 Salary must (e valid num(er 2 9
MessageString = "Salary is missing or invalid7must (egreater than Hero." TitleString = "Salary error" Message!o.Show$MessageString/ TitleString/ Message!o!uttons.-4/ Message!o#on.Error% SalaryTet!o.5ous$% SalaryTet!o.SeletAll$%
Else 'Data passes all (usiness rules ,alidData = True End #&
End 5untion
• The function is declared Boolean because it returns either a %alue of (rue or False.
• Begin by assuming that one or more business rule will be %iolated by storing a %alue
of "alse to the 'alidata function name.
• se an I45,lseI45,lse5,nd I4 structure to code a series of business rules. /ere the
rules are+o Business rule
8/9/2019 Visual basic tutorial 6
20/25
Dim NewEmployeeString As String =EmployeeNameTet!o.Tet 6 "/ " 6 TitleCom(o!o.Tet 6 "/ " 6DepartmentCom(o!o.Tet 6 "/ " 6 SalaryTet!o.Tet
'Add string to ist!o Employeeist!o.#tems.Add$NewEmployeeString%
'Clear the &orm 7 ready to add another employee
EmployeeNameTet!o.Clear$% TitleCom(o!o.Seleted#nde = 78 DepartmentCom(o!o.Seleted#nde = 78 SalaryTet!o.Clear$%
'Set &ous EmployeeNameTet!o.5ous$% End #& End Su(
In5Class ,#er"ise(as$ *: Add the Valid&ata function to your program.
Tas) D+ 5odify the Clic) e%ent for the /dd,mployee(oolStripMenuItem control to call theValid&ata function.
Test the application one business rule at a time.
Solution to n!Class Exercise
This solution shows the Ch07VBUniversity pro&ect code.
'*roet Ch9K,!:niversity $Solution%LCS?
-ption Strit -n
*u(li Class Employee
*rivate Su( AddDepartmentToolStripMenu#tem+Cli)$!y,al sender AsSystem.-(et/ !y,al e As System.EventArgs% 0andles
AddDepartmentToolStripMenu#tem.Cli) 'Add department tet property to om(o (o listing
Dim 5ound!oolean As !oolean = 5alse Dim #nde#nteger As #nteger = 9
Do :ntil 5ound!oolean = True -r #nde#nteger =DepartmentCom(o!o.#tems.Count #& DepartmentCom(o!o.Tet.Trim.To:pper =DepartmentCom(o!o.#tems$#nde#nteger%.ToString.Trim.To:pper Then 5ound!oolean = True Else 'Add 8 to inde value
#nde#nteger = 8 End #& oop 'oop (a) and try again
'Now deide whether to add item or not
8/9/2019 Visual basic tutorial 6
21/25
#& 5ound!oolean = 5alse And DepartmentCom(o!o.Tet.Trim 12String.Empty Then DepartmentCom(o!o.#tems.Add$DepartmentCom(o!o.Tet.Trim% Else Message!o.Show$"Dupliate or #nvalid Department Name"/"Dupliate Data Error"/ Message!o!uttons.-4/ Message!o#on.Elamation%
DepartmentCom(o!o.5ous$% DepartmentCom(o!o.SeletAll$% End #& End Su(
*rivate Su( AddEmployeeToolStripMenu#tem+Cli)$!y,al sender As System.-(et/ !y,al e As System.EventArgs% 0andles AddEmployeeToolStripMenu#tem.Cli) 'Add a new employee to the ist!o i& ,alid #& ,alidData Then '!uild the string to add Dim NewEmployeeString As String =
EmployeeNameTet!o.Tet 6 "/ " 6 TitleCom(o!o.Tet 6 "/ " 6DepartmentCom(o!o.Tet 6 "/ " 6 SalaryTet!o.Tet
'Add string to ist!o Employeeist!o.#tems.Add$NewEmployeeString%
'Clear the &orm 7 ready to add another employee EmployeeNameTet!o.Clear$% TitleCom(o!o.Seleted#nde = 78 DepartmentCom(o!o.Seleted#nde = 78 SalaryTet!o.Clear$%
'Set &ous EmployeeNameTet!o.5ous$% End #& End Su(
*rivate Su( ClearEmployeeistToolStripMenu#tem+Cli)$!y,al sender As System.-(et/ !y,al e As System.EventArgs% 0andles ClearEmployeeistToolStripMenu#tem.Cli) ':se response varia(le to apture user response
Dim ;esponseDialog;esult As Dialog;esult = Message!o.Show$"Clear employee listing 3
8/9/2019 Visual basic tutorial 6
22/25
DepartmentCom(o!o.Seleted#nde = 78 TitleCom(o!o.Tet = String.Empty DepartmentCom(o!o.Tet = String.Empty
':nselet the urrently seleted &aulty mem(er in theist(o Employeeist!o.Seleted#nde = 78
';eset &ous to the employee name tet (oEmployeeNameTet!o.5ous$% End Su(
*rivate Su( DisplaySeletedToolStripMenu#tem+Cli)$!y,al sender As System.-(et/ !y,al e As System.EventArgs% 0andles DisplaySeletedToolStripMenu#tem.Cli) ':se message(o to display seleted employee #& Employeeist!o.Seleted#nde = 78 Then Message!o.Show$"3ou must selet an employee mem(er todisplay."/ "No Seletion Error"/ Message!o!uttons.-4/ Message!o#on.Error%
Else Message!o.Show$Employeeist!o.Seleted#tem.ToString/"Current seletion"/ Message!o!uttons.-4/ Message!o#on.#n&ormation% End #& End Su(
*rivate Su( CountDepartmentsToolStripMenu#tem+Cli)$!y,al sender As System.-(et/ !y,al e As System.EventArgs% 0andles CountDepartmentsToolStripMenu#tem.Cli) 'Display a message (o with the ount o& the num(er o&departments
Dim MessageString As String = "Num(er o& departments " 6DepartmentCom(o!o.#tems.Count.ToString$% Dim TitleString As String = "Count o& Departments" Message!o.Show$MessageString/ TitleString/ Message!o!uttons.-4/ Message!o#on.#n&ormation% End Su(
*rivate Su( ;emoveDepartmentToolStripMenu#tem+Cli)$!y,al sender As System.-(et/ !y,al e As System.EventArgs% 0andles ;emoveDepartmentToolStripMenu#tem.Cli) 'Delare dialog result varia(le Dim ;esponseDialog;esult As Dialog;esult =
Message!o.Show$";emove the seleted department"/ ";emove "/ Message!o!uttons.3esNo/ Message!o#on.>uestion/ Message!oDe&ault!utton.!utton?% #& ;esponseDialog;esult = @indows.5orms.Dialog;esult.3esThen ';emove the seleted department &rom the listing DepartmentCom(o!o.#tems.;emove$DepartmentCom(o!o.Seleted#tem% 'This net line o& ode lears the Tet 'property o& the Com(o!o this is automati '&or the ;emove method/ (ut not &or the last 'item in a list.
DepartmentCom(o!o.Tet = String.Empty End #& End Su(
8/9/2019 Visual basic tutorial 6
23/25
*rivate Su( ;emoveAtDepartmentToolStripMenu#tem+Cli)$!y,al sender As System.-(et/ !y,al e As System.EventArgs% 0andles ;emoveAtDepartmentToolStripMenu#tem.Cli) 'Try to remove the department i& one is seleted Try 'Delare dialog result varia(le Dim ;esponseDialog;esult As Dialog;esult = Message!o.Show$";emove the seleted department"/ ";emove "/
Message!o!uttons.3esNo/ Message!o#on.>uestion/ Message!oDe&ault!utton.!utton?% #& ;esponseDialog;esult = @indows.5orms.Dialog;esult.3esThen ';emove the seleted department &rom the listing DepartmentCom(o!o.#tems.;emoveAt$DepartmentCom(o!o.Seleted#nde% 'This net line o& ode lears the Tet 'property o& the Com(o!o this is automati '&or the ;emove method/ (ut not &or the last 'item in a list. DepartmentCom(o!o.Tet = String.Empty
End #& Cath e As Argument-ut-&;angeEeption Message!o.Show$"3ou must selet a department toremove."/ "No Seletion @as Made"/ Message!o!uttons.-4/ Message!o#on.Error% End Try End Su(
*rivate Su( CountToolStripMenu#tem+Cli)$!y,al sender As System.-(et/ !y,al e As System.EventArgs% 0andles CountToolStripMenu#tem.Cli) 'Demonstrates using nested 5or...Net loops.
Dim Totalong As ong Dim -uter#nde#nteger As #nteger Dim #nner#nde#nteger As #nteger
'Start o& the outer loop 5or -uter#nde#nteger = 8 To B 'Start o& the inner loop eah time we get here the
'inner loop starts all over again 5or #nner#nde#nteger = 8 To G Totalong = 8 Countist!o.#tems.Add$Totalong.ToString% Net #nner#nde#nteger
'Eited inner loop ontrol trans&ers to outer loop Net -uter#nde#nteger Message!o.Show$"5inished Counting."% End Su(
*rivate Su( 5ruitTet!o+TetChanged$!y,al sender As System.-(et/ !y,al e As System.EventArgs% 0andles 5ruitTet!o.TetChanged '#nitialiHe varia(les to ontrol the searh Dim #nde#nteger As #nteger = 9 Dim 5ound!oolean As !oolean = 5alse Dim ist#temString As String
'Start the searh Do @hile Not 5ound!oolean And #nde#nteger 15ruitist!o.#tems.Count 'Compare the value in the Tet!o to the ist!o #tems
8/9/2019 Visual basic tutorial 6
24/25
ist#temString =5ruitist!o.#tems$#nde#nteger%.ToString.To:pper #& ist#temString.Starts@ith$5ruitTet!o.Tet.To:pper%Then '&ound a &ruit name that starts with the Tet typedthus &ar 5ruitist!o.Seleted#nde = #nde#nteger 5ound!oolean = True
Else #nde#nteger = 8 End #& oop
#& 5ound!oolean = 5alse Then Message!o.Show$"That &ruit is not in the list."/ "Not5ound"/ Message!o!uttons.-4/ Message!o#on.Elamation% End #& End Su(
*rivate Su( 0elpToolStripMenu#tem+Cli)$!y,al sender As
System.-(et/ !y,al e As System.EventArgs% 0andles 0elpToolStripMenu#tem.Cli) Message!o.Show$"*rogrammed (y D. !o)"/ "A(out Me"/ Message!o!uttons.-4/ Message!o#on.#n&ormation% End Su(
*rivate Su( A(outToolStripMenu#tem+Cli)$!y,al sender As System.-(et/ !y,al e As System.EventArgs% 0andles A(outToolStripMenu#tem.Cli) 'Display a(out message Dim MessageString As String = "*rogrammed (y D. !o)" 6ControlChars.Newine 6 "Today's date and time " 6 Date.Now
Dim TitleString As String = "A(out Ch9K ,! :niversity" Message!o.Show$MessageString/ TitleString/ Message!o!uttons.-4/ Message!o#on.#n&ormation% End Su(
*rivate 5untion ,alidData$% As !oolean 'Assume data is not valid ,alidData = 5alse Dim MessageString/ TitleString As String
#& EmployeeNameTet!o.Tet.Trim = String.Empty Then '!usiness rule I8 7 Name annot (e missing
MessageString = "Employee name is missing." TitleString = "Employee name error" Message!o.Show$MessageString/ TitleString/ Message!o!uttons.-4/ Message!o#on.Error% EmployeeNameTet!o.5ous$% EmployeeNameTet!o.SeletAll$%
Else#& TitleCom(o!o.Seleted#nde = 78 Then '!usiness rule I? 7 Title must (e seleted '&rom the list provided in the Com(o!o MessageString = "Title was not seleted." TitleString = "Title error"
Message!o.Show$MessageString/ TitleString/ Message!o!uttons.-4/ Message!o#on.Error% TitleCom(o!o.5ous$%
Else#& DepartmentCom(o!o.Tet.Trim = String.Empty Then '!usiness rule IB 7 Department must (e seleted
8/9/2019 Visual basic tutorial 6
25/25
'or typed into the Tet property o& the Com(o!o MessageString = "Department name was not seleted orentered." TitleString = "Department Name error" Message!o.Show$MessageString/ TitleString/ Message!o!uttons.-4/ Message!o#on.Error% DepartmentCom(o!o.5ous$%
Else#& #sNumeri$SalaryTet!o.Tet% = 5alse -rElse Deimal.*arse$SalaryTet!o.Tet/Jlo(aliHation.Num(erStyles.Curreny% 1= 9D Then '!usiness rule I 7 Salary must (e valid num(er 2 9 MessageString = "Salary is missing or invalid7must (egreater than Hero." TitleString = "Salary error" Message!o.Show$MessageString/ TitleString/ Message!o!uttons.-4/ Message!o#on.Error% SalaryTet!o.5ous$% SalaryTet!o.SeletAll$%
Else 'Data passes all (usiness rules ,alidData = True End #& End 5untion
End Class
,nd o4 )otes