22
1 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis Haywood Community College Kip Irvine Florida International University Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter Lists, Loops, Validation, and More 5 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 3 Introduction This chapter covers the Visual Basic looping statements Do … While Do … Until For … Next It also discusses the use of List Boxes Combo Boxes As well as presenting some properties and events used for user input validation Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Input Boxes 5.1 Input Boxes Provide a Simple Way to Gather Input Without Placing a Text Box on a Form

Chapter Visual Basic 2008 - University of Houston–Downtown

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Chapter Visual Basic 2008 - University of Houston–Downtown

1

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 1

STARTING OUT WITH 

Visual Basic 2008FOURTH EDITION

Tony GaddisHaywood Community College

Kip IrvineFlorida International University

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

ChapterLists, Loops,Validation, and More5

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 3

Introduction This chapter covers the Visual Basic looping

statements Do … While Do … Until For … Next

It also discusses the use of List Boxes Combo Boxes

As well as presenting some properties and events used for user input validation

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Input Boxes5.1Input Boxes Provide a Simple Way to Gather Input Without Placing a

Text Box on a Form

Page 2: Chapter Visual Basic 2008 - University of Houston–Downtown

2

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 5

Format of the InputBox Function

Prompt - message to the user (required) Title - text for the box's title bar Default - default text for user's input Xpos - X coordinate for the box's position Ypos - Y coordinate for the box's position Square brackets around Title and following

arguments indicate these are optional

InputBox(Prompt [,Title] [,Default] [,Xpos] [,Ypos])

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 6

Sample InputBox UsagestrUserInput = InputBox("Enter the distance.", _

"Provide a Value", "150")

If the users clicks OK without entering a value, 150 will be assigned to strUserInput due to the default value

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 7

Xpos & Ypos

Xpos specifies the distance from the left of the screen to the left side of the box

Ypos specified the distance from the top of the screen to the top of the box

Both are specified in pixels

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

List Boxes5.2

List Boxes Display a List of Items and Allow the User to Select an

Item From the List

Page 3: Chapter Visual Basic 2008 - University of Houston–Downtown

3

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

The ListBox Control

A ListBox control displays a list of items and allows the user to select one or more

Drag from Toolbox to create this control on a form

Slide 5- 9 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 10

ListBox Items Property

The Items property holds an entire list of values from which the user may choose

The list of values may be established at run time or as part of the form design

To set list values in the form design: Select the list box in the Design window View properties & click the Items ellipsis button This property is a collection, a list of values Type each value on a separate line

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 11

ListBox Items.Count Property

This property returns an integer with the number of entries stored in the Items property

Example of use:

The number of entries in the list can be assigned to an integer variable

If lstEmployees.Items.Count = 0 ThenMessageBox.Show("The list has no items!")

End If

numEmployees = lstEmployees.Items.Count

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 12

Item Indexing The Items property values can be accessed from

your VB code Each item value is given a sequential index

The first item has an index of 0 The second item has an index of 1, etc.

Example:

name = lstCustomers.Items(2)' Access the 3rd item value

Page 4: Chapter Visual Basic 2008 - University of Houston–Downtown

4

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 13

Index Out of Range Error The index of the last item is always

list.Items.Count-1

Reference to an index greater than Count-1 or less than zero throws an exception

An exception handler can trap this error The variable ex captures the exception thrown

TrystrInput = lstMonths.Items(n).ToString()

Catch ex as ExceptionMessageBox.show(ex.Message)

End Try

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 14

ListBox SelectIndex Property The SelectIndex property returns an integer with

the index of the item selected by the user If no item is selected, the value is set to -1 (an

invalid index value) Can use SelectIndex to determine if an item has

been selected by comparing to -1 Example:

If lstLocations.SelectedIndex <> -1 Thenlocation = lstLocations.Items(lstLocations.SelectedIndex)

End If

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 15

ListBox SelectedItem Property

Instead of using the SelectedIndex property as follows:

The SelectedItem property can be used to retrieve the value of a selected item as follows:

If lstMonths.SelectedIndex <> -1 Thenmonth = lstMonths.Items(lstMonths.SelectedIndex)

End If

If lstMonths.SelectedIndex <> -1 Thenmonth = lstMonths.SelectedItem.ToString)

End If

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 16

ListBox Sorted Property

Sorted is a boolean property When set to true, values in the Items property are

displayed in alphabetical order When set to false, values in the Items property

are displayed in the order they were added

Page 5: Chapter Visual Basic 2008 - University of Houston–Downtown

5

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 17

ListBox Items.Add Method

Items can be added to the end of a ListBox list in your VB code using the Add method

Format isListBox.Items.Add(Item)

ListBox is the name of the control Item is a string value to add to the Items property Example:

lstStudents.Items.Add("Sharon")

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 18

ListBox Items.Insert Method

Items can be added at a specific position of a ListBox in VB code using the Insert methodListBox.Items.Insert(Index, Item)

Index specifies position where Item is placed Index is zero based similar to SelectedIndex

property Items that follow are “pushed” down Example inserting "Jean“ as the 3rd item

lstStudents.Items.Insert(2, "Jean")

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 19

ListBox Methods to Remove Items

ListBox.Items.RemoveAt(Index)

Removes item at the specified index ListBox.Items.Remove(Item)

Removes item with value specified by Item ListBox.Items.Clear()

Removes all items in the Items property Examples:lstStudents.Items.RemoveAt(2) ‘remove 3rd itemlstStudents.Items.Remove(“Jean”) ‘remove item JeanlstStudents.Items.Clear() ‘remove all items

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 20

Other ListBox Methods

ListBox.Items.Contains(Item) Returns true if Item is found in the collection

ListBox.Items.IndexOf(Item) Returns an integer with the index position of

the first occurrence of Item in the collection Examples:

Tutorial 5-1 provides more examples of ListBox controls, methods and properties

blnFound = lstMonths.Items.Contains(“March”)intIndex = lstMonths.Items.IndexOf(“March”)

Page 6: Chapter Visual Basic 2008 - University of Houston–Downtown

6

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Tutorial 5.1

Slide 5- 21 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

The Do While Loop5.3

A Loop Is Part of a ProgramThat Repeats

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 23

Repetition Structure (or Loop)

Visual Basic has three structures that allow a statement or group of statements to repeat Do While Do Until For...Next

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 24

Do While Flowchart

The Do While loop If the expression is

true, the statement(s)are executed

Expression is thenevaluated again

As long as the expression remains true, the statement(s) continue to be repeated

Expression statement(s)

False

True

Page 7: Chapter Visual Basic 2008 - University of Houston–Downtown

7

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 25

Do While Syntax

Do, While, and Loop are new keywords The Do While statement marks the beginning of

the loop The Loop statement marks the end The statements to repeat are found between

these and called the body of the loopDo While expression

statement(s)Loop

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 26

Do While Example

Private Sub btnRunDemo_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles btnRunDemo.Click' Demonstrate the Do While loopDim intCount As Integer = 0

Do While intCount < 10lstOutput.Items.Add("Hello")intCount += 1

LoopEnd Sub

Note that programming styledictates the body of theloop be indented for clarity

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 27

Infinite Loops

A loop must have some way to end itself Something within the body of the loop must

eventually force the test expression to false In the previous example

The loop continues to repeat intCount increases by one for each repetition Finally intCount is not <10 and the loop ends

If the test expression can never be false, the loop will continue to repeat forever This is called an infinite loop

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 28

Counters

Variables called counters are frequently used to control Do While loops intCount in previous example is a counter

Counters generally initialized before loop beginsDim intCount As Integer = 0

Counter must be modified in body of loopintCount += 1

The test expression ends the loop when the counter compares to some value

Page 8: Chapter Visual Basic 2008 - University of Houston–Downtown

8

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 29

Pretest vs. Posttest Loops Previous Do While loops are in pretest form

Expression is tested before the body of the loop is executed

The body may not be executed at all Do While loops also have a posttest form

The body of the loop is executed first Then the expression is evaluated Body repeats as long as expression is true A posttest loop always executes the body of

the loop at least onceCopyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 30

Posttest Loop Syntax and Flowchart

The statement(s) mustbe executed at leastonce, irrespective of the expression used

Dostatement(s)

Loop While expression

Expression

statement(s)

False

True

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 31

A Posttest Running Total LoopintCount = 1 ' Initialize the counterdecTotal = 0 ' Initialize totalDo

strInput = InputBox("Enter the sales for day " & _intCount.ToString, "Sales Amount Needed")

If strInput <> "" ThendecSales = CDec(strInput) decTotal += decSales ' Add sales to totalintCount += 1 ' Increment the counter

End IfLoop While intCount <= 5

Tutorial 5-4 uses the code above in pretest form as part of a more complete example

Tutorial 5-5 demonstrates how to structure a loop such that the user can specify the iterations

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Tutorial 5.2 & 5.3

Slide 5- 32

Page 9: Chapter Visual Basic 2008 - University of Houston–Downtown

9

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Tutorial 5.4 & 5.5

Slide 5- 33 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

The Do Until andFor Next Loops5.4

A Do Until Loop Iterates Until Its Test Expression Is True

The For...Next Loop Is Designed to Use a Counter Variable and Iterates a Specific

Number of Times

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 35

Do Until vs. Do While A Do While loop

Repeats as long as its test expression is true Ends when its test expression becomes false

A Do Until loop Repeats as long as its test expression is false Ends when its test expression becomes true

The Do Until loop has a pretest and posttest form just as a Do While loop

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 36

Do Until: Pretest & Posttest Forms Pretest:

Posttest:

Tutorial 5-6 provides a hands-on example of a pretest Do Until loop

Do Until expressionstatement(s)

Loop

Dostatement(s)

Loop Until expression

Page 10: Chapter Visual Basic 2008 - University of Houston–Downtown

10

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 37

Do Until Loop – Test Score AveragestrInput = InputBox("How many test scores do you " _

& “want to average?", "Enter a Value")intNumScores = CInt(strInput)

‘ Store starting valuessngTotal = 0intCount = 1

‘ Get the test scoresDo Until intCount > intNumScores

strInput = InputBox("Enter the value for test score " _& intCount.ToString, "Test Score Needed")

sngTotal = sngTotal + CSng(strInput)intCount = intCount + 1

Loop‘ Calculate the average

If intNumScores > 0 thensngAverage = sngTotal / intNumScores

ElsesngAverage = 0.0

End IfCopyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Tutorial 5.6 & 5.7

Slide 5- 38

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 39

For…Next Loop

Ideal for loops that require a counter

For, To, and Next are keywords CounterVariable tracks number of iterations StartValue is initial value of counter EndValue is counter number of final iteration Optional Step allows the counter to increment at

a value other than 1 at each iteration of the loop

For CounterVariable = StartValue To EndValue [Step]statement

Next [CounterVariable]

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 40

For…Next Flowchart

Counter =EndValue? statement(s)

False

True

setcounter

to StartValue

incrementcounter

Page 11: Chapter Visual Basic 2008 - University of Houston–Downtown

11

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 41

The following code from Tutorial 5-7 uses a For…Next loop to place the squares of the numbers 1 through 10 in a ListBox

Tutorial 5-8 uses a For…Next loop to move a PictureBox control around a window

For…Next Example

For intCount = 1 To 10intSquare = CInt(intCount ^ 2)strTemp = "The square of " & intCount.ToString _

& “ is “ & intSquare.ToStringlstOutput.Items.Add(strTemp)

Next intCount

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 42

More on the StepValue

It’s optional and if not specified, defaults to 1 The following loop iterates 11 times with counter

values 0, 10, 20, …, 80, 90, 100

StepValue may be negative, causing the loop to count downward

For x = 0 To 100 Step 10MessageBox.Show("x is now " & x.ToString)

Next x

For x = 10 To 1 Step -1MessageBox.Show("x is now " & x.ToString)

Next x

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Tutorial 5.8

Slide 5- 43 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 44

Exiting a Loop Prematurely

In some cases it is convenient to end a loop before the test condition would end it

The following statements accomplish this Exit Do (used in Do While or Until loops) Exit For (used in For Next loops)

Use this capability with caution It bypasses normal loop termination Makes code more difficult to debug

Page 12: Chapter Visual Basic 2008 - University of Houston–Downtown

12

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 45

Example: Exit a Loop Prematurely

maxNumbers = CInt(InputBox("How many numbers do " & _"you wish to sum?"))

total = 0For x = 1 to maxNumbers

input = InputBox("Enter a number.")If input = "" Then

Exit ForElse

num = CDbl(input)total += num

End IfNext xMessageBox.Show(“Sum of the numbers is " & total.ToString)

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 46

When to Use the Do While Loop

Use Do While when the loop should repeat as long as the test expression is true

Can be written as a pretest or posttest loop A pretest Do While is ideal when the body should

not be perfomed for a test expression that is initially false

Posttest loops are ideal when you always want the loop to iterate at least once

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 47

When to Use the Do Until Loop

Use Do Until when the loop should repeat as long as the test expression is false

Can be written as a pretest or posttest loop A pretest Do Until is ideal when the body should

not be perfomed for a test expression that is initially true

Posttest loops are ideal when you always want the loop to iterate at least once

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 48

When to Use the For Next Loop

The For...Next loop is a pretest loop ideal when a counter is needed

It automatically increments the counter variable at the end of each iteration

The loop repeats as long as the counter variable is not greater than an end value

Used primarily when the number of required iterations is known

Page 13: Chapter Visual Basic 2008 - University of Houston–Downtown

13

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Nested Loops5.5

A Loop that is Inside Another Loop is Called a Nested Loop

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 50

Nested Loops

The body of a loop can contain any type of VB statements including another loop

When a loop is found within the body of another loop, it’s called a nested loop

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 51

Nested Loop Example

For hours = 0 To 24lblHours.Text = hours.ToStringFor minutes = 0 To 59

lblMinutes.Text = minutes.ToStringFor seconds = 0 To 59

lblSeconds.Text = seconds.ToStringNext seconds

Next minutesNext hours

A clock is an example of a nested loop Minute hand repeats 60 times for each hour Second hand repeats 60 times for each minute

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 52

Nested Loop Example Analysis The innermost loop will iterate 60 times for each

iteration of the middle loop The middle loop will iterate 60 times for each

iteration of the outermost loop 24 iterations of the outermost loop require:

1,440 iterations of the middle loop 86,400 iterations of the innermost loop

An inner loop goes through all its iterations for each iteration of the outer loop

Multiply iterations of all loops to get the total iterations of the innermost loop

Page 14: Chapter Visual Basic 2008 - University of Houston–Downtown

14

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Multicolumn List Boxes,Checked List Boxesand Combo Boxes

5.6A Multicolumn List Box Displays Items in ColumnsA Checked List Box Displays a Check Box Next to

Each Item in the ListA Combo Box Is Like a List Box Combined With a

Text Box

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 54

List Box Multicolumn Property

The ListBox has a Multicolumn property Boolean property with default value of false If set to true, entries can appear side by side

Below, ColumnWidth is set to 30 Note the appearance of a horizontal scroll bar in

this case

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 55

Checked List Box A form of ListBox with the list box properties and

methods already discussed One item at a time may be selected but many

items in a Checked List Box can be checked The CheckOnClick property determines how

items may be checked False - user clicks item once

to select it, again to check it True - user clicks item only once

to both select it and check it

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 56

Finding the Status of Checked Items

The GetItemChecked method returns true if the item at Index has been checkedCheckedListBox.GetItemChecked(Index)

Dim i as IntegerDim intCheckedCities as Integer = 0

For i = 0 to clbCities.Items.Count – 1If clbCities.GetItemChecked(i) = True Then

intCheckedCities += 1End If

Next i

MessageBox.Show(“You checked “ & _intCheckedCities.Tostring() & “ cities.”)

Page 15: Chapter Visual Basic 2008 - University of Houston–Downtown

15

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 57

Combo Boxes Similar to List Boxes

Both display a list of items to the user Both have Items, Items.Count, SelectedIndex,

SelectedItem, and Sorted properties Both have Items.Add, Items.Clear,

Items.Remove, and Items.RemoveAt methods These properties and methods work the same

with combo boxes and list boxes

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 58

Additional Combo Box Features

A combo box also functions like a text box The user may enter text into a combo box Or the user may select the text from a series of

list box type choices

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 59

Combo Box Styles

Simple Combo Box List is always shown

Drop-down Combo Box List appears when user

clicks down arrow User can type text or select

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 60

Combo Box Styles

Drop-down List Combo Box

Behaves like a Drop-DownCombo Box, but the usermay not enter text directly

Tutorial 5-9 demonstrates each style of combo box

Page 16: Chapter Visual Basic 2008 - University of Houston–Downtown

16

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 61

Choosing a Combo Box Style

If restricting the user to select items listed If empty space – use ListBox If limited space – use drop-down list

ComboBox If allowing user to select an item listed or enter an

entirely new item If empty space – use simple ComboBox If limited space – use drop-down ComboBox

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Tutorial 5.9

Slide 5- 62

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Input Validation5.7As Long As a User Enters Bad Input, the

Application Will Produce Bad OutputApplications Should Be Written to Filter Out

Bad Input

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 64

Examples of Input Validation Numbers are checked to ensure they are within a range

of possible values For example, there are 168 hours in a week A person can’t work more than 168 hours a week

Values are checked for their “reasonableness” A person might possibly work 168 hours in a week However, this is highly improbable

Items selected from a menu or a set of choices are checked to ensure these options are available

Variables are checked for values that might cause problems, such as division by zero

Page 17: Chapter Visual Basic 2008 - University of Houston–Downtown

17

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 65

CausesValidation/Validating Event

A control’s Validating event is triggered when focus is shifting from that control to a control whose CausesValidation property is true

The Validating event of the control losing the focus fires before focus is lost

This allows your code to validate an entry just before focus shifts If user shifts focus, input must be complete

Tutorial 5-10 demonstrates this capability

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 66

The Validated Event

A control’s Validated event is triggered After the Validating event After focus has been lost

Allows operations on input that should occur only after the user moves away from the field

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Tutorial 5.10

Slide 5- 67 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Select Text with SelectAll Method

SelectAll makes correcting invalid input easier If you know which TextBox is in error you can:

Use the Focus method to position the cursor Use the SelectAll method to select the text Then the user need not erase incorrect text Simply start typing to enter the corrected text

If txtName is in error:txtName.Focus()txtName.SelectAll()

Slide 5- 68

Page 18: Chapter Visual Basic 2008 - University of Houston–Downtown

18

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 69

Using the With…End Statement

A With statement establishes a default object in effect until an End With is encountered

Instead of repeating txtNum1 in this code

With allows you to reference the txtNum1 object without specifying it repeatedly

txtNum1.SelectionStart = 0txtNum1.SelectionLength = txtNum1.Text.Length

With txtNum1.SelectionStart = 0.SelectionLength = .Text.Length

End With

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Tool Tips5.8Tool Tips Are a Standard, Convenient Way of

Providing Help to Users of an ApplicationThe ToolTip Control Allows You to Assign

Pop-up Hints to the Other Controls on a Form

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 71

What is a Tool Tip?

A Tool Tip is the short text message you see when holding the mouse over a control

These are easy to set up and use in Visual Basic forms

The ToolTip control allows you to create ToolTips for other controls on a form

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 72

Setting Up ToolTips

Display the form design window Double-click the ToolTip tool in the Toolbox The ToolTip control is invisible at runtime so

It appears in the component tray, not the form Component tray shows at the bottom of the

design window ToolTips are now enabled for this form Form controls now have a ToolTip property This new property holds the text string that will be

displayed for that control

Page 19: Chapter Visual Basic 2008 - University of Houston–Downtown

19

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 73

Controlling the Tool Tips

Select the ToolTip control from the tray View Properties window to see the following

An InitialDelay property that regulates the delay before a tip appears

An AutoPopDelay that determines how long a tip is displayed

ReshowDelay determines the time between the display of different tips as the user moves the mouse from control to control

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Building the Vehicle Loan Calculator Application5.9

This application utilizes loops, input validation, and tool tips.

It also makes use of some Visual Basic intrinsic financial functions.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Case Study: Vehicle Loan CalculatorThe Bayou Credit Union finances new and used vehicles for its members. A credit union branch manager asks you to create an application names Vehicle Loan Calculator that displays the following information for a loan: The monthly payment amount The amount of the monthly payment applied toward

interest The amount of the monthly payment applied toward

principal The credit union currently charges 8.9% annual interest for new vehicles loans and 9.5% annual interest on used vehicle loans.

Slide 5- 75 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Vehicle Loan Calculator

Slide 5- 76

Page 20: Chapter Visual Basic 2008 - University of Houston–Downtown

20

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Health Club Fee Calculator Form

Slide 4- 77 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Algorithm Chart

Slide 4- 78

Vehicle Loan Calculator Application

Calculate Button Click Event: Validate inputs. Display error message if the input is not

valid. Calculate and display a table in the list box showing

interest and principal payment for the loan.

Exit Button Click Event: Close the application/window.

Clear Button Click Event: Clear all text boxes, Clear list box, Reset interest rate.

New RadioButton Checked Change Event: Update interest rate.

Used RadioButton Checked Change Event: Update interest rate.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Calculate Button Click Event:

Get inputs and validate Get cost of vehicle:

Cost = CostTextBox.Text Get down payment amount:

DownPayment = DownTextBox.Text Get number of months:

Months = MonthsTextBox.Text

Slide 4- 79 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Caculate Button Click Event:

Calculate or Compute Compute loan amount:

LoanAmount = Cost – DownPayment Compute monthly payment:

Monthly = Pmt(PeriodicInterestRate, NumberOfPeriods, LoanAmount)

Slide 4- 80

Page 21: Chapter Visual Basic 2008 - University of Houston–Downtown

21

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Calculate Button Click Event:

Compute interest paid, principal paid and display:

For Count = 0 to MonthsInterest = IPmt()Principal = PPmt() Display Month, Payment, Interest, and Principal in the list box

Next

Slide 4- 81 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

New RadioButton CheckedChangeEvent:

Reset annual interest rate to 8.9%: AnnualRate = NewRateRateLabel.text = NewRate.ToString("p")

Slide 4- 82

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Used RadioButton CheckedChangeEvent:

Reset annual interest rate to 9.5%: AnnualRate = UsedRateRateLabel.text = UsedRate.ToString("p")

Slide 4- 83 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Clear Button Click Event:

Clear all text boxes, TextBoxName.Clear()

Clear listbox, ListBoxName.Items.Clear()

Reset interest rate.LabelName.Text = ValueToDisplay

Slide 4- 84

Page 22: Chapter Visual Basic 2008 - University of Houston–Downtown

22

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Exit Button Click Event:

Close()

Slide 4- 85 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Calculate Button Flowchart

Slide 5- 86

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Radio Button CheckChanged Events

Slide 5- 87 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Cost Textbox Validating Event

Slide 5- 88