Presentation is loading. Please wait.

Presentation is loading. Please wait.

STARTING OUT WITH Visual Basic 2008

Similar presentations


Presentation on theme: "STARTING OUT WITH Visual Basic 2008"— Presentation transcript:

1 STARTING OUT WITH Visual Basic 2008
FOURTH EDITION Tony Gaddis Haywood Community College Kip Irvine Florida International University

2 Introduction to Programming and Visual Basic 2005
Chapter Introduction to Programming and Visual Basic 2005 1 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

3 Computer Systems: Hardware and Software
1.1 Computer Systems Consist of Similar Hardware Devices and Components Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

4 Computer Hardware Refers to the physical components
Not one device but a system of many devices Major types of components include: Central Processing Unit Main memory Secondary storage devices Input devices Output devices

5 Organization of a Computer System
Central Processing Unit Input Device Output Device Main Memory Secondary Storage

6 The CPU Fetches instructions from main memory
Carries out the operations commanded by the instructions Each instruction produces some outcome CPU gets instructions from a program A program is an entire sequence of instructions Instructions are stored as binary numbers Binary number - a sequence of 1’s and 0’s

7 Main Memory Commonly known as random access memory, or just RAM
Holds instructions and data needed for programs that are currently running RAM is usually a volatile type of memory Contents are lost when power is turned off Used as temporary storage

8 Secondary Storage A nonvolatile storage medium
Contents retained while power is off Hard disk drives are most common Records data magnetically on a circular disk Provides fast access to large amounts of data Optical devices store data on CD’s as pits USB flash memory devices High capacity device plugs into USB port Portable, reliable, and fits easily in a pocket

9 Input Devices Any type of device that provides data to a computer from the outside world For example: Keyboard Mouse Scanner

10 Output Devices Any type of device that provides data from a computer to the outside world Examples of output data: A printed report An image such as a picture A sound Common output devices include: Monitor (display screen) Printer

11 Software The programs that run on a computer Two major categories
Operating systems Controls the processes within the computer Manages the computer's hardware devices Application Software Solve problems or perform tasks needed by users Examples include word processing, spreadsheets, games, Internet browsers, playing music, etc) Each program is referred to as an application This book develops applications in Visual Basic

12 Programs and Programming Languages
1.2 A Program Is a Set of Instructions a Computer Follows in Order to Perform a Task A Programming Language Is a Special Language Used to Write Computer Programs Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

13 What Is a Program? Computers can only follow instructions
A computer program is a set of instructions on how to solve a problem or perform a task In order for a computer to compute someone’s gross pay, we must tell it to perform the steps on the following slide

14 Computing Gross Pay Display message: "How many hours did you work?"
Allow user to enter number of hours worked Store the number the user enters in memory Display message: "How much are you paid per hour?" Allow the user to enter an hourly pay rate Multiply hours worked by pay rate and store the result in memory Display a message with the result of the previous step This well-defined, ordered set of steps for solving a problem is called an algorithm

15 States and Transitions
Program Starting State hours worked hourly pay rate amount earned Memory snapshots show states of the program Store hours worked in memory Store hourly pay rate in memory Multiply hours worked by pay rate and store amount earned in memory ?? ?? ?? Snapshot after Step 3 hours worked hourly pay rate amount earned 20 ?? ?? Snapshot after Step 6 hours worked hourly pay rate amount earned 20 25 ?? Snapshot after Step 7 hours worked hourly pay rate amount earned 20 25 500

16 Programming Languages
The steps in our algorithm must be stated in a form the computer understands The CPU processes instructions as a series of 1’s and 0’s called machine language This is a tedious and difficult format for people Instead, programming languages allow us to use words instead of numbers Software converts the programming language statements to machine language

17 Common Programming Languages
Visual Basic Python Javascript Java C# C C++ PHP Visual Basic is not just a programming language It’s a programming environment with tools to: Create screen elements Write programming language statements

18 Methods of Programming
Procedural Constructed as a set of procedures (operational, functional units) Each procedure is a set of instructions The Gross Pay computation is a procedure Object-Oriented Uses real-world objects such as students, transcripts, and courses Objects have data elements called attributes Objects also perform actions

19 Example of an Object This is a Visual Basic GUI object called a form
Contains data and actions Data, such as Hourly Pay Rate, is a text property that determines the appearance of form objects Actions, such as Calculate Gross Pay, is a method that determines how the form reacts A form is an object that contains other objects such as buttons, text boxes, and labels

20 Example of an Object Form elements are objects called controls
This form has: Two TextBox controls Four Label controls Two Button controls The value displayed by a control is held in the text property of the control Left button text property is Calculate Gross Pay Buttons have methods attached to click events

21 Event Driven Programming: Events
The GUI environment is event-driven An event is an action that takes place within a program Clicking a button (a Click event) Keying in a TextBox (a TextChanged event) Visual Basic controls are capable of detecting many, many events A program can respond to an event if the programmer writes an event procedure

22 More About Controls and Programming
1.3 More About Controls and Programming As a Visual Basic Programmer, You Must Design and Create the Two Major Components of an Application: the GUI Elements (Forms and Other Controls) and the Programming Statements That Respond to And/or Perform Actions (Event Procedures) Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

23 Visual Basic Controls As a Windows user you’re already familiar with many Visual Basic controls: Label - displays text the user cannot change TextBox - allows the user to enter text Button – performs an action when clicked RadioButton - A round button that is selected or deselected with a mouse click CheckBox – A box that is checked or unchecked with a mouse click Form - A window that contains these controls Tutorial 1-3 demonstrates these controls

24 Tutorial 1-3, Visual Basic Controls

25 Name Property All controls have properties
Each property has a value (or values) Not all properties deal with appearance The name property establishes a means for the program to refer to that control Controls are assigned relatively meaningless names when created Programmers usually change these names to something more meaningful

26 Examples of Names The label controls use the default names (Label1, etc.) Text boxes, buttons, and the Gross Pay label play an active role in the program and have been changed Label1 txtHoursWorked Label2 txtPayRate Label3 lblGrossPay btnCalcGrossPay btnClose

27 Naming Conventions Control names must start with a letter
Remaining characters may be letters, digits, or underscore 1st 3 lowercase letters indicate the type of control txt… for Text Boxes lbl… for Labels btn… for Buttons After that, capitalize the first letter of each word txtHoursWorked is clearer than txthoursworked

28 Event Handler – Compute Gross Pay
Private Sub btnCalcGrossPay_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCalcGrossPay.Click ‘Define a variable to hold the gross pay. Dim sngGrossPay As Single ‘Convert the values in the text boxes to numbers, ‘and calculate the gross pay. sngGrossPay = CSng(txtHoursWorked.Text) * CSng(txtPayRate.Text) ‘Format the gross pay for currency display and ‘assign it to the Text property of a label. lblGrossPay.Text = FormatCurrency(sngGrossPay) End Sub

29 Event Handler - Close Private Sub btnClose_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnClose.Click ‘End the program by closing its window. Me.Close() End Sub

30 Language Elements Keywords: Words with special meaning to Visual Basic (e.g., Private, Sub) Programmer-defined-names: Names created by the programmer (e.g., sngGrossPay, btnClose) Operators: Special symbols to perform common operations (e.g., +, -, *, and /) Remarks: Comments inserted by the programmer – these are ignored when the program runs (e.g., any text preceded by a single quote)

31 Language Elements: Syntax
Syntax defines the correct use of key words, operators, & programmer-defined names Similar to the syntax (rules) of English that defines correct use of nouns, verbs, etc. A program that violates the rules of syntax will not run until corrected

32 The Programming Process
1.4 The Programming Process The Programming Process Consists of Several Steps, Which Include Design, Creation, Testing, and Debugging Activities Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

33 Step 1 of Developing an Application
Clearly define what the program is to do For example, the Wage Calculator program: Purpose: To calculate the user’s gross pay Input: Number of hours worked, hourly pay rate Process: Multiply number of hours worked by hourly pay rate (result is the user’s gross pay) Output: Display a message indicating the user’s gross pay

34 Step 2 of Developing an Application
Visualize the application running on the computer and design its user interface

35 Step 3 of Developing an Application
Make a list of the controls needed Type Name Description TextBox txtHoursWorked Allows the user to enter the number of hours worked. TextBox txtPayRate Allows the user to enter the hourly pay rate Label lblGrossPay Displays the gross pay, after the btnCalcGrossPay button has been clicked Button btnCalcGrossPay When clicked, multiplies the number of hours worked by the hourly pay rate Button btnClose When clicked, terminates the application Label (default) Description for Number of Hours Worked TextBox Label (default) Description for Hourly Pay Rate TextBox Label (default) Description for Gross Pay Earned Label Form (default) A form to hold these controls

36 Step 4 of Developing an Application
Define values for each control's relevant properties: Control Type Control Name Text Form (Default) "Wage Calculator" Label (Default) "Number of Hours Worked" Label (Default) "Hourly Pay Rate" Label (Default) "Gross Pay Earned" Label lblGrossPay "$0.00" TextBox txtHoursWorked "" TextBox txtPayRate "" Button btnCalcGrossPay "Calculate Gross Pay" Button btnClose "Close"

37 Step 5 of Developing an Application
List the methods needed for each control: Method Description btnCalcGrossPay_Click Multiplies hours worked by hourly pay rate These values are entered into the txtHoursWorked and txtPayRate TextBoxes Result is stored in lblGrossPay Text property btnClose_Click Terminates the application

38 Step 6 of Developing an Application
Create pseudocode or a flowchart of each method: Pseudocode is an English-like description in programming language terms A flowchart is a diagram that uses boxes and other symbols to represent each step Store Hours Worked x Hourly Pay Rate in sngGrossPay. Store the value of sngGrossPay in lblGrossPay.Text. Start End Multiply hours worked by hourly payrate. Store result in sngGrossPay. Copy value in sngGrossPay to lblGrossPay text property

39 Step 7 of Developing an Application
Check the code for errors: Read the flowchart and/or pseudocode Step through each operation as though you are the computer Use a piece of paper to jot down the values of variables and properties as they change Verify that the expected results are achieved

40 Step 8 of Developing an Application
Use Visual Basic to create the forms and other controls identified in step 3 This is the first use of Visual Basic, all of the previous steps have just been on paper In this step you develop the portion of the application the user will see

41 Step 9 of Developing an Application
Use Visual Basic to write the code for the event procedures and other methods created in step 6 This is the second step on the computer In this step you develop the methods behind the click event for each button Unlike the form developed on step 8, this portion of the application is invisible to the user

42 Step 10 of Developing an Application
Attempt to run the application - find syntax errors Correct any syntax errors found Syntax errors are the incorrect use of an element of the programming language Repeat this step as many times as needed All syntax errors must be removed before Visual Basic will create a program that actually runs

43 Step 11 of Developing an Application
Run the application using test data as input Run the program with a variety of test data Check the results to be sure that they are correct Incorrect results are referred to as a runtime error Correct any runtime errors found Repeat this step as many times as necessary

44 Visual Studio and the Visual Basic Environment
1.5 Visual Studio and the Visual Basic Environment Visual Studio Consists of Tools That You Use to Build Visual Basic Applications Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

45 The Visual Studio IDE Visual Studio is an integrated development environment, often abbreviated as IDE Provides everything needed to create, test, and debug software including: The Visual Basic language Form design tools to create the user interface Debugging tools to help find and correct programming errors Visual Studio supports other languages beside Visual Basic such as C++ and C#

46 The Visual Basic Environment
Tutorial 1-4 introduces elements of the IDE: Customizing the IDE Design window – a place to design and create a form Solution Explorer window – shows files in the solution Properties window – modify properties of an object Dynamic Help window – a handy reference tool Toolbar – contains icons for frequently used functions Toolbox window – objects used in form design Tooltips – a short description of button’s purpose

47 STARTING OUT WITH Visual Basic 2008
FOURTH EDITION Tony Gaddis Haywood Community College Kip Irvine Florida International University

48 Creating Applications With Visual Basic
Chapter Creating Applications With Visual Basic 2 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

49 Introduction Develop your first application:
Display a map and written directions to the Highlander Hotel Use a form with Labels Use a PictureBox control Use Buttons Write an event procedure

50 Building the Directions Application
2.1 In This Section You Create Your First Visual Basic Application: a Window That Displays a Map and Road Directions to a Hotel Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

51 Define What the Program is To Do
Purpose: Display a map to the Highlander Hotel Input: None Process: Display a form Output: Display a graphic image showing a map on the form

52 Visualize and Design the User Interface
Below is a sketch of the form to be shown

53 List the Controls Needed
Control Type Control Name Description Form Form1 A small form that will serve as (Default Name) the window onto which the other controls will be placed Label Label1 Displays the message (Default Name) "Directions to the Highlander Hotel" PictureBox PictureBox1 Displays the graphic image (Default Name) showing the map to the hotel

54 Define Control Relevant Property Values
Form Name: Form1 Text: "Directions" Label Name: Label1 Text: "Directions to the Highlander Hotel" TextAlign: MiddleCenter Font: Microsoft sans serif, bold, 18 point PictureBox Name: PictureBox1 Picture: HotelMap.jpg SizeMode: StretchImage

55 Use VB to Create the Application
Establish the Form and set its Text property Add a Label control Position and resize it on the form Set Text, TextAlign, and Font properties Add a PictureBox control Set Image property to display HotelMap.jpg Run the application Close and save the application

56 Project Organization on Disk
User creates a new project in Visual Studio A solution and a folder are created at the same time with the same name as the project The project belongs to the solution Multiple projects can be included in a solution The folder stores files related to the project including: A solution file (.sln) A project file (.vbproj)

57 Opening an Existing Project
Use Recent Projects list on Start Page Provided it hasn’t been moved or deleted Use Open Project button on Start Page Then browse using Open Project dialog box Use Open Project option on File menu

58 Properties Window Used to view and modify the property values of a given object Two views of the properties are available: Alphabetic (across all properties) Categorized (groups properties by logical use)

59 Write the Event Procedures for the Directions Application
Responding to Events 2.2 An Application Responds to Events, Such As Mouse Clicks and Keyboard Input, by Executing Code Known As Event Procedures Write the Event Procedures for the Directions Application Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

60 Augment the Hotel Application
Now the hotel owner wants to add an option to view written directions:

61 Controls to be Added Control Type Control Name Description Label lblDirections Displays written directions to the hotel Button btnDisplayDirections When clicked, causes lblDisplayDirections text to appear on the form Button btnExit Stops the application when clicked

62 Control Properties Label: Name: lblDirections
Text: "Traveling on I-89, take…“ Visible: False Button: Name: btnDisplayDirections Text: "Display Directions“ Name: btnExit Text: "Exit"

63 Method btnDisplayDirections_Click
Marks the beginning of this event procedure Name of the control that owns the event procedure Name of the event the procedure responds to Line Continuation Mark Private Sub btnDisplayDirections_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnDisplayDirections.Click ' Make the directions visible lblDirections.Visible = True End Sub Event handled by this procedure Makes the control lblDirections visible: Assigns the value True to the Visible Property of the lblDirections control.

64 Syntax for Referring to the Value of a Control's Property
Specify the control name (lblDirections) Then a dot Then the PropertyName (Visible) For example: lblDirections.Visible refers to the Visible property of the lblDirections control The visible property values may only be true or false

65 Syntax for an Assignment Statement
Specify the item to receive the value Then the equal symbol Then the value to be assigned For example: lblDirections.Visible = True Assigns the value True to the Visible property of the lblDirections control Causes the text of the lblDirections control to become visible to the user

66 Method btnExit_Click Marks the beginning of this event procedure
Name of the control that owns the event procedure Name of the event the procedure responds to Line Continuation Mark Private Sub btnExit_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnExit.Click ' End the application by closing the window Me.Close() End Sub Event handled by this procedure Closes the current form, referred to as Me, and ends the program

67 Use Visual Basic to Update the Application
Place the label and the buttons on the form Enter the code for the two procedures Test the application

68 Additional Properties
Color properties for a control: BackColor: Sets the background (fill) color ForeColor: Sets the foreground (text) color Border style properties for a form: Sizable: (Default) Has min, max, and close buttons; can be resized by dragging edges Fixed3D: Has a 3D look; min, max, and close buttons; cannot be resized FixedSingle: Has single line border; min, max, and close buttons; cannot be resized

69 Modifying the Text Property With Code
2.3 Modifying the Text Property With Code Quite Often, You Will Need to Change a Control’s Text Property With Code This Is Done With an Assignment Statement Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

70 Modifying the Text Property in Code
Suppose a form is established with a label lblMessage whose Text property is: 1 Kilometer = ? And on a btnFeet button click, we want to change the value of the text property to: 1 Kilometer = 3,281 feet

71 Modifying the Text Property in Code
Private Sub btnFeet_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnFeet.Click ' Display the conversion to feet. lblMessage.Text = "1 Kilometer = 3,281 feet" End Sub Assigns the string to the right of the equal sign to the text property of lblMessage This replaces the previous text property of lblMessage with the new value shown

72 The AutoSize, BorderStyle, and TextAlign Properties
2.4 The AutoSize, BorderStyle, and TextAlign Properties The Label Control’s AutoSize Property Allows a Label to Change Size Automatically to Accommodate the Amount of Text in its Text Property The BorderStyle Property Allows You to Set a Border Around a Label Control Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

73 AutoSize Property for Labels
AutoSize is a Boolean (either True or False) Property of labels False (the default) means the box size will not change, regardless of the amount of text assigned to it True means the box will automatically resize itself to fit the amount of text assigned to it

74 BorderStyle Property for Labels
BorderStyle determines the look of the box None (the default) means no border FixedSingle results in a border one pixel wide Fixed3D gives the border a recessed 3-dimensional look

75 TextAlign Property for Labels
The value of TextAlign establishes the alignment (or justification) or the text: TopLeft TopCenter TopRight The assignment statement below forces the text of lblTitle to appear in the middle center of the label lblTitle.TextAlign = ContentAlignment.MiddleCenter MiddleLeft MiddleCenter MiddleRight BottomLeft BottomCenter BottomRight

76 2.5 Clickable Images Controls Other Than Buttons Have Click Event Procedures PictureBox Controls Can Respond to Mouse Clicks Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

77 PictureBox Control As we saw earlier the Image Property can be set to a graphic image of some sort The flag images in Tutorial 2-16 are clickable The click event can be handled by code to take whatever action is desired

78 PictureBox Click Event code
When PictureBox picUSA is clicked, the lblMessage text property is set to display United States of America Private Sub picUSA_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles picUSA.Click ' Display the country name lblMessage.Text = "United States of America" End Sub

79 Using Visual Studio Help
2.6 Using Visual Studio Help Learn to Use the Visual Studio Help System Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

80 Microsoft Document Explorer
The Visual Studio Help, also called Microsoft Document Explorer, contains these options: How Do I – a task-based topics list by category Search – find help topics using words/phrases Contents – displays a table of contents for help Index – Search using predefined keywords Favorites help – lets you bookmark help topics Dynamic help – help for current task performed

81 Context-Sensitive Help (F1 Key)
Displays information about whatever feature the user is currently focused on For example: Click on a Button control Press F1 Help explains all about the Button control Click on a Label control Help explains all about the Label control

82 Debugging Your Application
2.7 Debugging Your Application At Some Point, Most Applications Contain Bugs, or Errors That Prevent the Application From Operating Properly Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

83 Types of Errors: Compile Errors
These are errors in the syntax (form) of your program Visual Basic will inform you of these errors as soon as the code is entered The area of the error will be underlined with a jagged blue line A description of the error will be given in the Error List window Display this window by selecting Error List from the View menu option

84 Types of Errors: Runtime Errors
Some errors occur as your program runs These are different from syntax errors which occur as the code is entered by the programmer Runtime errors occur when Visual Basic attempts to perform an operation that cannot be executed

85 STARTING OUT WITH Visual Basic 2008
FOURTH EDITION Tony Gaddis Haywood Community College Kip Irvine Florida International University

86 Input, Variables, Exceptions, And Calculations
Chapter Input, Variables, Exceptions, And Calculations 3 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

87 Introduction This chapter covers the use of text boxes to gather input from users It also discusses the use of variables named constants Type conversion functions mathematical calculations Format menu commands the Load procedure of a form

88 3.1 Gathering Text Input In This Section, We Use the Textbox Control to Gather Input That the User Has Typed on the Keyboard Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

89 The TextBox Control A text box is a rectangular area on a form that accepts input from a keyboard Tutorial 3-1 provides an example in the use of a text box txtUserName lblGreeting btnClose btnShowGreeting

90 The Text Property of a TextBox
A user can change the text property of a text box simply by typing in the text box A programmer can change the text property of a text box with an assignment statement Uses the form Object.Property similar to working with the text property of a label The following code assigns the text to the right of the equal sign to the text property of a TextBox box txtInput left of the equal sign txtInput.Text = “Type your name”

91 The Text Property of a TextBox
We can also use the text property of a text box to retrieve something the user has typed The following code assigns the text in txtInput to the text property of the label lblSet lblSet.Text = txtInput.Text Once again we use the form Object.Property This is the standard format to refer to any property of any object

92 Clearing a TextBox Can be done with an assignment statement:
txtInput.Text = "" Two adjacent quote marks yields a null string So this replaces whatever text was in txtInput with "nothing" -- a string with no characters Can also be done with a method: txtInput.Clear() Clear is a Method, not a Property Methods are actions – as in clearing the text Uses the form Object.Method

93 String Concatenation We often need to combine two or more strings into a longer one This operation is called Concatenation Concatenation is signaled by the '&' operator in the same way addition is signaled by a '+'

94 String Concatenation Assume the user has entered their name into the TextBox txtName Label lblGreeting can say, “Hello” to any name found in the TextBox lblGreeting.Text = "Hello " & txtName.Text Appends user name in txtName.Text to “Hello ” and stores result in text property of lblGreeting

95 String Concatenation Tutorial 3-2 provides another example of how to concatenate strings from text boxes txtDayOfWeek txtMonth txtDayOfMonth txtYear lblDateString btnExit btnClear btnShowDate

96 Aligning Controls in Design Mode
When dragging a control to a form, it can be aligned with a control already on the form Guide lines automatically appear Blue guide lines appear for vertical alignment Lavender guide lines for horizontal alignment Horizontal alignment example

97 The Focus Method For a control to have the focus means that it is ready to receive the user's input In a running form, one and only one of the controls on the form may have the focus Only a control capable of receiving some sort of input may have the focus The focus can be set to a control in code using the Focus method: txtUserName.Focus()

98 The Focus Method You can tell which control has focus by its characteristics: When a TextBox has focus, it will have a blinking cursor or its text will be highlighted When a button, radio button, or a check box has focus, you’ll see a thin dotted line around the control Tutorial 3-3 shows an example of the Focus method

99 Controlling Form Tab Order with the TabIndex Property
Tab key steps focus from one control to the next This order is set by the TabIndex property The Tab key causes the focus to jump to the control with the next highest TabIndex value The TabIndex property is best changed with the Tab Order option from the View menu Displays the form in tab order selection mode Set a new tab order by clicking the controls in the order you want This sets the numeric TabIndex value

100 Keyboard Access Keys in Buttons
Say your form had a button with the text "Save" on it You can allow the user to activate the button using Alt-S instead of a mouse click Just change the button text property to "&Save" The character following the '&' (S in this case) is designated as an access key Be careful not to use the same access key for two different buttons

101 '&' Has Special Meaning in a Button
Note that the '&' in "&Save" does not display in the button control on the form It simply establishes the Alt Key access In order to actually display an '&' on a button, it must be entered as "&&“ Button text Save & Exit is entered as Save && Exit

102 Setting the Accept Button
The accept button is a button that is implicitly activated if the user hits the Enter Key The AcceptButton Property designates which button on the form will behave in this manner The button clicked most frequently on a form is usually assigned as the accept button

103 Setting the Cancel Button
The cancel button is a button that is implicitly activated if the user hits the Escape Key The CancelButton Property designates which button on the form will behave in this manner Any exit or cancel button on a form is a candidate to become the cancel button Tutorial 3-5 provides examples of setting access keys, accept, and cancel buttons

104 Variables and Data Types
3.2 Variables Hold Information That May Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

105 Why Have Variables? A variable is a storage location in the computer’s memory, used for holding information while the program is running The information that is stored in a variable may change, hence the name “variable”

106 What Can You Do With Variables?
Copy and store values entered by the user, so they may be manipulated Perform arithmetic on values Test values to determine that they meet some criterion Temporarily hold and manipulate the value of a control property Remember information for later use in the program

107 How to Think About Variables
You the programmer make up a name for the variable Visual Basic associates that name with a location in the computer's RAM The value currently associated with the variable is stored in that memory location

108 Declaring Variables A variable declaration is a statement that creates a variable in memory The syntax is Dim VariableName As DataType Dim (short for Dimension) is a keyword VariableName is the programmer designated name As is a keyword DataType is one of many possible keywords for the type of value the variable will contain Example: Dim intLength as Integer

109 Declaring Multiple Variables
Several variables may be declared in one statement if they all hold the same type of value Dim intLength, intWidth, intHeight as Integer Or this can be done in 3 separate statements Dim intLength as Integer Dim intWidth as Integer Dim intHeight as Integer

110 Setting the Value of a Variable
An assignment statement is used to set the value of a variable, as in: Assign the value 112 to the variable length length = 112 Assign the string literal “Good Morning “ followed by the contents of the text box txtName to the variable greeting greeting = "Good Morning " & txtName.Text An assignment changes only the left operand The right operand remains unchanged

111 Visual Basic Data Types
Integer types Byte Short Integer Long Floating-Point types Single Double Decimal Other data types Boolean Char String Date

112 Integer Data Types For values that will always be a whole number
Usually name a variable starting with a 3 or 4 letter prefix indicating the variable’s type Data Type Naming Prefix Description Byte byt Unsigned integer from 0 to 255 Short shrt Signed integer from -32,768 to 32,767 Integer int Signed integer from -2,147,483,648 to 2,147,483,647 Long lng Signed integer from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

113 Floating-Point Data Types
For values that may have fractional parts Single used most frequently Double sometimes used in scientific calculations Decimal often used in financial calculations Data Type Naming Prefix Description Single sng As large as 1038 plus or minus, 7 decimal positions Double dbl As large as plus or minus,15 decimal positions Decimal dec As large as 1029 plus or minus, 29 decimal positions

114 Other Common Data Types
Boolean – variable naming prefix is bln Holds 2 possible values, True or False Char – variable naming prefix is chr Holds a single character Allows for characters from other languages String – variable naming prefix is str Holds a sequence of up to 2 billion characters Date – variable naming prefix is dat Can hold date and/or time information

115 Working with the String Data Type
A string literal is enclosed in quotation marks The following code assigns the name Jose Gonzales to the variable strName Dim strName as string strName = "Jose Gonzales" An empty string literal can be coded as: Two consecutive quotation marks strName = "" Or by the special identifier String.Empty strName = String.Empty

116 Working with the Date Data Type
Date data type variables can hold the date and time A date literal is enclosed within # symbols startDate = #10/20/2005 6:30:00 AM# or startDate = #12/10/2005# or startTime = #21:15:02# Or can use a function to convert a string to a date startDate = System.Convert.ToDateTime("12/3/2002") System.Convert.ToDateTime function is used to store a date from a text box in a date variable userDate = System.Convert.ToDateTime(txtDate.text)

117 Assigning Text to a Variable
Tutorial 3-6 provides an example of how the contents of text boxes are assigned to a string variable ' Declare a string variable to hold the full name. Dim strFullName As String ' Combine the first and last names ' and copy the result to lblFullName strFullName = txtFirstName.Text & " " & txtLastName.Text lblFullName.Text = strFullName

118 Variable Naming Rules The first character of a variable name must be a letter or an underscore Subsequent characters may be a letter, underscore, or digit Thus variable names cannot contain spaces or periods (or many other kinds of characters) Visual Basic keywords cannot be used as variable names

119 Variable Naming Conventions
Naming conventions are a guideline to help improve readability but not required syntax A variable name should describe its use Each data type has a recommended prefix, in lower case, that begins the variable name The 1st letter of each subsequent word in the variable name should be capitalized intHoursWorked - an integer variable strLastName - a string (or text) variable

120 Declaring Variables with IntelliSense
As you enter your program, VB often aids you by offering a list of choices that could be used at that point After typing "As" in a variable declaration, VB will offer an alphabetical list of all possible data types Type the first few letters of the data type name Intellisense box will highlight the matching type Press the Tab key to select highlighted choice Or just complete typing the entire data type name

121 Default Values and Initialization
When a variable is first created in memory, it is assigned a default value numeric types are given a value of zero Boolean types are given a value of False strings are given a value of Nothing dates default to 12:00:00 AM January 1,1 Good practice to initialize string variables Dim strName as String = String.Empty String with value Nothing causes error if used

122 Initialization of Variables
Can provide a starting or initialization value for any type of variable in a Dim statement Usually want to set an initial value unless assigning a value prior to using the variable Just append = value to the Dim statement where value is the literal to be assigned to the variable Dim intMonthsPerYear As Integer = 12

123 Performing Calculations
3.3 Performing Calculations Visual Basic Has Powerful Arithmetic Operators That Perform Calculations With Numeric Variables and Literals Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

124 Common Arithmetic Operators
Visual Basic provides operators for the common arithmetic operations: + Addition - Subtraction * Multiplication / Division ^ Exponentiation

125 Common Arithmetic Operators
Addition decTotal = decPrice + decTax Subtraction decNetPrice = decPrice – decDiscount Multiplication dblArea = dblLength * dblWidth Division sngAverage = sngTotal / intItems Exponentiation dblCube = dblSide ^ 3

126 Special Integer Division Operator
The backslash (\) is used as an integer division operator Divides one integer by another The result is always an integer, created by discarding any remainder from the division If calculating the number of hours in a given number of minutes intHours = intMinutes \ 60 With intMinutes equal to 190, this calculation will result in the value 3 assigned to intHours

127 Modulus (MOD) Operator
This operator can be used in place of the backslash operator to give the remainder of a division operation intRemainder = 17 MOD 3 ‘result is 2 dblRemainder = 17.5 MOD 3 ‘result is 2.5 Use of the \ or MOD operator to perform integer division by zero causes a DivideByZeroException runtime error

128 Retrieving the Current Date/Time
A series of keywords yields the current date, current time, or both Description Keyword Example Date & Time Now datCurrent=Now Time only TimeOfDay datCurrTime=TimeOfDay Date only Today datCurrDate=Today Variables datCurrent, datCurrTime, and datCurrDate must be declared as Date data types

129 Scope and Local Variables
Scope refers to the part of the program where: A variable is visible and May be accessed by program code Variables declared within a procedure are called local variables and observe these characteristics Scope begins where variable is declared Extends to end of procedure where declared Variable is not visible outside the procedure A variable cannot be declared twice in the same procedure

130 Class-Level and Global Scope
A variable declared inside a class but outside any procedure is a class-level variable Scope is throughout all procedures of the class A variable declared outside any class or procedure is a global variable Scope is throughout all forms, classes, and procedures of the project Class-level and global scope will be discussed further in future chapters Values in a variable are destroyed when it goes out of scope

131 Combined Assignment Operators
Often need to change the value in a variable and assign the result back to that variable For example: var = var – 5 Subtracts 5 from the value stored in var Other examples: x = x + 4 Adds 4 to x x = x – 3 Subtracts 3 from x x = x * 10 Multiplies x by 10 VB provides for this common need with combined assignment operators

132 Combined Assignment Operators
These special assignment operators provide an easy means to perform these common operations: Operator Usage Equivalent to Effect += x += 2 x = x + 2 Add to -= x -= 5 x = x – 5 Subtract from *= x *= 10 x = x * 10 Multiply by /= x /= y x = x / y Divide by \= x \= y x = x \ y Int Divide by &= name &= last name = name & last Concatenate

133 Arithmetic Operator Precedence
Operator precedence tells us the order in which operations are performed From highest to lowest precedence: Exponentiation (^) Multiplicative (* and /) Integer Division (\) Modulus (MOD) Additive (+ and -) Where precedence is the same, operations occur from left to right

134 Operator Precedence Examples
The result is very different when the divide by 2 operation is moved from the end of the calculation to the middle. 6 * 2^3 + 4 / 2 6 * / 2 / 2 50 6 / 2 * 2^3 + 4 6 / 2 * 3 * 28

135 Grouping with Parentheses
Parentheses () can be used to force selected parts of an expression to be evaluated before others Assume we’re computing the average of 3 numbers dblAvg = int1 + int2 + int3 / 3 ‘incorrect int3 / 3 is evaluated first That result is added to int1 and int2 Use parentheses to control order of operations dblAvg = (int1 + int2 + int3) / 3 ‘correct int1 + int2 + int3 is evaulated first That result is divided by 3 When in doubt, use parentheses!

136 Mixing Different Data Types
3.4 Mixing Different Data Types Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

137 Implicit Type Conversions
A value of one data type can be assigned to a variable of a different type An implicit type conversion is an attempt to convert to the receiving variable’s data type A widening conversion suffers no loss of data Converting an integer to a single Dim sngNumber as Single = 5 A narrowing conversion may lose data Converting a decimal to an integer Dim intCount = 12.2 ‘intCount becomes 12

138 Option Strict Option Strict is a VB configuration setting
Only widening conversions are allowed when Option Strict is set to On An integer can be assigned to a decimal A decimal cannot be assigned to an integer A single can be assigned to a double A double cannot be assigned to a single Option Strict On is recommended to help catch errors

139 Type Conversion Runtime Errors
Consider the statement Dim intCount as Integer = “abc123” This is a narrowing conversion With Option Strict On, statement will not compile With Option Strict Off, statement compiles but String “abc123” will not convert to an integer A runtime error called a type mismatch occurs when this statement is executed

140 Named Constants Programs often need to use given values
For example: decTotal *= 1.06 Adds 6% sales tax to an order total Two problems with this approach The reason for multiplying decTotal by isn’t always obvious If sales tax rate changes, must find and change every occurrence of .06 or 1.06 Use of named constants resolves both these issues

141 Named Constants Can declare a variable whose value is set at declaration and cannot be changed later: Const sngSALES_TAX_RATE As Single = 1.06 Looks like a normal declaration except: Const used instead of Dim An initialization value is required By convention, entire name capitalized with underscore characters to separate words The objective of our code is now clearer decTotal *= sngSALES_TAX_RATE

142 Explicit Type Conversions
A function performs some predetermined operation and provides a single output VB provides a set of functions that permit narrowing conversions with Option Strict On These functions will accept a constant, variable name, or arithmetic expression The function returns the converted value

143 Explicit Type Conversions
The following narrowing conversions require an explicit type conversion Double to Single Single to Integer Long to Integer Boolean, Date, Object, String, and numeric types represent different sorts of values and require conversion functions as well

144 Explicit Type Conversion Examples
Rounding can be done with the CInt function intCount = CInt(12.4) ‘intCount value is 12 intCount = CInt(12.5) ‘intCount value is 13 CStr converts an integer value to a string Dim strText as String = CStr(26) CDec converts a string to a decimal value Dim decPay as Decimal = CDec(“$1,500”) CDate converts a string to a date Dim datHired as Date = CDate(“05/10/2005”)

145 A Full List of Conversion Functions
There are conversion functions for each data type CBool ( expr ) CByte ( expr ) CChar ( expr ) CDate ( expr ) CDbl ( expr ) CDec ( expr ) CInt ( expr ) CLng ( expr ) CObj ( expr ) CShort ( expr ) CSng ( expr ) CStr ( expr )

146 Invalid Conversions Conversion functions can fail
Dim dblSalary as Double = CDbl(“xyz”) Dim datHired as Date = CDate(“05/35/2005”) String “xyz” can’t be converted to a number There’s no day 35 in the month of May These failed conversions cause a runtime error called an invalid cast exception

147 The Val Function The Val function is a more forgiving means of performing string to numeric conversions Uses the form Val(string) as shown here If the initial characters form a numeric value, the Val function will return that Otherwise, it will return a value of zero

148 The Val Function Val Function Value Returned Val("34.90“) 34.9
Val("86abc“) 86 Val("$24.95“) 0 Val("3,789“) 3 Val("“) 0 Val("x29“) 0 Val("47%“) 47 Val("Geraldine“) 0

149 Formatting Numbers and Dates
3.5 Formatting Numbers and Dates Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

150 The ToString Method Converts the contents of a variable as a string
Every VB data type has a ToString method Uses the form VariableName.ToString Value in VariableName is converted to a string For example Dim number as Integer = 123 lblNumber.text = number.ToString Converts integer 123 to string “123” Then assigns the string to the text property of the lblNumber control

151 ToString Method with Format String
Can pass a format string to the ToString method Indicates how you want to format the string For example Dim dblSample as Double Dim strResult as String dblSample = strResult = dblSample.ToString(“c”) The value “c” is a format string Converts to currency format $1,234.50

152 Types of Format Strings
N or n – number format includes commas and displays 2 digits to the right of the decimal F or f – fixed point format 2 digits to the right of the decimal but no commas C or c – currency format includes dollar sign, commas, and 2 digits to the right of the decimal P or p – percent format multiplies number by 100 and displays with a trailing space and percent sign The computer’s regional settings determine some format items such as currency symbol

153 Specifying Decimal Positions
Can add an integer to the format string to indicate number of digits to display after the decimal point Rounding occurs when displaying fewer decimal positions than the number contains as in the 2nd line Number Value Format String ToString() Value 12.3 n3 12.300 12.348 n2 12.35 n 1,234,567.10 f2 .234 p 23.40 % c ($1,234,567.80)

154 Specifying Integer Leading Zeros
Can specify a minimum width when displaying an integer value Leading zeros are inserted to meet the minimum width if needed Integer Value Format String ToString() Value 23 d d4 0023 1 d2 01

155 Formatting Dates and Times
The ToString method can format a Date or DateTime value in a variety of ways If the date is 4/7/2008 and the time is 3:22:18 PM Tutorial 3-8 provides an opportunity to work with number formatting concepts Format String Description ToString() Value d Short Date 4/7/2008 D Long Date Monday, April 7, 2008 t Short Time 3:22 PM T Long Time 3:22:18 PM F Full Date/Time Monday, April 7, :22:18 PM

156 Use Exception Handling to Recover Gracefully from Errors
3.6 Exception Handling A Well-Engineered Program Should Report Errors and Try To Continue Or Explain Why It Can’t Continue and Then Shut Down. Use Exception Handling to Recover Gracefully from Errors Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

157 Runtime Errors We’ve shown two possible runtime errors
DivideByZeroException InvalidCastException There are many others Runtime errors occur for may reasons A runtime error results when: Visual Basic throws an exception And it is an unhandled exception Exception handling allows a program to fail gracefully and recover if possible

158 Message Boxes A message box is an easy way to notify the user when an error occurs MessageBox.Show displays a pop-up window with a message and an OK button There are two basic formats MessageBox.Show( message ) MessageBox.Show( message , caption ) message appears in the body of the window caption appears in the title bar of the window

159 Message Box Example The following code displays the message box shown below MessageBox.Show(“Please try again, and enter a number”) The capabilities of the MessageBox will be presented in more detail in Chapter 4

160 Handling Exceptions Visual Basic provides an exception handler
A simple form that ignores some options is: Try try-block Catch [exception-type] catch-block End Try The try-block contains program statements that might throw an exception The catch-block contains statements to execute if an exception is thrown

161 Exception Handling Example
Consider the following exception handling code Try Dim decSalary as Decimal decSalary = CDec(txtSalary.Text) MessageBox.Show(“Your salary is “ _ & decSalary & “ dollars”) Catch MessageBox.Show(“ Please try again,” _ & “and enter a number”, “Entry Error”) End Try If CDec throws a cast exception, the try block catches it, jumps to and executes the catch block which displays the error message

162 More Exception Handling Features
Can catch specific types of messages Can capture and show the exception message issued by Visual Basic Try Dim decAnnualSalary as Decimal Dim intPayPeriods as Integer Dim decSalary as Decimal decAnnualSalary = CDec(txtAnnualSalary.Text) intPayPeriods = CInt(txtPayPeriods.Text) decSalary.Text = decAnnualSalary / intPayPeriods lblSalary.Text = decSalary.ToString() Catch ex as InvalidCastException MessageBox.Show(ex.Message, “Entry Error”) Catch ex as DivideByZeroException MessageBox.Show(“Zero Value Not Allowed “ _ & “ for Pay Periods”) End Try

163 Exception Handling Exercise
Tutorial 3-9 provides an opportunity to work with exception handling concepts

164 Group Boxes and the Load Event Procedure
3.7 Group Boxes and the Load Event Procedure The GroupBox Control Is Used to Group Other Controls. The Load Event Procedure Is Executed When a Form Loads Into Memory Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

165 The GroupBox Control A GroupBox creates a grouping of controls
Controls are enclosed in a box with a title It’s apparent the controls within the GroupBox are related in some way Controls in a GroupBox have their own tab order Moving a GroupBox moves its controls with it Removing a GroupBox also removes all controls within it

166 Placing Controls within a Group Box
Must create the GroupBox first Then select the GroupBox control and Double-click the tool from the ToolBox to place the control in the group or Click and drag the control from the ToolBox to the GroupBox To move an existing control to a GroupBox Select the control and cut it from the form Select the group and paste the control into it

167 GroupBox Tab Order A GroupBox has it’s own place in form tab order
Once the tab order reaches the GroupBox Must tab through all controls in the GroupBox before tabbing to controls outside GroupBox Tab order of controls inside the GroupBox can be assigned in any order The GroupBox to the right is 2nd in the form tab order Tab order of controls in the GroupBox is 2.1, 2.3, & 2.5

168 Selecting Multiple Controls
Multiple controls can be selected and then acted upon as a group Click and drag over the desired controls Any control partially or completely within the selection box will be selected Or hold the Ctrl key while clicking the controls Once selected, a group of controls may Be moved together as a group Be deleted in a single step Have their properties set in a single step

169 Load Event Procedure Every form has a Load event procedure
Automatically executed when the form is displayed Double-click in any empty space on the form The code window will appear Place the code to be executed between the Private Sub and End Sub lines Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Code to be executed when the Form loads End Sub

170 Building the Room Charge Calculator Application
3.8 Building the Room Charge Calculator Application An Opportunity to Apply the Various Concepts Discussed in this Chapter Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

171 The Room Charge Calculator

172 Button Click Event Flowcharts
Calculate Button C l e a r B u t t o n

173 Completed Form

174 More About Debugging: Locating Logic Errors
3.9 More About Debugging: Locating Logic Errors Visual Basic Allows You to Pause a Program, Then Execute Its Statements One at a Time After Each Statement Executes, You May Examine Variable Contents and Property Values Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

175 Debugging Problem The program runs but does not work correctly (has one or more logic errors) Running the program with various inputs has not isolated where those logic errors lie What can be done?

176 Visual Basic Debugging Aids
You can set breakpoints A line or lines you select in your source code When execution reaches this line, it pauses You may then examine the values in variables and certain control properties You may also single step through the program which executes one statement at a time This allows you to see and examine: What is happening one statement at a time Where it is happening What the various data values are (Watches)

177 Visual Basic Debugging Aids
Tutorial 3-12 demonstrates how to Set breakpoints Examine the values of variables and control properties Use the Autos, Locals, and Watch windows Use the Debug Toolbar Step Into Start Debugging Step Out Break All Stop Debugging Step Over

178 STARTING OUT WITH Visual Basic 2008
FOURTH EDITION Tony Gaddis Haywood Community College Kip Irvine Florida International University

179 Making Decisions and Working With Strings
Chapter Making Decisions and Working With Strings 4 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

180 Introduction If…Then If…Then…Else If…Then…ElseIf Select Case
This chapter covers the Visual Basic decision statements If…Then If…Then…Else If…Then…ElseIf Select Case It also discusses the use of Radio Buttons Message Boxes

181 The Decision Structure
4.1 The Decision Structure Allows a Program to Have More Than One Path of Execution Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

182 Order of Statement Execution
Thus far, our code has been executed sequentially in a sequence structure To write meaningful programs we need multiple paths of execution Some statements should be executed under certain circumstances in a decision structure This chapter presents the means to execute statements conditionally Next chapter presents the means to execute the same statements repeatedly

183 The Decision Structure
Flowchart of a typical decision structure Evaluate the condition Is it cold outside? Execute or skip over some code If yes, wear a coat Condition True False Conditional Code

184 The If…Then Statement 4.2 The If…Then Statement Causes Other Statements to Execute Only Under a Certain Condition Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

185 If…Then Statement Syntax
If condition Then statement (more statements as needed) End If New keywords used above: If Then End

186 Relational Operators Test Conditions
Usually a condition is formed using a relational operator A relational operator determines if a specific relationship exists between two values > Greater than < Less than = Equal to <> Not equal to >= Greater than or equal to <= Less than or equal to

187 Binary Operators Relational operators are binary – meaning they use two operands, for example: length > width Is length greater than width? size <= 10 Is size less than or equal 10? Relational operators yield a True or False result

188 If…Then Examples ‘Bonus awarded if sales greater than 50000
If sales > Then getsBonus = True End If ‘Bonus, 12% commission rate, and a day off ‘awarded if sales greater than 50000 If sales > Then getsBonus = True commissionRate = 0.12 daysOff = daysOff + 1 End If

189 If…Then Rules The If and the Then must be on the same line
Only a remark may follow the Then The End If must be on a separate line Only a remark may follow the End If Tutorial 4-1 presents an application that uses the If…Then statement

190 If…Then Programming Style
The code between the If…Then and the End If is indented Visual Basic does not require this It is a convention among programmers to aid in the readability of programs By default, the Visual Basic editor will automatically do this indentation as you enter your program

191 Relational Operators with Math Operators
Either or both relational operator operands may be mathematical expressions Math operators are evaluated before relational operators x+y and a-b are evaluated first Each result is then compared using the > operator If x + y > a - b Then lblMessage.Text = "It is true!" End If

192 Relational Operators With Function Calls
Either or both relational operator operands may be function calls If CInt(txtInput.Text) < 100 Then lblMessage.Text = "It is true!" End If

193 Boolean Variables as Flags
A flag is a Boolean variable that signals when some condition exists in the program Since a Boolean variable is either True or False, it can be used as the condition of an If Since a Boolean variable already evaluates to True or False, an operator is not required If blnQuotaMet Then lblMessage.Text = "You have met your sales quota" End If

194 The If…Then…Else Statement
4.3 The If…Then…Else Statement The If...Then...Else Statement Executes One Group of Statements If the Condition Is True and Another Group of Statements If the Condition Is False Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

195 If…Then vs. If…Then…Else
The If…Then construct will execute or ignore a group of statements (do something or do nothing) The If…Then…Else construct will execute one group of statements or another group (do this or do that) Tutorial 4-2 contains an example of the If…Then…Else construct

196 If…Then…Else Example Condition False True Statement(s) If False
If True If temperature < 40 Then lblMesage.Text = “A little cold, isn’t it?” Else lblMesage.Text = “Nice weather we’re having!” End If

197 The If…Then…ElseIf Statement
4.4 The If…Then…ElseIf Statement The If...Then…Elseif Statement Is Like a Chain of If...Then...Else Statements They Perform Their Tests, One After the Other, Until One of Them Is Found to Be True Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

198 Two Mutually Exclusive Choices
The If…Then…Else has two choices The condition will either be True or False So either the Then clause or Else clause will be executed These are two mutually exclusive choices

199 Multiple Possible Choices
The If…Then…ElseIf statement allows for an entire series of possible choices In pseudo code: If it is very cold Then Wear a coat Elseif it is chilly Wear a light jacket Elseif it is windy Wear a windbreaker Elseif it is hot Wear no jacket

200 Multiple Possible Choices
Each of the series of conditions in an If…Then…ElseIf is tested in sequence When a condition is true, the remaining conditions are ignored The order of the conditions is vital Wrong order can result in wrong decision What if it’s chilly and windy? If windy is tested before chilly, you’d go out with a windbreaker when you need a jacket

201 In Visual Basic Syntax If condition1 Then Statement(s)1
Elseif condition2 Then Statements(s)2 Elseif condition3 Then Statements3 End If

202 In Flowchart Form C1 Statement(s)1 C2 Statement(s)2 C3 Statement(s)3
True Statement(s)1 False C2 True Statement(s)2 False C3 True Statement(s)3 False

203 Example of ElseIf Usage
If sngAverage < 60 Then lblGrade.Text = "F" ElseIf sngAverage < 70 Then lblGrade.Text = "D" ElseIf sngAverage < 80 Then lblGrade.Text = "C" ElseIf sngAverage < 90 Then lblGrade.Text = "B" ElseIf sngAverage <= 100 Then lblGrade.Text = "A" End If Does the order of these conditions matter? What happens if we reverse the order?

204 The Same Code Without ElseIf
If sngAverage < 60 Then lblGrade.Text = "F" End If If sngAverage < 70 Then lblGrade.Text = "D" If sngAverage < 80 Then lblGrade.Text = "C" If sngAverage < 90 Then lblGrade.Text = "B" If sngAverage <= 100 Then lblGrade.Text = "A" Does this code function correctly? What is assigned to lblGrade for a 65 average? 75?

205 The (Optional) Trailing Else
A sequence of ElseIf’s may end with a plain Else, called a trailing Else If none of the conditions are True, the trailing Else statement(s) will be executed

206 Use of a Trailing Else If average is greater than 100, lblGrade is assigned the text “Invalid” If sngAverage < 60 Then lblGrade.Text = "F" ElseIf sngAverage < 70 Then lblGrade.Text = "D" ElseIf sngAverage < 80 Then lblGrade.Text = "C" ElseIf sngAverage < 90 Then lblGrade.Text = "B" ElseIf sngAverage <= 100 Then lblGrade.Text = "A" Else lblGrade.Text = "Invalid" End If

207 4.5 Nested If Statements A Nested If Statement Is an If Statement in the Conditionally Executed Code of Another If Statement Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

208 If Statements Within If Statements
Any type of statement may be used inside a set of Then, Else, or ElseIf statements of an If This includes other If statements If statements within If statements create a more complex decision structure called a Nested If

209 Nested If Example A bank customer qualifies for a special loan if:
Earns over & on the job more than 2 years Or been on the job more than 5 years If sngSalary > Then If intYearsOnJob > 2 Then lblMessage.Text = “Applicant qualifies." Else lblMessage.Text = “Applicant does not qualify." End If If intYearsOnJob > 5 Then Note how the convention of indentations emphasizes the structure of nested Ifs.

210 Flowchart Version True False intYearsOnJob > 2 sngSalary > 30000
lblMessage.Text = “Applicant qualifies." “Applicant does not qualify." False True

211 4.6 Logical Operators Logical Operators Combine Two or More Relational Expressions Into a Single Expression Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

212 Visual Basic Logical Operators
Operator Effect And Both operands must be true for the overall expression to be true, otherwise it is false Or One or both operands must be true for the overall Xor One operand (but not both) must be true for the overall expression to be true, otherwise it is false Not Reverses the logical value of an expression

213 The And Operator The truth table for the And Operator True False False
Expression 1 Expression 2 Expression 1 And Expression 2 True False False False True False False False False True True True If temperature < 20 And minutes > 12 Then lblMessage.Text = “Temperature is in the danger zone." End If AndAlso operator works identically but does not test minutes>12 if temperature<20 is false

214 The Or Operator The truth table for the Or Operator True False True
Expression 1 Expression 2 Expression 1 Or Expression 2 True False True False True True False False False True True True If temperature < 20 Or temperature > 100 Then lblMessage.Text = “Temperature is in the danger zone." End If OrElse operator works identically but does not test minutes>12 if temperature<20 is true

215 The Xor Operator The truth table for the Xor Operator True False True
Expression 1 Expression 2 Expression 1 Or Expression 2 True False True False True True False False False True True False If total > 1000 Xor average > 120 Then lblMessage.Text = “You may try again." End If

216 The Not Operator The truth table for the Not Operator False True
Expression 1 Not Expression 1 True False False True If Not temperature > 100 Then lblMessage.Text = "You are below the maximum temperature." End If

217 Checking Numerical Ranges
Checking for a value inside a range uses And Checking for a value outside a range uses Or If x >= 20 And x <= 40 Then lblMessage.Text = “Value is in the acceptable range." End If If x < 20 Or x > 40 Then lblMessage.Text = “Value is outside the acceptable range." End If

218 Precedence of Logical Operators
Logical operators have an order of precedence just as arithmetic operators do From highest to lowest precedence Not And Or Xor As with arithmetic operations, parentheses are often used to clarify order of operations

219 Precedence of Logical Operators
For example, in the statement If x < 0 And y > 100 Or z = 50 x < 0 And y > 100 is evaluated first If the And condition is true, we then evaluate True Or z = 50 If the And condition is false, we then evaluate False Or z = 50 If the Or condition is to be evaluated first parentheses must be used If x < 0 And (y > 100 Or z = 50)

220 Math, Relational, & Logical Operators
Evaluate the following if a=5, b=7, x=100, y=30 If x > a * 10 And y < b + 20 Evaluating the math operators leaves us with If x > 50 And y < 27 Evaluating the relational operators leaves If True And False Evaluating the logical operators leaves False Parentheses make order of operations clear If (x > (a * 10)) And (y < (b + 20))

221 Comparing, Testing, and Working With Strings
4.7 Comparing, Testing, and Working With Strings This Section Shows You How to Use Relational Operators to Compare Strings, and Discusses Several Intrinsic Functions That Perform Tests and Manipulations on Strings Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

222 Strings Can Be Compared
Relational operators can be used to compare strings and string literals as well as numbers strName1 = "Mary" strName2 = "Mark" If strName1 = strName2 Then lblMessage.Text = “Names are the same" Else lblMessage.Text = “Names are NOT the same" End If If strMonth <> "October" Then ' statement End If

223 How Are Strings Compared?
Each character is encoded as a numerical value using the Unicode standard Letters are arranged in alphabetic order The Unicode numeric code for A is less than the Unicode numeric code for B Characters of each string are compared one by one until a difference is found M a r y M a r k Mary is greater than Mark because “y” has a Unicode value greater than “k”

224 How Are Strings Compared?
Upper case letters do not have the same value as their lower case equivalents Upper case letters are less than lower case The >, <, >=, and <= operators can be used with strings as well If one string is shorter than another, spaces are substituted for the missing characters Spaces have a lower value than letters “Hi” has 2 spaces added if compared to “High” “Hi ” is less than “High”

225 The Empty String A space (or blank) is considered a character
An empty string is a string with no characters A string with just spaces has characters in it The empty string is written as "", as in the following code that tests for no input: If txtInput.Text = "" Then lblMessage.Text = "Please enter a value" End If

226 ToUpper Method ToUpper method can be applied to a string
Results in a string with lowercase letters converted to uppercase The original string is not changed littleWord = "Hello" bigWord = littleWord.ToUpper() ' littleWord retains the value "Hello" ' bigWord is assigned the value "HELLO"

227 ToLower Method The ToLower method performs a similar but opposite purpose Can be applied to a string Results in a string with the lowercase letters converted to uppercase The original string is not changed bigTown = “New York" littleTown = bigTown.ToLower() ' bigTown retains the value “New York" ' littleTown is assigned the value “new york"

228 A Handy Use for ToUpper or ToLower
ToUpper or ToLower can be used to perform case insensitive comparisons of strings 1st comparison below is false “Hello”<>“hello” 2nd comparison is true ToLower converts both strings to lower case Causes “hello” to be compared to “hello” Tutorial 4-6 demonstrates how this is used word1 = "Hello“ Word2 = “hello” If word1 = word ‘false, not equal If word1.ToLower() = word2.ToLower() ‘true, equal

229 IsNumeric Function This function accepts a string as an argument and returns True if the string contains a number Dim strNumber as String strNumber = “576” If IsNumeric(strNumber) ‘returns true strNumber = “123abc” If IsNumeric(strNumber) ‘returns false Use IsNumeric function to determine if a given string contains numeric data

230 Determining the Length of a String
The Length method determines the length of a string, e.g.: If txtInput.Text.Length > 20 Then lblMessage.Text = “Enter fewer than 20 characters." End If Note: txtInput.Text.Length means to apply the Length Method to the value of the Text property of the Object txtInput

231 Trimming Spaces from Strings
There are three Methods that remove spaces from strings: TrimStart – removes leading spaces TrimEnd – removes trailing spaces Trim – removes leading and trailing spaces greeting = " Hello " lblMessage1.Text = greeting.TrimStart() ' Returns the value "Hello " lblMessage1.Text = greeting.Trim() ‘ Returns the value "Hello"

232 The Substring Method The Substring method returns a portion of a string or a “string within a string” (a substring) Each character position is numbered sequentially with the 1st character referred to as position zero StringExpression.Substring(Start) returns the characters from the Start position to the end StringExpression.Substring(Start, Length) returns the number of characters specified by Length beginning with the Start position

233 Substring Method Examples
Position 0 Position 7 Dim firstName As String Dim fullName As String = "George Washington" firstName = fullName.Substring(0, 6) ' firstName assigned the value "George" ' fullName is unchanged lastName = fullName.Substring(7) ‘ lastName assigned the value “Washington” ‘ fullName unchanged

234 Search for a String Within a String
Use the IndexOf method StringExpression.IndexOf(Searchstring) Searches the entire string for Searchstring StringExpression.IndexOf(SearchString, Start) Starts at the character position Start and searches for Searchstring from that point StringExpr.IndexOf(SearchString, Start, Count) Starts at the character position Start and searches Count characters for SearchString

235 IndexOf Method Examples
IndexOf will return the starting position of the SearchString in the string being searched Positions are numbered from 0 (for the first) If SearchString is not found, a -1 is returned Tutorial 4-7 provides an opportunity to work with several of the string methods Dim name As String = "Angelina Adams" Dim position As Integer position = name.IndexOf("A", 1) ' position has the value 9 Position 0 Position 9

236 Sometimes You Need a Convenient Way to Display a Message to the User
4.8 The Message Box Sometimes You Need a Convenient Way to Display a Message to the User This Section Discusses the Messagebox.Show Method, Which Allows You to Display a Message in a Dialog Box Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

237 Message Box Arguments A message box is a dialog box with a user message in a pop-up window The following can be specified Message - text to display within the box Caption - title for the top bar of the box Buttons - indicates which buttons to display Icon - indicates icon to display DefaultButton - indicates which button corresponds to the Return Key All arguments but the Message are optional Use of an argument requires those before it

238 MessageBox Buttons Argument
MessageBoxButtons.AbortRetryIgnore Displays Abort, Retry, and Ignore buttons MessageBoxButtons.OK Displays only an OK button MessageBoxButtons.OKCancel Displays OK and Cancel buttons MessageBoxButtons.RetryCancel Display Retry and Cancel buttons MessageBoxButtons.YesNo Displays Yes and No buttons MessageBoxButtons.YesNoCancel Displays Yes, No, and Cancel buttons

239 MessageBox Icon Argument
The Icon argument specifies a particular type of icon to appear in the message box There are 4 possible icons shown to the left Note that some values show the same icon

240 Example Message Box MessageBox.Show("Do you wish to continue?", _
"Please Confirm", _ MessageBoxButtons.YesNo, _ MessageBoxIcon.Question)

241 Which Button Was Clicked
MessageBox returns a value indicating which button the user clicked: DialogResult.Abort DialogResult.Cancel DialogResult.Ignore DialogResult.No DialogResult.OK DialogResult.Retry DialogResult.Yes

242 Which Button Was Clicked Example
Dim result As Integer result = MessageBox.Show("Do you wish to continue?", _ "Please Confirm", MessageBoxButtons.YesNo) If result = DialogResult.Yes Then ' Perform an action here ElseIf result = DialogResult.No Then ' Perform another action here End If

243 The Select Case Statement
4.9 The Select Case Statement In a Select Case Statement, One of Several Possible Actions Is Taken, Depending on the Value of an Expression Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

244 Select Case Statement Similar to If…Then…ElseIf
Performs a series of tests Conditionally executes the first true condition Select Case is different in that: A single test expression may be evaluated The test expression is listed once The possible values of the expression are then listed with their conditional statements Case Else may be included and executed if none of the values match the expression

245 Find Day of Week With Select Case
Select Case CInt(txtInput.Text) Case 1 MessageBox.Show("Day 1 is Monday.") Case 2 MessageBox.Show("Day 2 is Tuesday.") Case 3 MessageBox.Show("Day 3 is Wednesday.") Case 4 MessageBox.Show("Day 4 is Thursday.") Case 5 MessageBox.Show("Day 5 is Friday.") Case 6 MessageBox.Show("Day 6 is Saturday.") Case 7 MessageBox.Show("Day 7 is Sunday.") Case Else MessageBox.Show("That value is invalid.") End Select

246 Select Case With Multiple Values
Select Case strAnimal Case "Dogs", "Cats" MessageBox.Show ("House Pets") Case "Cows", "Pigs", "Goats" MessageBox.Show ("Farm Animals") Case "Lions", "Tigers", "Bears" MessageBox.Show ("Oh My!") End Select

247 Select Case with Operators
Select Case intScore Case Is >= 90 strGrade = “A” Case 80 to 89 strGrade = “B” Case 70 to 79 strGrade = “C” Case 60 to 69 strGrade = “D” Case 0 to 59 strGrade = “F” Case Else MessageBox.Show(“Invalid Score”) End Select Tutorial 4-8 demonstrates the Select Case

248 Introduction to Input Validation
4.10 Introduction to Input Validation Input Validation Is the Process of Inspecting Input Values and Determining Whether They Are Valid Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

249 Validation Example Output is only as good as the input
“Garbage in, garbage out” Input validation is the process of inspecting user input to see that it meets certain rules The TryParse method verifies that an input value is in a valid numeric or date format Decision structures are often used to validate input

250 The TryParse Method Converts an input value to another format
Verifies that input of integers, decimals, dates, etc., are entered in an acceptable format Returns Boolean value indicating True if conversion successful Returns False if unsuccessful Each numeric variable type has a TryParse method Date & Boolean types include the TryParse method as well

251 Verify Integer Entry With TryParse
Use Integer.TryParse method to convert value txtInput.Text contains numeric string to convert intResult receives converted value TryParse returns True if input is an integer TryParse returns False if input is not an integer Dim intResult As Integer If Integer.TryParse(txtInput.Text, intResult) Then lblMessage.Text = "Success!" Else lblMessage.Text = "Error: an integer was not found" End If

252 Verify Date Entry With TryParse
Use Date.TryParse method to convert value txtInput.Text contains date string to convert datBirth receives converted value TryParse returns True if input in date format TryParse returns False if input not a valid date Not used so Then clause indicates invalid date Dim datBirth As Date If Not Date.TryParse(txtInput.Text, datBirth) Then lblMessage.Text = “Not a valid date!“ End If

253 Using If To Check Range of Values
Decision structures often used to validate input Example verifies that entries for both decSales and decAdvance are positive numbers ' Validate the input to ensure that ' no negative numbers were entered. If decSales < 0 Or decAdvance < 0 Then MessageBox.Show("Please enter positive numbers" & _ " for sales and/or advance pay.“, “Error”) EndIf

254 Radio Buttons and Check Boxes
4.11 Radio Buttons and Check Boxes Radio Buttons Appear in Groups of Two or More and Allow the User to Select One of Several Possible Options Check Boxes Allow an Item to Be Selected or Deselected by Checking or Unchecking a Box Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

255 Radio Buttons Used when only one of several possible options may be selected at one time Car radio buttons select one station at a time May be placed in a group box Group box defines a set of radio buttons Can select only one button within a group box Those on a form but not inside a group box are considered members of the same group Radio buttons have a boolean Checked property and a CheckChanged event

256 Checking Radio Buttons in Code
If radCoffee.Checked = True Then MessageBox.Show("You selected Coffee") ElseIf radTea.Checked = True Then MessageBox.Show("You selected Tea") ElseIf radSoftDrink.Checked = True Then MessageBox.Show("You selected a Soft Drink") End If

257 Check Boxes Unlike radio buttons, can select many check boxes at one time May also be placed in a group box Not limited to one selection within a group box Can select as many check boxes as you like within the same group box Check boxes also have a boolean Checked property and a CheckChanged event Tutorial 4-9 provides radio button and check box examples

258 Checking Check Boxes in Code
If chkChoice4.Checked = True Then MessageBox.Show("You selected Choice 4") End If

259 Class-Level Variables
4.12 Class-Level Variables Class-level Variables Are Not Local to Any Procedure In a Form They Are Declared Outside of Any Procedure, and May Be Accessed by Statements in Any Procedure in the Same Form Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

260 Advantages of Class-level Variables
Variable scope refers to the portion of a program in which that variable is visible Variables declared inside a procedure or method have local scope Only visible inside that procedure or method Sometimes a variable needs to be visible to many procedures or methods within a form Variables declared outside a procedure but within a form have class scope These are visible throughout the form Makes communication between procedures easy

261 Declaring a Class-Level Variable
decTotalSalary - class-level variable Declared before first procedure in form class decWeeklyPay - local variable inside a procedure Public Class Form1 Dim decTotalSalary As Decimal ‘Class-level variable Private Sub btnAddWeekly_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddWeekly.Click Dim decWeeklyPay As Decimal 'Local variable decWeeklyPay = CDec(txtPay.Text) decTotalSalary += decWeeklyPay End Sub

262 Class-level Variables Disadvantages
Class-level variables should be used sparingly - only when really needed Why? As programs grow larger, use of variables becomes more difficult to keep track of The smaller the scope the better Smaller scope easier to keep track of

263 The Health Club Membership Fee Calculator Application
4.13 The Health Club Membership Fee Calculator Application The Health Club Membership Fee Calculator uses features discussed in this chapter, including If statements, a Select Case statement, radio buttons, and check boxes Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

264 Health Club Fee Calculator Form

265 Calculate Button Click Event Flowchart

266 Base Monthly Fee Calculation Flowchart
Uses a series of ElseIf statements

267 Calculate Optional Services Flowchart
Uses several If...Then statements

268 Compute Discount Flowchart
Uses a Select Case statement

269 Tony Gaddis Kip Irvine STARTING OUT WITH Visual Basic 2008
FOURTH EDITION Tony Gaddis Haywood Community College Kip Irvine Florida International University

270 Lists, Loops, Validation, and More
Chapter Lists, Loops, Validation, and More 5 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

271 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

272 Input Boxes 5.1 Input Boxes Provide a Simple Way to Gather Input Without Placing a Text Box on a Form Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

273 Format of the InputBox Function
InputBox(Prompt [,Title] [,Default] [,Xpos] [,Ypos]) 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

274 Sample InputBox Usage strUserInput = 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

275 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

276 List Boxes 5.2 List Boxes Display a List of Items and Allow the User to Select an Item From the List Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

277 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

278 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

279 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 Then MessageBox.Show("The list has no items!") End If numEmployees = lstEmployees.Items.Count

280 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

281 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 Try strInput = lstMonths.Items(n).ToString() Catch ex as Exception MessageBox.show(ex.Message) End Try

282 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 Then location = lstLocations.Items(lstLocations.SelectedIndex) End If

283 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 Then month = lstMonths.Items(lstMonths.SelectedIndex) End If If lstMonths.SelectedIndex <> -1 Then month = lstMonths.SelectedItem.ToString) End If

284 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

285 ListBox Items.Add Method
Items can be added to the end of a ListBox list in your VB code using the Add method Format is ListBox.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")

286 ListBox Items.Insert Method
Items can be added at a specific position of a ListBox in VB code using the Insert method ListBox.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")

287 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 item lstStudents.Items.Remove(“Jean”) ‘remove item Jean lstStudents.Items.Clear() ‘remove all items

288 Other ListBox Methods Returns true if Item is found in the collection
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”)

289 A Loop Is Part of a Program That Repeats
5.3 The Do While Loop A Loop Is Part of a Program That Repeats Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

290 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

291 Do While Flowchart The Do While loop
If the expression is true, the statement(s) are executed Expression is then evaluated again As long as the expression remains true, the statement(s) continue to be repeated Expression statement(s) False True

292 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 loop Do While expression statement(s) Loop

293 Do While Example Private Sub btnRunDemo_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnRunDemo.Click ' Demonstrate the Do While loop Dim intCount As Integer = 0 Do While intCount < 10 lstOutput.Items.Add("Hello") intCount += 1 Loop End Sub Note that programming style dictates the body of the loop be indented for clarity

294 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

295 Counters Variables called counters are frequently used to control Do While loops intCount in previous example is a counter Counters generally initialized before loop begins Dim intCount As Integer = 0 Counter must be modified in body of loop intCount += 1 The test expression ends the loop when the counter compares to some value

296 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 once

297 Posttest Loop Syntax and Flowchart
Do statement(s) Loop While expression statement(s) The statement(s) must be executed at least once, irrespective of the expression used Expression True False

298 A Posttest Running Total Loop
intCount = 1 ' Initialize the counter decTotal = 0 ' Initialize total Do strInput = InputBox("Enter the sales for day " & _ intCount.ToString, "Sales Amount Needed") If strInput <> "" Then decSales = CDec(strInput) decTotal += decSales ' Add sales to total intCount += 1 ' Increment the counter End If Loop 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

299 The Do Until and For Next Loops
5.4 The Do Until and For Next Loops 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

300 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

301 Do Until: Pretest & Posttest Forms
Tutorial 5-6 provides a hands-on example of a pretest Do Until loop Do Until expression statement(s) Loop Do statement(s) Loop Until expression

302 Do Until Loop – Test Score Average
strInput = InputBox("How many test scores do you " _ & “want to average?", "Enter a Value") intNumScores = CInt(strInput) ‘ Store starting values sngTotal = 0 intCount = 1 ‘ Get the test scores Do 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 then sngAverage = sngTotal / intNumScores Else sngAverage = 0.0 End If

303 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]

304 For…Next Flowchart False statement(s) True Counter = EndValue? set
to StartValue increment

305 For…Next Example 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 intCount = 1 To 10 intSquare = CInt(intCount ^ 2) strTemp = "The square of " & intCount.ToString _ & “ is “ & intSquare.ToString lstOutput.Items.Add(strTemp) Next intCount

306 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 10 MessageBox.Show("x is now " & x.ToString) Next x For x = 10 To 1 Step -1 MessageBox.Show("x is now " & x.ToString) Next x

307 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

308 Example: Exit a Loop Prematurely
maxNumbers = CInt(InputBox("How many numbers do " & _ "you wish to sum?")) total = 0 For x = 1 to maxNumbers input = InputBox("Enter a number.") If input = "" Then Exit For Else num = CDbl(input) total += num End If Next x MessageBox.Show(“Sum of the numbers is " & total.ToString)

309 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

310 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

311 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

312 A Loop that is Inside Another Loop is Called a Nested Loop
5.5 Nested Loops A Loop that is Inside Another Loop is Called a Nested Loop Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

313 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

314 Nested Loop Example 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 For hours = 0 To 24 lblHours.Text = hours.ToString For minutes = 0 To 59 lblMinutes.Text = minutes.ToString For seconds = 0 To 59 lblSeconds.Text = seconds.ToString Next seconds Next minutes Next hours

315 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

316 Multicolumn List Boxes, Checked List Boxes and Combo Boxes
5.6 Multicolumn List Boxes, Checked List Boxes and Combo Boxes A Multicolumn List Box Displays Items in Columns A Checked List Box Displays a Check Box Next to Each Item in the List A Combo Box Is Like a List Box Combined With a Text Box Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

317 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

318 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

319 Finding the Status of Checked Items
The GetItemChecked method returns true if the item at Index has been checked CheckedListBox.GetItemChecked(Index) Dim i as Integer Dim intCheckedCities as Integer = 0 For i = 0 to clbCities.Items.Count – 1 If clbCities.GetItemChecked(i) = True Then intCheckedCities += 1 End If Next i MessageBox.Show(“You checked “ & _ intCheckedCities.Tostring() & “ cities.”)

320 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

321 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

322 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

323 Combo Box Styles Drop-down List Combo Box
Behaves like a Drop-Down Combo Box, but the user may not enter text directly Tutorial 5-9 demonstrates each style of combo box

324 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

325 5.7 Input Validation As Long As a User Enters Bad Input, the Application Will Produce Bad Output Applications Should Be Written to Filter Out Bad Input Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

326 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

327 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

328 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

329 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()

330 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 = 0 txtNum1.SelectionLength = txtNum1.Text.Length With txtNum1 .SelectionStart = 0 .SelectionLength = .Text.Length End With

331 5.8 Tool Tips Tool Tips Are a Standard, Convenient Way of Providing Help to Users of an Application The 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

332 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

333 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

334 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

335 Building the Vehicle Loan Calculator Application
5.9 Building the Vehicle Loan Calculator Application 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

336 Vehicle Loan Calculator

337 Calculate Button Flowchart

338 Radio Button CheckChanged Events

339 Cost Textbox Validating Event

340 STARTING OUT WITH Visual Basic 2008
FOURTH EDITION Tony Gaddis Haywood Community College Kip Irvine Florida International University

341 Procedures And Functions
Chapter Procedures And Functions 6 A procedure is a collection of statements that performs a task Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

342 Introduction A procedure is a collection of statements that performs a task Event handlers are a type of procedure A function is a collection of statements that performs a task and returns a value to the VB statement that executed it Functions work like intrinsic functions, such as CInt and IsNumeric A method can be either a procedure or a function

343 Procedures 6.1 You Can Write Your Own General Purpose Procedures That Perform Specific Tasks General Purpose Procedures Are Not Triggered by Events but Called From Statements in Other Procedures Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

344 Procedure Uses Ann event handler is a type of procedure
Automatically executed when an event such as a mouse click occurs General purpose procedures are triggered by statements in other procedures, not by events Procedures help simplify & modularize code by: Breaking it into small, manageable pieces Performing a task that is needed repeatedly Dividing a program into a set of logical tasks

345 Sample Procedure, Tutorial 6-1
Private Sub btnGo_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnGo.Click ' This procedure calls the DisplayMessage procedure. lstOutput.Items.Add("Hello from btnGo_Click procedure.") lstOutput.Items.Add("Calling the DisplayMessage " & _ "procedure.") DisplayMessage() lstOutput.Items.Add("Now I am back ” _ & “in the btnGo_Click procedure.") End Sub Calls DisplayMessage procedure Returns to btnGo_Click Sub DisplayMessage() 'A Sub procedure that displays a message. lstOutput.Items.Add("") lstOutput.Items.Add("Hello from DisplayMessage.") End Sub

346 Declaring a Procedure [AccessSpecifier] Sub ProcedureName ([ParameterList]) [Statements] End Sub AccessSpecifier is optional and establishes accessibility to the program Sub and End are keywords ProcedureName used to refer to procedure Use Pascal casing, capitalize 1st character of the name and each new word in the name ParameterList is a list of variables or values being passed to the sub procedure

347 More on the Access Specifier
Private allows use only from that form Public allows use from other forms If not specified, default is Public There are other access specifiers such as: Protected Friend Protected Friend These will be discussed in later chapters Access specifiers won’t be used for now Practice writing procedures in Tutorial 6-2

348 Procedures and Static Variables
Variables needed only in a procedure, should be declared within that procedure Creates a local variable with scope only within the procedure where declared Local variable values are not saved from one procedure call to the next To save value between procedure calls, use Static keyword to create a static local variable Static VariableName As DataType Scope is still only within the procedure But variable exists for lifetime of application

349 Passing Arguments to a Procedure
6.2 When calling a procedure, you can pass it values known as arguments Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

350 Arguments Argument – a value passed to a procedure
We’ve already done this with functions Value = CInt(txtInput.Text) Calls the CInt function and passes txtInput.Text as an argument A procedure must be declared with a parameter list in order to accept an argument

351 Passing Arguments By Value
DisplayValue(5) ‘calls DisplayValue procedure Sub DisplayValue(ByVal intNumber As Integer) ' This procedure displays a value in a message box. MessageBox.Show(intNumber.ToString) End Sub intNumber declared as an integer argument Storage location intNumber created by procedure A value, 5 in this case, must be supplied and is copied into the storage location for intNumber The DisplayValue procedure then executes Tutorial 6-3 demonstrates passing arguments

352 Passing Multiple Arguments
ShowSum(intValue1, intValue2) ‘calls ShowSum procedure Sub ShowSum(ByVal intNum1 As Integer, _ ByVal intNum2 As Integer) ' This procedure accepts two arguments, and prints ' their sum on the form. Dim intSum As Integer intSum = intNum1 + intNum2 MessageBox.Show("The sum is " & intSum.ToString) End Sub Multiple arguments separated by commas Value of first argument is copied to first Second to second, etc.

353 Passing Arguments ByVal or ByRef
Arguments are usually passed ByVal New storage location created for procedure Storage location gets a copy of the value Any changes in value are made to the copy Calling procedure won’t “see” the changes Arguments can also be passed ByRef Procedure points to (references) argument’s original storage location Any changes are made to the original value Calling procedure “sees” the changes

354 ByVal or ByRef Argument Example
Tutorial 6-4 demonstrates the difference between parameters passed ByVal & ByRef Passed ByVal Calling procedure does not “see” changes made to the value of an argument Passed ByRef Calling procedure “sees” changes made to the value of an argument

355 6.3 Functions A Function Returns a Value to the Part of the Program That Called the Function Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

356 Declaring a Function New keyword Function
[AccessSpecifier] Function FunctionName ([ParameterList]) _ As DataType [Statements] End Function New keyword Function Also new is As DataType which states the data type of the value to be returned Return value is specified in a Return expression

357 Function Call Example sngValue1 & sngValue2 must be data type Single
sngTotal = Sum(sngValue1, sngValue2) Function Sum(ByVal sngNum1 As Single, _ ByVal sngNum2 As Single) As Single Dim sngResult As Single sngResult = sngNum1 + sngNum2 Return sngResult End Function sngValue1 & sngValue2 must be data type Single Data types must agree with parameter list sngTotal must be Single, agrees with return value Tutorial 6-5 demonstrates function use

358 Returning Nonnumeric Values
Function FullName(ByVal strFirst As String, _ ByVal strLast As String) As String Dim strName As String strName = strLast & ", " & strFirst Return strName End Function Function IsValid(intNum As Integer) As Boolean Dim blnStatus As Boolean If intNum >= 0 And intNum <= 100 Then blnStatus = True Else blnStatus = False End If Return blnStatus End Function

359 6.4 More About Debugging Step Into Step Over Step Out
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

360 Debugging Involving Procedures
Step Into - continue to debug by single-stepping through a procedure Step Over - run procedure without single-stepping, continue single-step after the call Step Out - end single-stepping in procedure, continue single-step after the call Tutorial 6-6 provides examples

361 Building the Bagel and Coffee Price Calculator Application
6.5 Building the Bagel and Coffee Price Calculator Application Use procedures and functions to calculate the total of a customer order. Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

362 Bagel and Coffee Price Calculator

363 Button Click Event Flowcharts
Calculate Button Reset Button

364 Cost Calculation Functions
Topping Cost Function Bagel Cost Function

365 Cost Calculations Functions
Coffee Cost Function Calc Tax Function

366 STARTING OUT WITH Visual Basic 2008
FOURTH EDITION Tony Gaddis Haywood Community College Kip Irvine Florida International University

367 Multiple Forms, Standard Modules, And Menus
Chapter Multiple Forms, Standard Modules, And Menus 7 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

368 Introduction How to add multiple forms to a project
How to create a standard module Holds procedures and functions not associated with a specific form Creating a menu system Context menus With commands and submenus that the user may select from

369 7.1 Multiple Forms Visual Basic Projects May Have Multiple Forms
A Form Designated as the Startup Object Is Displayed When the Project Executes Other Forms in a Project Are Displayed by Programming Statements Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

370 Form Names Each form has Name property
Programs refer to a form by this name VB assigns name Form1 Name property allows us to change form name Standard prefix is frm Each form also has a file name (.vb extension) Forms are stored on disk using this name Right click in Solution Explorer, and select Rename to change the file name

371 Adding a New Form to a Project
Click Add New Item on the toolbar Or Project on menu, then Add Windows Form Add New Item dialog box appears Click on Windows Form Change the default name Click the Add button New form now appears in: Design window Solution Explorer

372 Switching from Forms to Form Code
Design window has two tabs for each form One for form design One for the code associated with a form If you have two forms frmMain & frmError, you may select these tabs: Error form design Error form code Main form design Main form code

373 Removing a Form A form may also be removed from a project
To remove a form and delete its file from disk: Right-click on the form in Solution Explorer Click Delete on the pop-up menu To remove a form but leave its file on disk: Click Exclude from Project on the pop-up menu

374 Changing the Startup Form
First form in a project becomes startup object Form displayed when application starts Right-click project in Solution Explorer to change startup form Click Properties Click down arrow in Startup Form box Select new startup form from list Click Ok

375 Classes and Instances The form design is a class
It’s only a design or description of a form Think of it like a blueprint A blueprint is a detailed description of a house A blueprint is not a house The form design can be used to create one or more instances of the form Like building a house from the blueprint In order to use a form in a program, we must first create an instance of it from the design

376 Creating an Instance of a Form
Dim statement creates an instance of a form To create an instance of frmError: frmError is the form design name (the class) New frmError creates an instance of the form Variable errorForm refers to the form in RAM errorForm used to perform actions on the form The form is not yet visible, but it now exists Show or ShowDialog makes the form visible Dim ObjectVariable As New ClassName() Dim errorForm As New frmError()

377 Modal Forms & ShowDialog Method
A modal form prevents the user from changing focus to another form in the application as long as it remains open For example: Variable errorForm represents an instance of frmError as shown in the previous slide The ShowDialog method displays the form instance named errorForm as a modal form Must close errorForm in order to change focus to another form in the application errorForm.ShowDialog()

378 Modeless Forms & Show Method
A modeless form allows the user to change focus at will to another form in the application while the modeless form remains open For example: Variable errorForm represents an instance of frmError as shown previously The Show method displays the form instance named errorForm as a modeless form Can change focus to other forms in the application while errorForm remains open errorForm.Show()

379 Closing a Form A form may close itself using the Close method and referring to itself using the keyword "Me": As in Me.Close() Private Sub btnClose_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles btnClose.Click Me.Close() End Sub

380 Hiding a Form Closing a Form removes it from memory
To retain the form in memory but remove it from the display, use the Hide Method: To redisplay a hidden form use the ShowDialog or Show method Me.Hide()

381 More on Modal and Modeless Forms
Display of a modal form causes execution of calling statements to halt until form is closed Display of a modeless form allows execution to continue Tutorial 7-1 demonstrates these differences statement; messageForm.ShowDialog() ' Statements below will not execute ' until the Form is closed statement; messageForm.Show() ' Statements below will execute ‘ immediately after Form is displayed

382 The Form Load Event The Load event is triggered just before the form is initially displayed Any code needed to prepare the form prior to display should be in the Load event If some controls should not be visible initially, set their Visible property in the Load event Double click on a blank area of the form to set up a Load event as shown below Private Sub frmMain_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load End Sub

383 The Form Activated Event
The Activated event is triggered when focus switches to the form from another form or application The Load event is triggered once when the form is initially displayed The Activated event is also triggered when the form is initially displayed Occurs immediately after the Load event The Activated event may be triggered many more times, each time focus shifts back to the form

384 Creating an Activated Event Handler
Create an Activated event handler by selecting frmMain events from the class name drop-down list Then select the Activated Event from the method name drop-down list

385 The Form Closing Event The Closing event is triggered as the form is being closed, but before it has closed The Closing event can be used to ask the user if they really want the form closed Private Sub frmMain_Closing(ByVal sender As Object, _ ByVal e As System.ComponentModel.CancelEventArgs) _ Handles MyBase.Closing If MessageBox.Show(“Are you Sure?”, “Confirm”, _ MessageBoxButtons.YesNo) = DialogResult.Yes Then e.Cancel = False ‘continue, close form Else e.Cancel = True ‘cancel form close End If End Sub

386 The Form Closed Event Closed event triggered after a form is closed
Note that it is now too late to prevent the form from being closed Form is already closed when event fires Create the Closing and Closed events in the same way as the Activated event Click the class name drop-down list Select formname Events Click desired event from the method drop-down list

387 Using Objects on a Different Form
When code in a form refers to an object, it is assumed that object is in that same form You can refer to an object in another form Simply preface the object name with the variable name associated with that form frmGreeting has a control named lblMessage Set Text property to Hello before displaying Dim greetingForm As New frmGreeting() greetingForm.lblMessage.Text = "Hello!" greetingForm.ShowDialog()

388 Class-level Variables in a Form
Class-level variables are Private by default Private variables are not accessible by code in other forms To gain access to variables from other forms, a variable must be declared as: Class level Public Public sngTotal As Single ' Instead of the declaration ' Dim sngTotal As Single

389 Public/Private Procedures in a Form
Procedures, by default, are Public They can be accessed by code outside their form To make a procedure invisible outside its own form, declare it to be Private Tutorial 7-2 provides an opportunity to work with a multiple form application

390 Standard Modules 7.2 A Standard Module Contains Code - Declarations and Procedures - That Are Used by Other Files in a Project Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

391 Standard Modules A separate .vb file not associated with a form
Contains no Event Procedures Used for code to be shared by multiple forms Procedures, functions, or variables used in one form should be declared in that form Procedures, functions, or variables used by many forms may be declared in a standard module

392 Standard Module Syntax
Module ModuleName [Module Contents] End Module ModuleName is normally same as .vb file Module Contents are sub procedures and functions which can be Private - used only by procedures or functions in that module Public - can be called from anywhere in your Visual Studio project If not specified, a procedure is public

393 Adding a Standard Module
Click Add New Item on the toolbar Or Project on menu, then Add Module Add New Item dialog box appears Click on Module under Templates Change the default name if you choose Click the Add button A new empty module now appears in: Code window Solution Explorer

394 Module Level Variables
These are declared within a module But outside of any functions or sub procedures in that module If declared Dim or Private, the scope is the module (called module scope) If declared Public, the scope is the entire application (called global scope) Tutorial 7-3 demonstrates the use of a standard module in an application

395 Application with No Startup Form
Must change the startup form to Sub Main Main must be a public sub procedure It must be in a standard module When the application starts No Form will be displayed Main will be given control

396 7.3 Menus Visual Basic Allows You to Create a System of Drop-down Menus for Any Form in Your Application You Use the Menu Designer to Create a Menu System Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

397 Components of a Menu System
Each drop-down menu has a menu name Each drop-down menu has a list of actions or menu commands that can be performed Some commands may lead to a submenu

398 Components of a Menu System
Actions may be performed using a key or key combination called a shortcut key A checked menu command toggles between the checked (if on) and unchecked (if off) states A separator bar helps group similar commands

399 MenuStrip Control A MenuStrip control adds a menu to a form
Double-click on the MenuStrip icon in the Menus & Toolbars section of the Toolbox The MenuStrip control is displayed in the component tray (bottom of Design window) A MenuStrip can have many ToolStripMenuItem objects: Each represents a single menu command Name property - used by VB to identify it Text property – text displayed to the user

400 ToolStripMenuItem Object Names
Should begin with mnu Then by convention are named based on their text property and position in the menu hierarchy mnuFile mnuFileSave mnuFilePrint mnuFileExit

401 ToolStripMenuItem Text Properties
The text property holds the menu item description that is displayed to the user If an access key is assigned, that letter must be preceded with an ampersand Object Name Access Key Text Property mnuFile F &File mnuFileSave S &Save mnuFilePrint P &Print mnuFileExit X E&xit

402 Menu Designer The Menu Designer allows visual menu creation by filling in boxes with the menu text: Enter the next menu name Enter first command in the File menu

403 Shortcut Keys Keyboard based shortcuts that execute menu commands without using the menu system For example, ctrl-c to Copy to the clipboard These are set via the Shortcut property of each menu item A shortcut is displayed to the user only if the ShowShortcut property is set to true

404 Checked Menu Items Some menu items just turn a feature on or off
For example, an alarm for a clock To create a checked menu item: Set CheckOnClick property to true Set Checked property to True if feature should be on when the form is initially displayed Can test a checked menu item in code If mnuSettingsAlarm.Checked = True Then MessageBox.Show(“Wake UP!”) End If

405 Disabled Menu Items A menu item is grayed out (disabled) with the Enabled property Paste option is initially disabled and only enabled after something is cut or copied Code initially disables the Paste option Following a cut or copy, Paste is enabled mnuEditPaste.Enabled = False mnuEditPaste.Enabled = True

406 Adding Separator Bars Right-click menu item, select Insert Separator
Separator inserted above the menu item Or create a menu item with one hyphen (-) as the text property

407 Submenus When selecting a menu item in the designer, a Type Here box appears to the right Begin a submenu by setting up this menu item If a menu item has a submenu, a solid right-pointing arrow will be shown for this item

408 Inserting, Deleting, & Rearranging
To insert a new menu item within the list Right-click the item to follow the new one Select Insert then MenuItem from pop-up menu Use Menu Designer to add new menu items at the end by entering the text to appear To remove a menu item Right-click on the item Choose Delete from the pop-up menu The Menu Designer can rearrange items using a click and drag approach

409 ToolStripMenuItem Click Events
Menus and submenus require no code Commands must have a click event procedure Double click on the menu item Event procedure created in the code window Programmer supplies the code to execute Double click the menu item object mnuFileExit, then add a Me.Close command as shown below Private Sub mnuFileExit_Click(ByVal sender as System.Object, _ ByVal e as System.EventArgs) Handles mnuFileExit.Click Me.Close() End Sub Programmer supplied code Click event procedure created by VB

410 Standard Menu Items In general follow the conventions that most application menu systems use File is leftmost item with access key Alt-F File item has Exit command, access key Alt-X Help is the rightmost item Help menu has an About command Tutorial 7-4 demonstrates how to create a menu system

411 Context Menus A pop-up menu that appears on a right-click
Context menus are designed for a particular control or set of controls To set up a Context Menu: Double-click ContextMenuStrip control in the ToolBox to add it to the component tray Build menu system using Menu Designer Build Click event procedures as needed Use ContextMenuStrip property of form controls to link desired control(s) to the menu

412 The High Adventure Travel Agency Price Quote Application
7.4 The High Adventure Travel Agency Price Quote Application Build an application with multiple forms, a standard module, and a menu system Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

413 High Adventure Travel Main Form

414 High Adventure Travel Scuba Form

415 High Adventure Travel Sky Diving Form

416 High Adventure Travel Spelunking Form

417 Tony Gaddis Kip Irvine STARTING OUT WITH Visual Basic 2008
FOURTH EDITION Tony Gaddis Haywood Community College Kip Irvine Florida International University

418 8 Chapter Arrays, Timers, and More
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

419 Introduction Arrays are like groups of variables that allow you to store sets of similar data A single dimension array is useful for storing and working with a single set of data A multidimensional array can be used to store and work with multiple sets of data Array programming techniques covered Summing and averaging all the elements in an array Summing all the columns in a two-dimensional array Searching an array for a specific value Using parallel arrays

420 8.1 Arrays An Array Is Like a Group of Variables With One Name
You Store and Work Values in an Array by Using a Subscript Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

421 Array Characteristics
An array stores multiple values of same type Like a group of variables with a single name For example, the days of the week might be: a set of 7 string variables with a maximum length of 9 characters All variables within an array are called elements and must be of the same data type You access the elements in an array through a subscript

422 Subscript Characteristics
A subscript, also called an index, is a number that identifies a specific element within an array Subscript numbering works like a list box index: Subscript numbering begins at 0 1st element in an array is always subscript 0 Last element is total number of elements – 1 An array with 7 elements refers to the 1st element as subscript 0 and the last element as subscript 6

423 Declaring an Array ArrayName is the variable name of the array
Dim ArrayName(UpperSubscript) As DataType ArrayName is the variable name of the array UpperSubscript is the value of the array's highest subscript Must be a positive whole number DataType may be any Visual Basic data type VB knows an array is declared when name is followed by parentheses with number of elements

424 Array Declaration Example
Dim intHours(5) As Integer intHours(0) intHours(1) intHours(2) intHours(3) intHours(4) intHours(5) Note that 6 elements are available when an array with an upper subscript of 5 is declared Each element is an integer type

425 Default Initialization
All elements of an Integer array are initialized to zero Same initialization as an integer variable Each array element is initialized exactly the same as a simple variable of that data type A Single is initialized to zero (0.0) A String is initialized to nothing (empty string)

426 Implicit Array Sizing & Initialization
An array can be initialized when declared Example: This array is implicitly sized Upper subscript value is left blank Number of elements implied from initialization Upper subscript of 5 implied by this example This results in a 6 element array Elements are assigned the values shown Dim intNumbers() As Integer = {2, 4, 5, 7, 9, 12}

427 Named Constant as Upper Subscript
A named constant may be used as an array's highest subscript instead of a number This is a common use for named constants Highest subscript is often used multiple times If highest subscript changes, use of a named constant allows it to be changed in one place Const UPPER_SUB As Integer = 100 Dim array(UPPER_SUB) As Integer

428 Working With Array Elements
Simply include the subscript to use an array element like an ordinary variable intNumbers(2) refers to 3rd element of array intNumbers(0) = 100 intNumbers(1) = 200 intNumbers(2) = 300 intNumbers(3) = 400 intNumbers(4) = 500 intNumbers(5) = 600 decPay = intHours(3) * decRate intTallies(0) += 1 MessageBox.Show(decPay(5).ToString())

429 Arrays and Loops Loops are frequently used to process arrays
Use a loop to prompt for 10 values Use a loop to reset values in the strNames array to an empty string Dim intNbrs(9) as Integers Dim intCount As Integer For intCount = 0 To 9 intNbrs(intCount) = CInt(InputBox("Enter number")) Next intCount Dim strNames(999) as String Dim intCount As Integer For intCount = 0 To 999 strNames(intCount) = "" Next intCount

430 Array Bounds Checking Visual Basic checks each subscript value of each array reference used at run time A subscript is invalid if it is Negative Greater than the UpperSubscript declared An invalid subscript causes VB to throw a run-time exception Bounds checking is not done at design time

431 For Each Loop Array Processing
A For…Each loop is similar to a For…Next Iterates for each element in the array strName is assigned the value of the next array element at each iteration Tutorial 8-1 demonstrates array processing Dim strEmployees As String() = {"Jim", "Sally", _ "Henry", "Jean", "Renee"} Dim strName As String For Each strName In strEmployees MessageBox.Show(strName) Next strName

432 Use For Each To Sum an Array
Private intArray() as Integer = {10, 20, 90, -20) Dim intSum as Integer = 0 For Each intVal as Integer in intArray intSum = intSum + intVal Next Start of iteration 1 intVal = 10 intSum = 0 End of iteration 1 intVal = 10 intSum = 10 Start of iteration 2 intVal = 20 intSum = 10 End of iteration 2 intVal = 20 intSum = 30 Start of iteration 3 intVal = 90 intSum = 30 End of iteration 3 intVal = 90 intSum = 120 End of iteration 4 intVal = -20 intSum = 120 Start of iteration 4 intVal = -20 intSum = 100

433 Use For Each To Find Largest Value
Dim intArray() as Integer = {10, 20, 90, -20) Dim intLargest as Integer = intArray(0) For Each intVal as Integer in intArray If intVal > intLargest Then intLargest = intVal Next Start of iteration 1 intVal = 10 intLargest = 10 End of iteration 1 intVal = 10 intLargest = 10 Start of iteration 2 intVal = 20 intLargest = 10 End of iteration 2 intVal = 20 intLargest = 20 Start of iteration 3 intVal = 90 intLargest = 30 End of iteration 3 intVal = 90 intLargest = 90 End of iteration 4 intVal = -20 intLargest = 90 Start of iteration 4 intVal = -20 intLargest = 90

434 More About Array Processing
8.2 Arrays Have Many Uses & Many Programming Techniques Can Be Applied to For Example, Arrays Are Used to Total Values or Search for Data Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

435 Determining Number of Elements
Arrays have a Length property that holds the number of elements in the array Note that length is number of array elements, not the upper subscript of the array Length property always 1 greater than the upper subscript Dim intValues(25) As Integer For intCount = 0 to (intValues.Length – 1) MessageBox.Show(intValues(intCount).ToString) Next intCount

436 Total the Values in an Array
Variable to hold sum (intTotal)is initialized to zero prior to loop Iterate over all elements, adding each element to intTotal Dim intUnits(24) as Integer ‘Declare array Dim intTotal As Integer = 0 'Initialize accumulator Dim intCount as Integer ‘Declare loop counter ‘Find total of all values held in array For intCount = 0 To (intUnits.Length – 1) intTotal += intUnits(intCount) Next intCount

437 Average the Values in an Array
Similar to previous example but then divides total by number of elements to get average Dim intUnits(24) as Integer ‘Declare array Dim intTotal As Integer = 0 'Initialize accumulator Dim dblAverage as Double ‘Declare average var Dim intCount as Integer ‘Declare loop counter ‘Find total of all values held in array For intCount = 0 To (intUnits.Length – 1) intTotal += intUnits(intCount) Next intCount ‘Use floating-point division to compute average dblAverage = intTotal / intUnits.Length

438 Find Highest & Lowest Array Values
Pick first element as the highest Search rest of array for higher values If a higher value is located, save the value Use similar logic to find lowest value Dim intNumbers(24) as Integer Dim intCount as Integer Dim intHighest as Integer = intNumbers(0) For intCount = 1 To (intNumbers.Length - 1) If intNumbers(intCount) > intHighest Then intHighest = intNumbers(intCount) End If Next intCount

439 Copy Values in One Array to Another
Must copy each element one at a time Note that this cannot be done by a simple assignment intNewValues = intOldValues Causes intNewValues array to reference the same memory location as intOldValues Thus any change to intOldValues will affect intNewValues and vice versa This is because arrays are object variables For intCount = 0 To intOldValues.Length -1 intNewValues(intCount) = intOldValues(intCount) Next intCount

440 Parallel Arrays Sometimes it’s useful to store related data in two or more arrays called parallel arrays Causes the nth element of one array to be related to the nth element of another Allows related data to be accessed using the same subscript on both arrays

441 Parallel Arrays Example
Assume the following array declarations Element 1 refers to the same person with name in one array and address in the other Dim strNames(4) As String Dim strAddresses(4) As String strNames(0) strNames(1) strNames(2) strNames(3) strNames(4) Person #1 Person #2 Person #3 Person #4 Person #5 strAddresses(0) strAddresses(1) strAddresses(2) strAddresses(3) strAddresses(4)

442 Parallel Arrays Processing
Use parallel array processing to add name and address of each person to a list box Tutorial 8-2 has an example of parallel arrays Dim strNames(4) As String Dim strAddresses(4) As String For intCount = 0 To 4 lstPeople.Items.Add("Name: " & strNames(intCount) _ & " Address: " & strAddresses(intCount)) Next intCount

443 Array & List Box Parallel Processing
A list box selection used as an array index ' Initialize a List Box with names lstPeople.Items.Add("Jean James") ' Subscript 0 lstPeople.Items.Add("Kevin Smith") ' Subscript 1 lstPeople.Items.Add("Joe Harrison") ' Subscript 2 ' Initialize an Array with corresponding phone numbers phoneNumbers(0) = " " phoneNumbers(1) = " " phoneNumbers(2) = " " ' Process a selection If lstPeople.SelectedIndex > -1 And _ lstPeople.SelectedIndex < phoneNumbers.Length Then MessageBox.Show(phoneNumbers(lstPeople.SelectedIndex)) Else MessageBox.Show("That is not a valid selection.") End If

444 Searching Arrays, The Search
Find 1st instance of value 100 in array intScores intPosition gives position of this value Dim blnFound as Boolean = False Dim intCount as Integer = 0 Dim intPosition as Integer = -1 ‘ Search for a 100 in the array Do While Not blnFound And intCount < scores.Length If intScores(intCount) = 100 Then blnFound = True intPosition = intCount End If intCount += 1 Loop

445 Searching Arrays, The Result
Indicates whether the value was found If found, position is given as a test number ' Was 100 found in the array? If blnFound Then MessageBox.Show( _ "Congratulations! You made a 100 on test " & _ (intPosition + 1).ToString, "Test Results") Else "You didn’t score a 100, but keep trying!", _ "Test Results") End If

446 Sorting an Array Arrays have a Sort method
Arranges elements in ascending order (lowest to highest) Sort so intNumbers order is {1, 3, 6, 7, 12} Sort so strNames order is {Alan, Bill, Kim, Sue} Dim intNumbers() As Integer = { 7, 12, 1, 6, 3 } Array.Sort(intNumbers) Dim strNames() As String = { "Sue", "Kim", _ "Alan", "Bill" } Array.Sort(strNames)

447 Dynamically Sizing an Array
ReDim [Preserve] Arrayname(UpperSubscript) ReDim is a new keyword Used to change nbr of elements at run time If Preserve is specified, the existing contents of the array are preserved Arrayname names the existing array UpperSubscript specifies the new highest subscript value Can declare an array with no subscript and state number of elements later with ReDim

448 Resizing Example Array sngScores declared with no elements
User prompted for number of elements ReDim resizes array based on user input Dim sngScores() As Single ' Declared with no elements Dim intNumScores as Integer ' Obtain number of elements from the user intNumScores = CInt(InputBox("Enter number of test scores")) If intNumScores > 0 Then ReDim sngScores(intNumScores - 1) Else MessageBox.Show("You must enter 1 or greater.") End If

449 Procedures and Functions That Work With Arrays
8.3 Procedures and Functions That Work With Arrays You Can Pass Arrays As Arguments to Sub Procedures and Functions You Can Also Return an Array From a Function This Allows You to Write Sub Procedures and Functions That Perform General Operations With Arrays Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

450 Passing Arrays as Arguments
Array intNumbers passed to DisplaySum sub Sub computes & shows sum of array elements Can pass any integer array to DisplaySum Dim intNumbers() As Integer = { 2, 4, 7, 9, 8, 12 } DisplaySum(intNumbers) Sub DisplaySum(ByVal intArray() As Integer) Dim intTotal As Integer = 0 ' Accumulator Dim intCount As Integer ' Loop counter For intCount = 0 To (intArray.Length - 1) intTotal += intArray(intCount) Next MessageBox.Show(“Total is " & intTotal.ToString) End Sub

451 Passing Arrays: ByVal and ByRef
When passing an array ByVal Calling procedure “sees” sub procedure changes to element values Simple variables don’t work this way If sub assigns array argument to another array, no effect on array in calling procedure When passing an array ByRef If sub assigns array argument to another array, calling procedure array values affected

452 Passing Arrays Example
After ResetValues procedure executes, intNumbers array still contains { 1, 2, 3, 4, 5 } If array passed ByRef, intNumbers array will contain { 0, 0, 0, 0, 0 } after procedure runs Dim intNumbers() As Integer = { 1, 2, 3, 4, 5 } ResetValues(intNumbers) Sub ResetValues(ByVal intArray() As Integer) Dim newArray() As Integer = {0, 0, 0, 0, 0} intArray = newArray End Sub

453 An Array Returned From a Function
Return type String() indicates array of strings returned Thus the function result must be assigned to an array of strings Function GetNames() As String() ' Get four names from user ' Return them as an array of strings. Dim strNames(3) As String Dim strInput As String Dim intCount As Integer For intCount = 0 To 3 strInput = InputBox("Enter name " & _ (intCount + 1).ToString) strNames(intCount) = strInput Next Return strNames End Function

454 Multidimensional Arrays
8.4 Multidimensional Arrays You May Create Arrays With More Than Two Dimensions to Hold Complex Sets of Data Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

455 A Two Dimensional Array Picture
Thus far, arrays have been one-dimensional Arrays can also be two-dimensional A two-dimensional array looks like a spreadsheet with rows and columns Column 0 Column 1 Column 2 Column 3 Row 0 Row 1 Row 2

456 Two Dimensional Array Syntax
Dim ArrayName(UpperRow, UpperColumn) As DataType UpperRow and UpperColumn give the highest subscript for the row and column indices of the array The array on the previous slide could be: Defines three rows; 0, 1, and 2 And four columns; 0, 1, 2, and 3 Dim array(2,3) As Single

457 Two Dimensional Array Subscripts
Dim array(2,3) As Single Column 0 Column 1 Column 2 Column 3 Row 0 sngScores(0,0) sngScores(0,1) sngScores(0,2) sngScores(0,3) Row 1 sngScores(1,0) sngScores(1,1) sngScores(1,2) sngScores(1,3) Row 2 sngScores(2,0) sngScores(2,1) sngScores(2,2) sngScores(2,3)

458 Nested Loops And Two Dimensions
Must use two subscripts to indicate a single element in a two dimensional array Nested loops are often used to specify subscripts for two-dimensional array processing For example, a nested loop below is used to insert a value into every element of array scores For intRow = 0 To 2 For intCol = 0 To 3 intNum = Val(InputBox("Enter a score.")) sngScores(intRow, intCol) = intNum Next intCol Next intRow

459 Implicit Sizing and Initialization
Can be used with multi-dimensional arrays: Row 0 values Row 1 values Row 2 values Initializes array intNumbers with the following values Dim intNumbers(,) As Integer = _ { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} } Col 0 Col 1 Col 2 Row 0 1 2 3 Row 1 4 5 6 Row 2 7 8 9

460 Sum Columns, 2 Dimensional Array
Code below uses nested loops to compute sum of elements in each column of a 2 dimensional array Outer loop controls column subscript Dim intValues(,) As Integer = {{1, 2, 3, 4}, _ {5, 6, 7, 8}, _ {9, 10, 11, 12}} For intCol = 0 to 3 intTotal = 0 ‘Initialize accumulator For intRow = 0 to 2 ‘Sum rows in this column intTotal += intValues(intRow, intCol) next intRow ‘Display the sum of the column MessageBox.Show(“Column “ & intCol.ToString() _ & “ sum is “ & intTotal.ToString) Next intCol

461 Three-Dimensional Arrays & Beyond
VB allows arrays of up to 32 dimensions Can think of a 3 dimensional array as having multiple pages of two dimensional arrays Arrays beyond three dimensions are difficult to visualize But, all one needs to do is to be consistent in the use of the different indices

462 Enabled Property, Timer Control, and Splash Screens
8.5 Enabled Property, Timer Control, and Splash Screens You Disable Controls by Setting Their Enabled Property to False The Timer Control Allows Your Application to Execute a Procedure at Regular Time Intervals Splash Screens Are Forms That Appear As an Application Begins Executing Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

463 Enabled Property Most controls have an Enabled property
If this Boolean property is set to false the control is disabled meaning the control: Cannot receive the focus Cannot respond to user generated events Will appear dimmed, or grayed out Default value for this property is true May be set in code when needed as shown: btnExample.Enabled = False

464 Timer Control A Timer control generates Tick events
Double-click on Timer tool in Toolbox to add Appears in component tray Standard prefix is tmr Can perform a process at regular intervals by coding the process in a Tick event procedure Two important properties Enabled must be true to generate Tick events Interval (milliseconds) decides tick frequency Interval of 1000 causes 1 timer tick per second Tutorial 8-5 demonstrates the Timer control

465 Splash Screens A form, often with an application logo, that is displayed while an application is loading A splash screen usually: Has Topmost property set to True so it is displayed over the forms of other applications Disappears shortly by using a Timer Is modeless so the application continues to load while the splash screen is displayed Tutorial 8-6 demonstrates a splash screen

466 Anchoring and Docking Controls
8.6 Anchoring and Docking Controls Controls Have Two Properties, Anchor and Dock, That Allow You to Determine the Control’s Position on the Form When the Form Is Resized at Run Time Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

467 Anchor Property Anchor - a property of various form controls
A control anchored to a form edge keeps the same distance to the form edge Controls may be anchored to any, all, or none of the right, left, top, or bottom edges Default is to anchor to top and left edges Can just as easily anchor to bottom right If anchoring to opposing sides, control is resized when form is resized Anchoring to all 4 sides causes control to be resized proportionally to form

468 Dock Property Dock - a property of various form controls A control docked to a form edge is placed directly against the form edge Controls may be docked to Any one form edge but not more than one No edge or not docked (the default) Length or width of docked control changes to match length or width of the form edge

469 Visual Basic Provides the Tools to Generate Random Numbers
8.7 Random Numbers Visual Basic Provides the Tools to Generate Random Numbers Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

470 Initial Random Number Generation
Often used for games and simulations Must create an instance of the Random class to use random number methods and properties May supply a seed number as below so the same set of random numbers are generated every time If no seed number is supplied when instantiated: VB uses its default random number seed Causes each sequence to be unique Private rand as New Random Private rand as New Random(25)

471 Generating More Random Numbers
The Next method returns the next integer in a random number sequence Returns integer between 0 and 2,147,483,647 Repeatedly use a statement such as the following to generate additional random numbers Dim intNum as Integer = rand.Next() intNum = rand.Next()

472 Random Numbers in a Range
Can set an upper limit for the number generated by specifying the limit as an argument Following example generates a random number between 0 and 99 Lower limit of a random number is always 0 Can add or subtract to change this lower limit Following example generates a random number between -50 and +49 intNum = rand.Next(100) intNum = rand.Next(100) - 50

473 Random Numbers of Type Double
Use NextDouble method to generate random numbers of type double Returns floating point number from 0.0 to 1.0 For a random double between 0.0 and 500.0 For a random double between and 600.0 Tutorial 8-7 shows an interesting use of random numbers Dim dblNum as Double = rand.NextDouble() dblNum = rand.NextDouble() * 500 dblNum = (rand.NextDouble() * 500) + 100

474 Building the Demetris Leadership Center Application
8.8 Building the Demetris Leadership Center Application Build an application making use of arrays and a splash screen Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

475 Demetris Leadership Center Form

476 Demetris Leadership Center Form
Splash Screen Publisher of books, audiocassettes, and videos Product info stored in parallel arrays Input boxes used to prompt for sales, product, & quantity Sales displayed as shown on right

477 Tony Gaddis Kip Irvine STARTING OUT WITH Visual Basic 2008
FOURTH EDITION Tony Gaddis Haywood Community College Kip Irvine Florida International University

478 Files, Printing, and Structures
Chapter Files, Printing, and Structures 9 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

479 Introduction Saving data to sequential text files
Reading the data back into an application Using the OpenFileDialog, SaveFileDialog, ColorDialog, and FontDialog controls Using the PrintDocument control to print reports from your application Packaging units of data together into structures

480 Using Files 9.1 A File Is a Collection of Data Stored on a Computer Disk Information Can Be Saved to Files and Later Reused Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

481 The Life Span of Data Thus far, all of our data has been stored in controls and variables existing in RAM This data disappears once the program stops running If data is stored in a file on a computer disk, it can be retrieved and used at a later time

482 Three Steps in Using a File
The file must be opened If it does not yet exist, it will be created Data is read from or written to the file The program closes the file

483 Reading and Writing to a File
Data must be retrieved from disk and put in memory for an application to work with it Data is transferred from disk to memory by: Reading it from an input file Placing it in variables or control properties Data is transferred from memory to disk by: Writing it to an output file Getting it from variables or control properties Data is frequently placed in the text property of a control

484 File Types/Access Methods
Text file type Character based text Contents can be viewed by Notepad Binary file type Pure binary form Contents cannot be viewed with a text editor Access Methods Sequential access – a continuous stream of data written and read as a whole from beginning to end Random access – access in any order with data written to or read from specific places in the file Like the difference between a casette tape and a CD

485 Creating Files with StreamWriter Objects
Add Imports System.IO before class declared Makes StreamWriter classes available in code A StreamWriter object is used to create a sequential text file in the following way: Declare an object variable of type StreamWriter Call CreateText method passing the filename Method returns a StreamWriter object Object is assigned to a StreamWriter variable Variable phoneFile now defines a stream of data that can be written to phonelist.txt Dim phoneFile As StreamWriter phoneFile = File.CreateText(“phonelist.txt”)

486 Appending Text with StreamWriter
A StreamWriter object is used to append data to a sequential text file in the following way: Declare an object variable of type StreamWriter Call AppendText method passing the filename Method returns a StreamWriter object Object is assigned to a StreamWriter variable Variable phoneFile now defines a stream of data that can be added to the end of phonelist.txt Dim phoneFile As StreamWriter phoneFile = File.AppendText(“phonelist.txt”)

487 File Paths Filename can include the file path
Can be a complete file path with drive letter “C:\WordProc\memo.txt" Refer to a file in the default drive root directory "\pricelist.txt" Or include no path information at all "mytext.txt“ If no path information specified, the bin folder of the current project is used

488 Writing Data to a File The WriteLine method of a StreamWriter object actually writes data to the file ObjectVar.WriteLine(Data) Streamwriter object identified by ObjectVar The method’s Data argument consists of constants or variables with data to be written WriteLine appends an invisible newline character to the end of the data Omit argument to write a blank line to a file ObjectVar.WriteLine()

489 Writing Data to a File Example
Dim studentFile As StreamWriter studentFile = File.CreateText("StudentData.txt") studentFile.WriteLine("Jim") studentFile.WriteLine(95) studentFile.WriteLine("Karen") studentFile.WriteLine(98) studentFile.WriteLine("Bob") studentFile.WriteLine(82) studentFile.Close() The Resulting File, StudentData.txt Jim 95 Karen 98 Bob 82

490 The StreamWriter Write Method
ObjectVar.Write(Data) The Write method writes an item of data without writing a newline character Usually need to provide some sort of delineation or delimiter between data items A blank space could be used Comma is a more common delimiter

491 Closing a StreamWriter Object
Should close files when finished with them Avoids losing data Data is initially written to a buffer Writes unsaved data from the buffer to the file The Close method of a StreamWriter object clears the buffer and closes the file ObjectVar.Close() Streamwriter object identified by ObjectVar Tutorial 9-1 provides an example of an application that writes data to a file

492 Appending to a File If opening an existing file with CreateText
Existing contents are removed New text overwrites the old text If opening an existing file with AppendText Existing contents are retained New text adds on to the end of the old text If adding a new friend to friendFile, use: friendFile = File.AppendText("MyFriends.txt")

493 Appending a File Example
‘Declare an object variable Dim friendFile as StreamWriter ‘Open the file friendFile = File.AppendText(“MyFriends.txt”) ‘Write the data friendFile.WriteLine(“Bill Johnson”) friendFile.WriteLine(30) friendFile.WriteLine(“36 Oak Street”) ‘Close the file friendFile.Close() friendFile “After” Jim Weaver 30 P.O. Box 124 Mary Duncan 24 47 Elm Street Karen Warren 28 24 Love Lane Bill Johnson 36 Oak Street Jim Weaver 30 P.O. Box 124 Mary Duncan 24 47 Elm Street Karen Warren 28 24 Love Lane friendFile “Before”

494 StreamReader Objects Use StreamReader objects to read from a file
Define and open similar to StreamWriter: Sample code: Variable phoneFile now defines a stream of data that can be read from phonelist.txt Must have Imports System.IO before class declaration as was done with StreamWriter Dim ObjectVar As StreamReader ObjectVar = File.OpenText(Filename) Dim phoneFile As StreamReader phoneFile = File.OpenText(“phonelist.txt")

495 Reading Data from a File
The ReadLine method of a StreamReader object actually reads data from the file dataVar = ObjectVar.ReadLine() Streamwriter object identified by ObjectVar The result of the method, the data read from the file, is assigned to string variable dataVar Sample code: Dim custFile As StreamReader custFile = File.OpenText("customer.txt") custName = custFile.ReadLine() custName holds the data read from the file StreamReader also has a Close method

496 Determining Whether a File Exists
The File.OpenText method issues a runtime error if the file does not exist Avoid this by using the File.Exists method Format is File.Exists(filename) Returns a boolean result that can be tested: Tutorial 9-2 shows how to read text file data If System.IO.File.Exists(filename) Then ' Open the file. inputFile = System.IO.File.OpenText(filename) Else MessageBox.Show(filename & " does not exist.") End If

497 Detecting the End of a File
The Peek method tests if you’ve reached end of file (no more characters to read) Format is objectvar.Peek If no more characters, the value -1 is returned Tutorial 9-3 demonstrates the Peek method Dim scoresFile As StreamReader Dim strInput As String scoresFile = File.OpenText("Scores.txt") Do Until scoresFile.Peek = -1 strInput = scoresFile.ReadLine() lstResults.Items.Add(input) Loop scoresFile.Close()

498 Read Method Read method returns the integer code of the next character in the file Chr function converts integer code to character This loop appends one character at a time to input until no more characters are in the file Dim textFile As StreamReader Dim strInput As String = String.Empty textFile = File.OpenText("names.txt") Do While textFile.Peek <> -1 strInput &= Chr(textFile.Read) Loop textFile.Close()

499 ReadToEnd Method ReadToEnd method returns the rest of the file from the current read position to end of file Functions differently from ReadLine method ReadToEnd method ignores line delimiters The statement input = textFile.ReadToEnd reads the file contents and stores it in strInput Dim textFile As StreamReader Dim strInput As String textFile = File.OpenText("names.txt") strInput = textFile.ReadToEnd textFile.Close()

500 Write Then Read an Entire Array
Dim intValues(9) Dim outputFile as StreamWriter outputFile = File.CreateText("values.txt") For intCount = 0 To (intValues.Length – 1) outputFile.WriteLine(intValues(intCount)) Next intCount outputFile.Close() Dim inputFile as StreamReader inputFile = File.OpenText("values.txt") intValues(intCount) = CInt(inputFile.ReadLine) inputFile.Close()

501 The OpenFileDialog, SaveFileDialog, FontDialog, and ColorDialog Controls
9.2 Visual Basic Provides Dialog Controls That Equip Your Applications With Standard Windows Dialog Boxes for Operations Such As Opening Files, Saving Files, and Selecting Fonts and Colors Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

502 OpenFileDialog and SaveFileDialog
Windows has a standard method of allowing a user to choose a file to open or save These methods let users browse for a file The OpenFileDialog and SaveFileDialog controls provide this capability in VB To use the OpenFileDialog control Double click on this tool in the Toolbox Appears in component tray Use ofd as standard prefix when naming SaveFileDialog is used in a similar way

503 Displaying an Open Dialog Box
Display control with the ShowDialog method ControlName.ShowDialog() Method returns a value indicating which dialog box button the user selects, either DialogResult.OK, or DialogResult.Cancel For example: If ofdOpenfile.Showdialog() = DialogResult.OK Then MessageBox.Show(ofdOpenFile.FileName) Else MessageBox.Show(“You selected no file”) End If

504 Dialog Box Filter Property
FileDialog controls have a Filter property Limits files shown to specific file extensions Specify filter description shown to user first Then specify the filter itself Pipe symbol (|) used as a delimiter Following Filter property lets user choose: Text files (*.txt), displays all .txt files All files (*.*), displays all file extensions ofdOpenFile.Filter = "Text files (*.txt)|*.txt|" & _ "All files (*.*)|*.*"

505 Other OpenFileDialog Properties
InitialDirectory property specifies folder to use Default if not specified is current folder To set dialog box initial directory to C:\Data: ofdOpenFile.InitialDirectory = “C:\Data” Title property specifies the text on the title bar Default title is Open if not specified ofdOpenFile.Title = “Select a File to Open” Filename property returns file selected from dialog box by user, in this case to selectedFile selectedFile = ofdOpenFile.Filename

506 Open Dialog Box Example
User may choose to display .txt files or all files Files from Data folder of hard drive are shown Dialog box title shows Select a File to Open Variable inputFile holds file selected by user ' Configure the Open dialog box and display it. With ofdOpenFile .Filter = "Text files (*.txt)|*.txt|" & _ "All files (*.*)|*.*" .InitialDirectory = "C:\Data" .Title = "Select a File to Open" If .ShowDialog() = DialogResult.OK Then inputFile = System.IO.File.OpenText(.Filename) End If End With

507 Open Dialog Box Example
InitialDirectory property Title property Filter property

508 SaveFileDialog Control
SaveFileDialog uses the same methods: ShowDialog() The same properties: Filter InitialDirectory Title Filename And the same result constants: DialogResult.OK DialogResult.Cancel Tutorial 9-4 uses these controls in a text editor

509 ColorDialog Control Displays a typical Windows color dialog box
Provides users the ability to choose a color

510 ColorDialog Control To use the ColorDialog control
Double click the tool in the Toolbox Appears in component tray Use cd as standard prefix when naming The following code sets the text in control lblMessage to the color selected by the user cdColor.ShowDialog() If cdColor.ShowDialog() = DialogResult.OK Then lblMessage.ForeColor = cdColor.Color End If

511 FontDialog Control Displays a Windows font selection dialog box
Allows users to choose font, font size, etc.

512 FontDialog Control To use the FontDialog control
Double click the tool in the Toolbox Appears in component tray Use fd as standard prefix when naming The following code sets the text in control lblMessage to the font selected by the user fdFont.ShowDialog() If fdFont.ShowDialog() = DialogResult.OK Then lblMessage.Font = fdFont.Font End If

513 The PrintDocument Control
9.3 The PrintDocument Control The PrintDocument Control Allows You to Print Data to the Printer Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

514 PrintDocument Control
Allows you to send output to the printer To use the PrintDocument control Double click the tool in the Toolbox Appears in component tray Use pd as standard prefix when naming PrintDocument control has a Print method This method starts the printing process Format is: PrintDocumentControl.Print() This triggers a PrintPage event

515 PrintPage Event Handler
The code in the PrintPage event handler performs the actual printing Double click PrintDocument control in tray This creates the PrintPage event handler Insert your print code inside the event handler Basic format of event handler shown below: Private Sub pdPrint_PrintPage(ByVal sender As System.Object, _ ByVal e As System.Drawing.Printing.PrintPageEventArgs) _ Handles pdPrint.PrintPage ‘Your print code inserted here End Sub

516 DrawString Method The DrawString method is used inside the PrintPage event to: Specify data to send to the printer in string Set font, font size, and font style Determine horizontal position (HPos) of text Determine vertical position (VPos) of text Brushes.Black specifies output in black DrawString method is formatted as follows: e.Graphics.DrawString(String, _ New Font(FontName, Size, Style), _ Brushes.Black, HPos, VPos)

517 Specifying Fonts, Sizes, Styles
Fonts are specified with the string which names the font to be used "Times New Roman" “Arial" , etc. Sizes are specified with a number 10, 12, etc. Print effects are specified with provided constants FontStyle.Regular FontStyle.Bold FontStyle.Underline

518 Sample PrintPage Event Procedure
Private Sub pdPrint_PrintPage(ByVal sender As System.Object, _ ByVal e As System.Drawing.Printing.PrintPageEventArgs) _ Handles pdPrint.PrintPage Dim inputFile As StreamReader Dim intX As Integer = 10 ‘Horizontal Position Dim intY As Integer = 10 ‘Vertical Position inputFile = File.OpenText(strFilename) Do While inputFile.Peek <> -1 e.Graphics.DrawString(inputFile.ReadLine, _ New Font("Courier", 10, FontStyle.Regular), _ Brushes.Black, intX, intY) intY += ‘Increment Vert Pos Loop inputFile.Close() End Sub Tutorial 9-5 adds a print feature to Tutorial 9-4

519 Printing Column Based Reports
Business reports typically contain a: Report header printed at the top of the page Report body with the data, usually in columns Optional footer, often totalling certain columns Report header usually has column headings Monospaced font used for column reports Each character takes same amount of space This allows columns to be aligned String.Format used to align data along column boundaries

520 String.Format Example Results in the following output: 50Arg 1 6
String.Format("{0, 7}{1, -10}{2, 7}", 50, "Arg1", 6) Argument 0 Specifies the argument number Argument 1 Argument 2 Specifies field width for arg negative - left justified positive - right justified Results in the following output: 50Arg 7 spaces 10 spaces Left Justified 7 spaces

521 9.4 Structures Visual Basic Allows You to Create Your Own Data Types, in Which You May Group Multiple Data Fields Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

522 Structures vs. Arrays Arrays: Multiple fields in one array
All of the same data type Distinguished by a numerical index Structures Multiple fields in one structure Can be of differing data types Distinguished by a field name

523 Syntax for Declaring a Structure
[AccessSpecifier] Structure StructureName FieldDeclarations End Structure StructureName is a name that identifies the structure itself FieldDeclarations are the declarations of the individual fields within the structure

524 Structure Declaration Example
Following declares a structure with six fields intended to record employee payroll data Structure name is EmpPayData Structure EmpPayData Dim intEmpNumber As Integer Dim strFirstName As String Dim strLastName As String Dim sngHours As Single Dim decPayRate As Decimal Dim decGrossPay As Decimal End Structure

525 Creating and Initializing a Structure
Using the EmpPayData structure just defined Define variable deptHead of type EmpPayData deptHead contains the six fields in the structure Access each field using varName.fieldName Dim deptHead As EmpPayData deptHead.strEmpNumber = 1101 deptHead.strFirstName = "Joanne" deptHead.strLastName = "Smith" deptHead.sngHours = 40 deptHead.decPayRate = 25 deptHead.decGrossPay = CDec(deptHead.sngHours) * _ deptHead.decPayRate

526 Passing Structure Variables to Procedures and Functions
Structures can be passed to procedures and functions like any other variable The data type to use in the specification is the name of the structure Sub CalcPay(ByRef employee as EmpPaydata) ‘ This procedure accepts an EmpPayData variable ‘ as its argument. The employee’s gross pay ‘ is calculated and stored in the grossPay ‘ field. With employee .decGrossPay = .sngHours * .decPayRate End With End Sub

527 Structures Containing Arrays
Structures can contain arrays Must ReDim after declaring structure variable Structure StudentRecord Dim strName As String Dim sngTestScores() As Single End Structure Dim student As StudentRecord ReDim student.sngTestScores(4) student.strName = "Mary McBride" student.sngTestScores(0) = 89 Student.sngTestScores(1) = 92 Student.sngTestScores(2) = 84 Student.sngTestScores(3) = 96 Student.sngTestScores(4) = 91

528 Arrays Containing Structures
Can declare an array of structures Example below declares employees as an array of type EmpPayData with 10 elements Can refer to each field using the format arrayName(index).fieldName Tutorial 9-6 examines an application with a structure Dim employees(9) As EmpPayData ' Refer to the empNumber of the first employee employees(0).empNumber = 1101

529 Modifying the Demetris Leadership Center Application
9.5 Modifying the Demetris Leadership Center Application Modify this application to include the ability to save and retrieve data, use an array of structure variables instead of parallel arrays, print the sales report Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

530 Changes to Demetris Application
Replace parallel arrays with an array of structure variables Add option to print sales report Add options to save & retrieve units sold Structure ProductData Dim strName As String ' Item name Dim strDesc As String ' Descr Dim intProdNum As Integer ' Item nbr Dim decPrice As Decimal ' Unit price Dim intUnitsSold As Integer ' Units sold End Structure Const intMAX_SUB As Integer = 8 ' Array of ProductData Dim products(intMAX_SUB) As ProductData

531 Tony Gaddis Kip Irvine STARTING OUT WITH Visual Basic 2008
FOURTH EDITION Tony Gaddis Haywood Community College Kip Irvine Florida International University

532 Working With Databases
Chapter Working With Databases 10 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

533 Introduction Basic database terminology Fundamental database concepts
Use ADO .NET to access databases Display, sort, and update database data Use the DataGridView control

534 Database Management Systems
10.1 Visual Basic applications use database management systems to make large amounts of data available to programs Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

535 Visual Basic and Database Management Systems
Simple text files as shown in chapter 9 are: Fine for small amounts of data But impractical for large amounts of data Businesses must maintain huge amounts of data A database management system (DBMS) is the typical solution to the data needs of business Designed to store, retrieve, & manipulate data Visual Basic can communicate with a DBMS Tells DBMS what data to retrieve or manipulate

536 Layered Approach to Using a DBMS
Applications that work with a DBMS use a layered approach VB application is topmost layer VB sends instructions to next layer, the DBMS DBMS works directly with data Programmer need not understand the physical structure of the data Just need to know how to interact with the database

537 Visual Basic Supports Many DBMS’s
Visual Basic can interact with many DBMS’s Microsoft SQL Server Oracle DB2 MySQL Microsoft SQL Server 2008 Express used in this chapter

538 Database Concepts 10.2 A database is a collection of one or more tables, each containing data related to a particular topic Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

539 Terminology Database: a collection of interrelated tables
Table: a logical grouping of related data A category of people, places, or things For example, employees or departments Organized into rows and columns Field: an individual piece of data pertaining to an item, an employee name for instance Record: the complete data about a single item such as all information about an employee A record is a row of a table

540 Database Table Each table has a primary key
Uniquely identifies that row of the table Emp_Id is the primary key in this example Columns are also called fields or attributes Each column has a particular data type Emp_Id First_Name Last_Name Department 001234 Ignacio Fleta Accounting 002000 Christian Martin Computer Support 002122 Orville Gibson Human Resources 003400 Ben Smith 003780 Allison Chong Row (Record) Column Field

541 VB and SQL Server Data Types
VB data types must match table data types SQL Server and VB have similar data types SQL Type Usage Visual Basic Type Bit True/false values Boolean DateTime Dates and times Date, DateTime Decimal, Money Financial values Decimal Float Real-number values Double Int Integer values Integer Smallint Integers -32,768 to 32,767 Short Varchar(n) Variable length strings String Text Strings more than 8000 char String

542 Choosing Column Names Define a column for each piece of data
Allow plenty of space for text fields Avoid using spaces in column names For the members of an organization: Column Name Type Remarks Member_ID int Primary key First_Name varchar(40) Last_Name varchar(40) Phone varchar(30) varchar(50) Date_Joined smalldatetime Date only, no time values Meeings_Attended smallint Officer Yes/No True/False values

543 Issues with Redundant Data
Database design minimizes redundant data In the following employee table: ID First_Name Last_Name Department Ignacio Fleta Accounting Christian Martin Computer Support Orville Gibson Human Resources 00300 Jose Ramirez Research & Devel Ben Smith Accounting Allison Chong Computer Support Same dept name appears multiple times Requires additional storage space Causes problems if misspelled What if a department needs to be renamed?

544 Eliminating Redundant Data
Create a department table Dept_ID Dept_Name Num_Employees 1 Human Resources 10 2 Accounting 5 3 Computer Support 30 4 Research & Development 15 Reference department table in employee table ID First_Name Last_Name Dept_ID Ignacio Fleta 2 Christian Martin 3 Orville Gibson 1 Jose Ramirez 4 Ben Smith 2 Allison Chong 3

545 One-to-Many Relationships
The previous changes created a one-to-many relationship Every employee has one and only one dept Every department has many employees DeptID in department table is a primary key DeptID in employee table is a foreign key One-to-many relationship exists when primary key of one table is specified as a field of another table

546 DataGridView Control 10.3 The DataGridView Control Allows you to Display a Database Table in a Grid Which Can be Used at Runtime to Sort and Edit the Contents of the Table Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

547 Connecting VB to a Database
VB provides tools to display database tables Data binding links tables to controls on forms Controls called components establish the link A wizard guides you through the process We’ll use these data-related components: Data source – usually a database Binding source – connects data bound controls to a dataset Table adapter – uses SQL to select data Dataset – in-memory copy of data from tables

548 Connecting VB to a Database
The flow of data from database to application Data travels from data source to application Application can view/change dataset contents Changes to dataset can be written back to the data source Tutorial 10-1 demonstrates how to connect a database table to a DataGridView control

549 10.4 Data-Bound Controls Some Controls Can Be Bound to a Dataset. A Data-bound Control Can be Used to Display and Edit the Contents of a Particular Row and Column Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

550 Advantages of Data-Binding
Can bind fields in a data source to controls: Text boxes Labels List boxes Contents of data-bound controls change automatically when moving from row to row Data-bound control also allow the contents of a database field to be changed

551 Adding a New Data Source
Open the Data Sources window Click the Add New Data Source link Follow the steps in the Data Source Configuration Wizard to create a connection to the database

552 Deleting a Data Source Once created, it’s almost impossible to rename a data source Easier to delete and create a new data source than rename one A data source named Employees for example would be defined by a file named Employees.xsd To delete this data source: Select Employees.xsd file in Solution Explorer Press Delete

553 Binding Existing Dataset to DataGrid
If you wish to bind a dataset already found in the Data Sources window Locate the table in the Data Sources window Drag table to an open area of a form Creates a data grid bound to the data source Automatically adds a navigation bar to form Set Dock property to Center Docking to make the data grid fill the entire form

554 Binding Individual Fields to Controls
Use the dataset in the Data Sources window Select Details from the table drop-down list Drag table to an open area of a form Creates a separate control for each field Can also drag columns individually Text and numeric fields added as text boxes Yes/No fields added as checkboxes DateTime fields use DateTimePicker controls May wish to change some control properties Tutorial 10-3 & 10-4 demonstrate binding

555 Binding to List and Combo Boxes
List and combo boxes are frequently used to supply a list of items for a user to select from Such lists are often populated from a table Must set two list/combo box properties DataSource identifies a table within a dataset DisplayMember identifes the table column to be displayed in the list/combo box If table column dragged onto a list/combo box Visual Studio creates the required dataset, table adapter, and binding source components Tutorial 10-5 demonstrates binding to a list box

556 Adding Rows to a Database Table
A data source has a schema definition file (.xsd) An .xsd file was created in Tutorial 10-5 for the Members table DataTable created when data source added TableAdapter object created for the DataTable A TableAdapter object has an Insert method Used to add a new row to the database table Each column is an argument of the method Just provide the values for each argument MembersTableAdapter.Insert(10, “Hasegawa”, _ “Adrian”, “ ”, #5/15/2008#)

557 Identity Columns Some database tables have an identity column
Assigned a unique number by the database Occurs automatically for identity columns Thus no need to supply a value for this column Payments table uses an identity column So omit ID column value Supply Member_Id, Payment_Date, & Amount Tutorial 10-6 adds a row to the Payments table PaymentsTableAdapter.Insert(5, #5/15/2008#, 50D)

558 Reading Dataset Rows with For-Each
A For-Each statement can be used to iterate over all rows of a dataset Usually use a strongly typed dataset for this Sum Amount column of dsPayments dataset Dim row as PaymentsDataSet.PaymentsRow Dim decTotal as Decimal = 0 For Each row in Me.PaymentsDataSet.Payments.Rows decTotal += row.Amount Next Tutorial 10-7 demonstrates this technique

559 Structured Query Language (SQL)
10.5 Structured Query Language (SQL) SQL Is a Standard Language for Working With Databases Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

560 The Select Statement Select retrieves rows from one or more tables in a database Basic form of Select for a single table is Select column-list From table column-list contains column names to select from table, each separated by a comma The following Select statement retrieves the ID and Salary fields from the SalesStaff table Select ID, Salary From SalesStaff

561 Column Names Use asterisk to select all columns in a table
From SalesStaff Unlike VB names, SQL columns can have embedded spaces If so, use square brackets around column names Select [Last Name], [First Name] Better to avoid embedded spaces for this reason As operator can be used to rename columns Select Last_Name, Hire_Date As Date_Hired From Employees

562 Creating New Columns Sometimes useful to create a new column by appending existing columns together Create a Full_Name field from first and last name Select Last_Name + ‘, ‘ + First_Name as Full_Name From Members Creates a Full_Name field in the format last, first Can also be useful to create a new column by performing arithmetic operations Columns involved must be numeric Select ID, hrsWorked * hourlyRate As payAmount From Payroll Creates a payAmount column with gross pay

563 Sorting Rows with Order By Clause
SQL Select has an optional Order By clause that affects the order in which rows appear Order by Last_Name, First_Name Displays rows in order by last name, then first Sort in reverse order (high to low) using Desc Order by Last_Name DESC Order By clause appears after From clause Select First_Name, Last_Name, Date_Joined From Members Order By Last_Name, First_Name Lists all members by last name, then first

564 Selecting Rows with Where Clause
SQL Select has an optional Where clause that can be used to select (or filter) certain rows Where Last_Name = ‘Gomez’ Displays only rows where last name is Gomez Must be a defined column (in table or created) This example selects based on a created field Select Last_Name, hrsWorked * Rate As payAmount From Payroll Where payAmount > 1000 Order by Last_Name Selects those being paid more than $1,000

565 SQL Relational Operators
SQL Where uses relational operators just like a VB If Operator Meaning = equal to <> not equal to < less than <= less than or equal to > greater than >= greater than or equal to Between between two values (inclusive) Like similar to (match using wildcard) Example of Between operator: Where Hire_Date Between #1/1/1992# and #12/31/1999# Example of Like operator with % sign as wildcard: Where Last_Name Like ‘A%’

566 Compound Expressions SQL uses And, Or, and Not to create compound expressions Select all employees hired after 1/1/1990 and with a salary is greater than $40,000 Where (Hire_Date > #1/1/1990#) and (Salary > 40000) Select all employees hired after 1/1/1990 or with a salary is greater than $40,000 Where (Hire_Date > #1/1/1990#) or (Salary > 40000) Select employee names not beginning with A Where Last_Name Not Like ‘A%’

567 Modifying a Query in a Data Source
Dataset schema file contains an SQL query Created as part of schema file Named Fill, GetData() by default Right-click title bar of TableAdapter in schema Click Configure from pop-up Use Configuration Wizard to change simple queries Query Builder often used for complex queries

568 Query Builder Visual Studio tool to work with SQL queries
Consists of 4 sections or panes Diagram pane displays tables Grid pane displays query in spreadsheet form SQL pane shows actual SQL created Results pane shows data returned by query

569 Adding a Query to a DataGridView
Can add a new query as well as changing an existing one Right-click table adapter icon in component tray Select Add Query to display Search Criteria Builder Add Where clause Click New query name radio button enter a name for query Query made available from ToolStrip control

570 Karate School Management Application
10.6 Karate School Management Application Create an Application that Works With the Karate School Database Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

571 Karate School Startup Form
Menu Selections: File Exit Membership List All Find member Add new member Payments All members One member

572 Karate School Member Forms
All Members Form Add New Member Form Find Member by Last Name Form

573 Karate School Payments Forms
Payments by One Member Form Payments by All Members Form

574 Tony Gaddis Kip Irvine STARTING OUT WITH Visual Basic 2008
FOURTH EDITION Tony Gaddis Haywood Community College Kip Irvine Florida International University

575 Developing Web Applications
Chapter 11 Developing Web Applications Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

576 Introduction Programming for the World Wide Web
Creating ASP.NET applications Web server controls and web forms Using databases in ASP.NET

577 Programming for the Web
11.1 A Web Application Runs on a Web Server and Presents Its Content to the User Across a Network, via a Web Browser Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

578 Hypertext Markup Language (HTML)
HTML describes appearance of web pages A standardized formatting language It is not a programming language Formatting instructions appear as commands called tags embedded in the web page text Tags enclosed by greater than/less than signs Text following the bold tag (<b>) is shown in bold until an end bold tag (</b>) appears <b>This text is bold.</b>This text is normal. Web design editors create HTML for you

579 ASP.NET A server-side Web programming platform
Provides development tools and visual controls for web browser based applications Contains Web forms and controls, HTML, and program logic in compiled VB code VB knowledge transfers directly to ASP.NET VB code runs on the server, not the client Server runs code that creates an HTML page Client web browser receives the HTML Visual Web Developer included with text CD

580 Web Clients and Web Servers
The client-server model A server is a computer that produces data A client is a computer that uses the data Web applications use the client-server model Web browsers run on clients and request data from web servers Web sites are hosted on Web servers that produce data as requested by Web browsers

581 Uniform Resource Locator (URL)
A URL references a particular web page Begins with the protocol, Then the domain name pearsonhighered.com Can add a file path such as /vbnet/index.html to display the index.html file in the vbnet folder The URL is used as an address that uniquely identifies the web page to be retrieved

582 Displaying a Web Page Web server waits for browser connection requests
Browser connects to server requesting a URL Server translates URL into a physical file located within the server’s file system Server sends HTML for the requested file, called a Web page, back to the browser Server breaks connection after sending Web page Browser interprets HTML & renders a Web page Postback occurs if client requests Web page again

583 Web Forms ASP.NET web pages are called Web forms
Uses a file name extension of .aspx Contains text, HTML tags, and HTML controls Also contains Web server controls such as text boxes, list boxes, and buttons Web server controls are similar to VB controls Program logic for a Web form is stored in a related codebehind file with extension aspx.vb Cascading style sheet (.css) customizes the appearance of a Web form

584 ASP.NET Runs on a Web Server
Need a web server environment to run ASP Can use the ASP.NET Development Server included with Visual Studio Internet Information Services available as an option with certain versions of Microsoft Windows Requires careful security configuration Or use existing Web server if available to you Usually from an ISP or corporate server Need an account with a user ID and password

585 HTML Design & Browser Issues
HTML Designer is a tool to generate HTML and Web server controls Can do this with a text editor but it’s tedious The tool simplifies the design process Has a design view similar to VB form design Has a source view for direct editing of HTML Many different Web browser versions in use ASP.NET generates version specific HTML Usually good to try Web applications on other browsers such as Netscape and Firefox

586 Web Form Controls Toolbox contains controls for Web forms
Many such as Label and TextBox are closely related to Windows form controls used in VB Some like Hyperlink & login control are ASP only Can connect to data sources similar to VB Validation and navigation controls provided There are login controls to authenticate users Standard HTML controls are also available Buttons, checkboxes, radio buttons, text boxes But with few properties and no event handling

587 Creating ASP.NET Applications
11.2 You Use Visual Studio or Visual Web Developer Express to Develop Web Applications in Visual Basic. Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

588 Choosing Type of Web Site
File System Web Site best suited to a network Uses ASP.NET Development Server Supplied with Visual Studio Simple to use, not open to security attacks Select HTTP Web Site for a local Web server Uses Internet Information Services, or IIS Professional level, extensive security features Extensive set-up, must have admin rights FTP Web Site if existing site on remote server Need userID & password to upload application

589 Creating a Web Application
Click New Web Site from File menu Dialog box lists possible Web sites templates Our focus is the ASP.NET Web Site Choose a folder for the project If File System, can choose to use any folder on local computer or network If HTTP, application will be located on a Web site set up by IIS If FTP, must use Web site on remote computer Creates files Default.aspx & Default.aspx.vb

590 Opening an Existing Web Application
To open an existing Web application Select project from Recent Projects window If project doesn’t appear in Recent Projects click Open: Web Site… link in Recent Projects Or click Open Web Site on File menu Either of the two previous options display an Open Web Site dialog box Navigate to folder containing Web site Click Open

591 Running a Web Application
Can change default browser for your project Right-click project name in Solution Explorer Select Browse With... from shortcut menu To run your Web application Click Run Without Debugging on Debug menu Web forms allow constants called static text No label control required like a Windows form

592 Web Application Debug Mode
Must configure a project for debug capability Message box shown when first running a project in debug mode Clicking OK adds option to Web.config file that enables debugging Tutorial 11-1 demonstrates using static text, a button, and a label in ASP.NET

593 Web Server controls make Web applications interactive.
11.3 Web Server Controls Web Server controls are similar to form controls in Windows applications. Web Server controls make Web applications interactive. Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

594 Web Server Controls Overview
Make ASP.NET dynamic and interactive Work like HTML controls but far more flexible Class based with properties, methods, events Similar to Windows form controls, making it easy for VB programmers to learn Frequently used Web controls Button ImageButton LinkButton Label RadioButton RadioButtonList* TextBox CheckBoxList* ListBox CheckBox Image Calendar DropDownList * Those noted with asterisk have no Windows form equivalent

595 Web vs. Windows Controls
Web controls properties similar to those of Windows form controls including Text, Enabled, Visible, Font, ReadOnly, etc. There are some important differences Windows control Name property same as the ID property for Web controls Web controls have an AutoPostBack property Web controls lose runtime properties when the user moves away from that page Must save state to retain runtime properties

596 Processing of Web Controls
ASP.NET functions differently from HTML The Web server executes the VB code found behind the ASP.NET Web page When a browser requests an .aspx Web page Server reads/interprets Web controls on page VB statements in codebehind file executed Web page of standard HTML tags and controls built using .aspx Web controls and VB code HTML Web page sent back to browser

597 Label and TextBox Controls
Label control displays data from program Use only if label text will change at runtime If text does not change, set up as static text TextBox control holds text input by user TextMode property can be: SingleLine: permits a single line of input MultiLine: permits multiple lines of input Password: characters typed appear as asterisks Deal with browser compatibility issues using: Columns property to control TextBox width Rows property to specify entry of multiple lines

598 CheckBox Control Functions almost identically to CheckBox in Windows forms Text property sets text visible to user Evaluate Checked property at runtime to determine if control checked by user TextAlign lets you position text Tutorial 11-2 creates a simple input form

599 Event Handling in Web Forms
Events fire differently in Web forms Page_Load event fires each time a page is displayed instead of just the first time Page_Load fires before other events such as TextChanged Mouse click on a control with AutoPostBack property set to true sends form back to server Useful if server should react to a mouse click such as selecting an item from a list box Occurs automatically for Button, LinkButton, and ImageButton controls

600 HyperLink Control Provides a link to navigate to another page
Text property specifies text shown for link NavigateURL property holds destination URL Target property determines if a new browser window is opened to display the new page

601 More Web Controls ImageButton provides a clickable image
Generates a click event ImageURL property specifies path to image LinkButton behaves like a hyperlink but generates a click event RadioButtonList is a group of radio buttons Functions similar to a ListBox Has SelectedIndex & SelectedValue properties

602 ListBox Control Very similar to the Windows ListBox control
Has an Items collection Has the ListBox properties SelectedIndex, SelectedItem, and SelectedValue SelectionMode property specifies whether multiple list items may be selected SelectedIndexChanged event handling Must set AutoPostBack to true if this event should fire immediately upon a user selection If not, event fires only after another control causes form to be posted back to the server

603 CheckBoxList and DropDownList
CheckBoxList control looks like group of check boxes but works like a ListBox Has an Items collection Has the ListBox properties SelectedIndex, SelectedItem, and SelectedValue Each item has a boolean Selected property DropDownList similar to ComboBox except: Initial value of SelectedIndex always zero so the first item is always displayed Must select item from list, cannot key entry

604 Designing Web Forms 11.4 HTML Table Controls Are Used Extensively to Design a Web Application’s User Interface HTML Table Controls Provide a Convenient Way to Align the Elements of a Web Form Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

605 The HTML Table Control Essential tool in Web form design
Creates a grid of rows and columns Text and controls placed inside cells of the grid Permits text and controls to be aligned Align by right or left justifying each column Blank columns may be used for spacing Click Insert Table in Table menu to show Insert Table dialog box

606 Adjusting a Table Control
Click & drag to adjust row height or column width Insert rows or columns with Insert on Table menu Can set cell Align property to center, left, or right Adjacent cells can be merged together Drag mouse over cells to be merged Select Merge Cells from Layout menu Tutorial 11-3 aligns controls with HTML table

607 Applications with Multiple Web Pages
11.5 Applications with Multiple Web Pages Web Applications Are Not Limited to One Web Page. A Web Application May Have Multiple Web Forms for Displaying Data and Interacting with the User. Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

608 Adding New Web Forms to a Project
Two ways to add a new Web form to a project Select Add New Item from Web Site menu Right-click project in Solution Explorer and select Add New Item Either displays the Add New Item dialog box Select Web Form icon Enter name of page Be sure Place code in separate file checked

609 Moving Between Pages To allow the user to move between pages:
Specify URL of target page in NavigateURL property of a HyperLink control Use Response.Redirect method in click event of a Button, ImageButton, or LinkButton Use HyperLink button on Formatting toolbar to convert static text into a hyperlink

610 Using Response.Redirect
Allows programmer to display another Web page using code in a click event handler Transfer to Web page Page_two.aspx using: Response.Redirect(“Page_two.aspx”) Complete URL needed to display a page on another server: Response.Redirect(“ Tutorial 11-4 creates a new Web form and links the Kayak Tour form in 11-3 to it

611 11.6 Using Databases ASP.NET provides Several Web Controls for Displaying and Updating a Database from a Web Application Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

612 Web Forms Database Access
Web forms database access differs from that used for Windows forms Dataset not used DataSource control used instead Access databases use AccessDataSource control SQL Server databases use SqlDataSource control DataSource controls update database directly No Update method required as with a dataset

613 GridView Control Found in Data section of Toolbox window
An ideal way to display a complete table Serves same function as DataGridView control in Windows forms Click smart tag in upper right of grid to set properties on GridView Tasks menu

614 GridView Database Connection Setup
Data Source option in GridView Tasks menu allows database connection to be configured Copy database file to App_Data folder Select Data Source, use Database Select database file from the App_Data folder Configure Select statement for the SQL query If query requires multiple tables, must create custom SQL using Query Builder Places a DataSource control on the Web form Tutorial 11-5 configures a GridView control

615 DetailsView Control Found in Data section of Toolbox window
GridView only displays database tables DetailsView can be used to view, edit, delete, or add rows to a database table Connect to data source just as with GridView Allows you to create an effective update program without writing any code Tutorial 11-6 demonstrates how to use the DetailsView control

616 Tony Gaddis Kip Irvine STARTING OUT WITH Visual Basic 2008
FOURTH EDITION Tony Gaddis Haywood Community College Kip Irvine Florida International University

617 Classes, Exceptions, Collections, and Scrollable Controls
Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

618 Introduction Classes Abstract Data Types Objects, Properties, Methods
Exceptions Collections Object Browser Scrollable Controls

619 Classes and Objects 12.1 Classes Are Program Structures That Define Abstract Data Types and Are Used to Create Objects Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

620 Abstract Data Types An abstract data type (ADT) is a data type created by a programmer ADTs are important in computer science and object-oriented programming An abstraction is a model of something that includes only its general characteristics Dog is an abstraction Defines a general type of animal but not a specific breed, color, or size A dog is like a data type A specific dog is an instance of the data type

621 Classes A class is a program structure that defines an abstract data type Must create the class first Then can create instances of the class Class instances share common attributes VB forms and controls are classes Each control in the toolbox represents a class Placing a button on a form creates an instance, or object, of the class

622 Class Properties, Methods, & Events
Programs communicate with an object using the properties and methods of the class Class properties example: Buttons have Location, Text, and Name properties Class methods example: The Focus method functions identically for every single button Class event procedures: Each button in a form has a different click event procedure

623 Object Oriented Design
The challenge is to design classes that effectively cooperate and communicate Analyze application requirements to determine ADTs that best implement the specifications Classes are fundamental building blocks Typically represent nouns of some type A well-designed class may outlive the application Other uses for the class may be found

624 Object Oriented Design Example
Specifications: We need to keep a list of students that lets us track the courses they have completed. Each student has a transcript that contains all information about his or her completed courses. At the end of each semester, we will calculate the grade point average of each student. At times, users will search for a particular course taken by a student. Nouns from the specification above typically become classes in the program design Verbs such as calculate GPA and search become methods of those classes

625 OOD Class Characteristics
Class Attributes (properties) Operations (methods) Student LastName, FirstName, Display, Input IdNumber StudentList AllStudents, Count Add, Remove, FindStudent Course Semester, Name, Display, Input Grade,Credits Transcript CourseList, Count Display, Search, CalcGradeAvg

626 Interface and Implementation
Class interface is the portion of the class visible to the application programmer Made available by creating properties, methods, and events that are public Class implementation is the portion of the class hidden from client programs Kept hidden by designating member variables, properties, & methods as private Hiding of data and procedures inside a class is referred to as encapsulation

627 To Create a Class in Visual Basic, You Create a Class Declaration
Creating a Class 12.2 To Create a Class in Visual Basic, You Create a Class Declaration The Class Declaration Specifies the Member Variables, Properties, Methods, and Events That Belong to the Class Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

628 Class Declaration Student is the name of the class
Public Class Student MemberDeclarations End Class Student is the name of the class Examples of MemberDeclarations are presented in the following slides To create a new class: Click Add New Item button on toolbar Select Class from Add New Item dialog box Provide a name for the class and click Add Adds a new, empty class file (.vb) to project

629 Member Variables A variable declared inside a class declaration
Syntax: AccessSpecifier may be Public or Private Example: AccessSpecifer VariableName As DataType Public Class Student Public strLastName As String ‘Holds last name Public strFirstName As String ‘Holds first name Public strId As String ‘Holds ID number End Class

630 Creating an Instance of a Class
A two step process creates an instance of a class Declare a variable whose type is the class Create instance of the class with New keyword and assign the instance to the variable freshman defined here as an object variable Can accomplish both steps in one statement Dim freshman As Student freshman = New Student() Dim freshman As New Student()

631 Accessing Members Can work with Public member variables of a class object in code using this syntax: For example: If freshman references a Student class object And Student class has public member variables strFirstName, strLastName, and strID Can store values in member variables with objectVariable.memberVariable freshman.strFirstName = "Joy" freshman.strLastName = "Robinson" freshman.strId = "23G794"

632 Property Procedure A property procedure is a function that defines a property Controls access to property values Procedure has two sections: Get and Set Get code executes when value is retrieved Set code executes when value is stored Properties almost always declared Public to allow access from outside the class Set code often provides data validation logic

633 Property Procedure Syntax
Public Property PropertyName() As DataType Get Statements End Get Set(ParameterDeclaration) End Set End Property

634 Property Procedure Example
Public Class Student ' Member variables Private sngTestAvg As Single Public Property TestAverage() As Single Get Return sngTestAvg End Get Set(ByVal value As Single) If value >= 0.0 And value <= Then sngTestAvg = value Else MessageBox.Show( _ "Invalid test average.", "Error") End If End Set End Property End Class

635 Setting and Validating a Property
TestAverage property is set as shown: Passes 82.3 into value parameter of Set If in the range 0.0 to 100.0, value is stored If outside the range, message box displayed instead of value being stored Dim freshman as New Student() freshman.TestAverage = 82.3 Set(ByVal value As Single) If value >= 0.0 And value <= Then sngTestAvg = value Else MessageBox.Show( _ "Invalid test average.", "Error") End If End Set

636 Read-Only Properties Useful at times to make a property read-only
Allows access to property values but cannot change these values from outside the class Add ReadOnly keyword after access specifier This causes the propertyName to be read-only -- not settable from outside of the class Public ReadOnly Property PropertyName() As DataType Get Statements End Get End Property

637 Read-Only Property Example
' TestGrade property procedure ReadOnly Property TestGrade() As Char Get If sngTestAverage >= 90 return "A“c Else If sngTestAverage >= 80 return "B“c Else If sngTestAverage >= 70 return "C“c Else If sngTestAverage >= 60 return "D“c Else return "F“c End If End Get End Property

638 Object Removal & Garbage Collection
Memory space is consumed when objects are instantiated Objects no longer needed should be removed Set object variable to Nothing so it no longer references the object Object is a candidate for garbage collection when it is no longer referenced by any object variable The garbage collector monitors for and automatically destroys objects no longer needed freshman = Nothing

639 Going Out of Scope An object variable instantiated within a procedure is local to that procedure An object goes out of scope when Referenced only by local variables and The procedure ends Object removed once it goes out of scope An object instantiated in a procedure and assigned to a global variable is not removed Reference remains when procedure ends

640 Going Out of Scope, Example
Sub CreateStudent() Dim sophomore As Student sophomore = New Student() sophomore.FirstName = "Travis" sophomore.LastName = "Barnes" sophomore.IdNumber = "17H495" sophomore.TestAverage = 94.7 g_studentVar = sophomore End Sub With this statement, sophomore will not go out of scope. Without this statement, it will go out of scope when the procedure ends. (g_studentVar is a module-level variable.)

641 Comparing Object Variables
Multiple variables can reference the same object Can test if two variables refer to same object Must use the Is operator The = operator cannot be used to test for this Dim collegeStudent As Student Dim transferStudent As Student collegeStudent = New Student() transferStudent = collegeStudent If collegeStudent Is transferStudent Then ' Perform some action End If

642 IsNot & Nothing Object Comparisons
Use the IsNot operator to determine that two variables do not reference the same object Use the special value Nothing to determine if a variable has no object reference If collegeStudent IsNot transferStudent Then ' Perform some action End If If collegeStudent Is Nothing Then ' Perform some action End If

643 Creating an Array of Objects
Can create an entire array of object variables Declare an array whose type is a class Instantiate an object for each element ' Declare the array Dim mathStudents(9) As Student Dim i As Integer For i = 0 To 9 ' Assign each element to an object mathStudents(i) = New Student() Next i

644 Objects As Procedure Arguments
Can use object variables as arguments to a procedure or function Example: student object s as an argument Pass object variable with the procedure call Sub DisplayStudentGrade(ByVal s As Student) ' Displays a student’s grade. MessageBox.Show("The grade for " & _ s.FirstName & " " & s.LastName & _ " is " & s.TestGrade.ToString) End Sub DisplayStudentGrade(freshman)

645 Objects Passed ByVal and ByRef
If argument is declared using ByRef Values of object properties may be changed The original object variable may be assigned to a different object If argument is declared using ByVal The original object variable may not be assigned to a different object

646 Functions Can Return Objects
Example below instantiates a student object Prompts for and sets its property values Then returns the instantiated object Dim freshman As Student = GetStudent() Function GetStudent() As Student Dim s As New Student() s.FirstName = InputBox("Enter first name.") s.LastName = InputBox("Enter last name.") s.IdNumber = InputBox("Enter ID number.") s.TestAvg = CSng(InputBox("Enter test average.")) Return s End Function

647 Class Methods In addition to properties, a class may also contain Sub procedures and functions Methods are Sub procedures and functions defined in a class Typically operate on data stored in the class The following slide shows a Clear method for the Student class Method called with freshman.Clear() Method clears member data in the Student class object referenced by freshman

648 Clear Method for Student Class
Public Class Student ' Member variables Private strLastName As String 'Holds last name Private strFirstName As String 'Holds first name Private strId As String 'Holds ID number Private sngTestAvg As Single 'Holds test avg (...Property procedures omitted...) ' Clear method Public Sub Clear() strFirstName = String.Empty strLastName = String.Empty strId = String.Empty sngTestAvg = 0.0 End Sub End Class

649 Constructors A constructor is a method called automatically when an instance of the class is created Think of constructors as initialization routines Useful for initializing member variables or performing other startup operations To create a constructor, simply create a Sub procedure named New within the class Next slide shows a Student class constructor The statement freshman = New Student() Creates an instance of the Student class Executes constructor to initialize properties of the Student object referenced by freshman

650 Constructor Example Public Class Student ' Member variables
Private strLastName As String 'Holds last name Private strFirstName As String 'Holds first name Private strId As String 'Holds ID number Private sngTestAvg As Single 'Holds test avg ' Constructor Public Sub New() strFirstName = "(unknown)" strLastName = "(unknown)" strId = "(unknown)" sngTestAvg = 0.0 End Sub (The rest of this class is omitted.) End Class

651 Finalizers VB provides a class method named Finalize
Called automatically just before garbage collector removes an instance of a class Select Finalize from method name drop-down list to let Visual Basic create the following template Add your code following MyBase.Finalize() Protected Overrides Sub Finalize() MyBase.Finalize() End Sub

652 Using the Output Window
Usually shown at bottom of Visual Studio display If not appearing, click View, Other Windows, then Output to display A valuable debugging tool Messages about an application displayed here Can add your own messages to Output window using Debug.WriteLine method Causes the expression Output to appear in the Output window Insert following code in form Load event to enable Debug.WriteLine(Output) Debug.Listeners.Add(New ConsoleTraceListener())

653 Create a Class Tutorial 12-1 demonstrates code needed to create the Student class

654 A Collection Holds a Group of Items
12.3 Collections A Collection Holds a Group of Items It Automatically Expands and Shrinks in Size to Accommodate the Items Added to It and Allows Items to Be Stored With Associated Key Values, Which May Be Used in Searches Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

655 Collections A collection is similar to an array
A single unit that contains several items Can access items in a collection by numeric index A collection’s indices begin at one, not zero Collections automatically expand and shrink as items are added and removed The items stored in a collection do not have to be of the same type

656 A Collection is a Class Dim customers As Collection customers = New Collection() ' Or alternatively Dim customers As New Collection() New collections are instantiations of the Collection Class The Collection Class provides methods and properties for use with individual collections

657 Adding Items to a Collection
Object.Add(Item [, Key] [, Before] [,After]) Add is a method of the Collection class Object is a variable that refers to a collection Item can be an object, variable, or value that is added to the collection Key is a unique value optionally used to identify a member of the collection Before or After optionally specifies where a new item should be placed in the collection Default is to insert at the end of the collection

658 Uses of Before and After
Add custData with key "Smith" before the item with key "Thomas“ Add custData with key "Smith" after the item with key "Reece“ Add custData after 3rd item in collection customers.Add(custData, "Smith", "Thomas") customers.Add(custData, "Smith",, "Reece") customers.Add(custData,,,3)

659 Add Method Exceptions An exception can occur when adding to a collection so Try-Catch should be used Cannot add member with same key as another member of the collection If a key or index is specified for a Before or After, the value must exist Try customers.Add(custData, "Smith") Catch ex as ArgumentException MessageBox.Show(ex.Message) End Try

660 Accessing Item by Their Indices
Can access an item in a collection using an index value Index value can be used in two ways: Using the collection’s Item method Item is the default method so it can be omitted Get value at index 3 of names collection by: names.Item(3) –or- names(3) Object.Item(Index) Object(Index)

661 IndexOutOfRange Exception
If an invalid index is encountered, an index out of range exception will occur Should use Try-Catch to trap such messages Ctype casts collection object to Customer object Try Dim cust as Customer ‘Get collection index from user input Dim index as Integer = CInt(txtIndex.Text) ‘Locate the customer in the collection cust = CType(customers.Item(index), Customer) Catch ex as IndexOutOfRangeException MessageBox.Show(ex.Message) End Try

662 The Count Property The Count property of a collection gives the number of current items in the collection Note that, unlike an array, a collection index is not zero based First item in a collection found at index 1 Following code adds collection items to a list box Dim intX As Integer For intX = 1 To names.Count lstNames.Items.Add(names(intX).ToString()) Next intX

663 Searching for an Item by Key Value
Item method can be used to retrieve an item with a specific index If Expression is a string, it is used as a key to search for a member with a matching key If Expression is numeric, it is used as an index value for the item If no item is found (via key or index), an exception occurs Object.Item(Expression)

664 Retrieving Item Examples
Find studentCollection item with key 49812 If Option Strict on, must cast result to Student Retrieve all members by index and display LastName property in a message box Dim s as Student s = CType(studentCollection.Item(“49812”), Student) Dim intIndex as Integer Dim s as Student For intIndex = 1 to studentCollection.Count s = Ctype(studentCollection.Item(intIndex), Student) MessageBox.Show(s.LastName) Next intIndex

665 Using References Versus Copies
When an Item in a collection is a fundamental VB data type, only a copy is retrieved This code does not change the item at index 1 The Item in this collection is an object so: A reference is returned instead of a copy LastName of object in collection is changed Dim intNum as Integer intNum = CType(numbers(1), Integer) intNum = 0 Dim s as Student s = CType(studentCollection.Item("49812"), Student) s.LastName = "Griffin"

666 For Each Loop with a Collection
Can use a For Each loop to read members of a collection Eliminates the counter variable required to use a For…Next Also no need to compare to Count property Dim s As Student For Each s In studentCollection MessageBox.Show(s.LastName) Next s

667 Removing Members of a Collection
Object.Remove(Expression) Remove is a method of the Collection class Object refers to collection Member removed from Expression can be Numeric and interpreted as an index Or a string and interpreted as a key value Exception thrown if Expression not found

668 Removing Member Examples
Verify “49812” is a key value in collection, then remove member with this key value Verify index location 7 exists in collection, then remove member at this index location If studentCollection.Contains(“49812”) Then studentCollection.Remove("49812") End If Dim intIndex As Integer = 7 If intIndex > 0 and _ intIndex <= studentCollection.Count Then studentCollection.Remove(intIndex) End If

669 Working with Collections
Since a collection is an instance of a class Procedures accept collections as arguments Functions can return a collection Follow same guidelines as any class object Parallel collections work like parallel arrays Can use index to relate parallel collections just as we did with arrays Or can use key values to relate collections

670 The Student Collection Application
12.4 The Student Collection Application Create an Application that Uses a Collection of Student Objects Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

671 Student Collection Application Forms
Select student ID number from list box to see detail information for the student Click Remove Student button remove an instance of the Student class Click Add Student button to create a new instance of the Student class Add Student form

672 12.5 The Object Browser The Object Browser Is a Dialog Box That Allows You to Browse All Classes and Components Available to Your Project Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

673 Using the Object Browser
A dialog box with information about objects used in a project Allows you to examine Information about forms used in a project Classes created for the project Other components used by VB in the project Tutorial 12-3 uses the Object Browser to examine the Student Collection project

674 Object Browser, Example
Student class selected Class members shown

675 Scroll Bars and Track Bars
12.6 Scroll Bars and Track Bars The HScrollBar, VScrollBar, and TrackBar Controls Provide a Graphical Way to Adjust a Number Within a Range of Values Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

676 Visual Appearance and Usage
HScrollBar and VScrollBar look like normal scroll bars TrackBar has an arrow pointer as the slider with tick marks Scrollable controls hold integers in their Value property Position of slider corresponds to Value Move scroll bar to increase or decrease Value Right increases, left decreases horizontal bar Up increases, down decreases vertical bar

677 Scrollable Control Properties
Minimum – the bar’s lowest possible value Maximum – the bar's highest possible value Value – the bar's value at the current position LargeChange – change in the Value property with a mouse click on/near the slider SmallChange – change in the Value property for a mouse click on an arrow at the end TickFrequency - for TrackBar only, the number of units between tick marks With min=0 and max=1000, if Tick Frequency is 100, 10 tick marks are shown on the bar

678 Coding for Scrollable Controls
Any change to the position of a scroll bar generates a Scroll event Allows program to react to a shift in scroll bar Standard prefixes for these controls Horizontal scroll bar is hsb Vertical scroll bar is vsb TrackBar is tb Tutorial 12-4 demonstrates how to set up Scroll events and use of these controls

679 Introduction to Inhertance
12.7 Introduction to Inhertance Inheritance Allows a New Class to be Based on an Existing Class The New Class Inherits the Accessible Member Variables, Methods, and Properties of the Class on Which It Is Based Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

680 Why Inheritance? Inheritance allows new classes to derive their characteristics from existing classes The Student class may have several types of students such as GraduateStudent ExchangeStudent StudentEmployee These can become new classes and share all the characteristics of the Student class Each new class would then add specialized characteristics that differentiate them

681 Base and Derived Classes
The Base Class is a general-purpose class that other classes may be based on A Derived Class is based on the base class and inherits characteristics from it Can think of the base class as a parent and the derived class as a child

682 The Vehicle Class (Base Class)
Consider a Vehicle class with the following: Private variable for number of passengers Private variable for miles per gallon Public property for number of passengers (Passengers) Public property for miles per gallon (MilesPerGallon) This class holds general data about a vehicle Can create more specialized classes from the Vehicle class

683 The Truck Class (Derived Class)
Declared as: Truck class derived from Vehicle class Inherits all non-private methods, properties, and variables of Vehicle class Truck class defines two properties of its own MaxCargoWeight – holds top cargo weight FourWheelDrive – indicates if truck is 4WD Public Class Truck Inherits Vehicle ' Other new properties ' Additional methods End Class

684 Instantiating the Truck Class
Instantiated as: Values stored in MaxCargoWeight and FourWheelDrive properties Properties declared explicitly by Truck class Values also stored in MilesPerGallon and Passengers properties Properties inherited from Vehicle class Dim pickUp as New Truck() pickUp.Passengers = 2 pickUp.MilesPerGallon = 18 pickUp.MaxCargoWeight = 2000 Pickup.FourWheelDrive = True

685 Overriding Properties and Methods
Sometimes a base class property procedure or method must work differently for a derived class Can override base class method or property Must write the method or property as desired in the derived class using same name When an object of the derived class accesses the property or calls the method VB uses overridden version in derived class Version in base class is not used

686 Property Override Example
Vehicle class has no restriction on number of passengers But may wish to restrict the Truck class to two passengers at most Can override Vehicle class Passengers property by: Coding Passengers property in derived class Specify Overridable in base class property Specify Overrides in derived class property

687 Overridable Base Class Property
Overridable keyword added to base class property procedure Public Overridable Property Passengers() As Integer Get Return intPassengers End Get Set(ByVal value As Integer) intPassengers = value End Set End Property

688 Overridden Derived Class Property
Overrides keyword and new logic added to derived class property procedure Public Overrides Property Passengers() As Integer Get Return MyBase.Passengers End Get Set(ByVal value As Integer) If value >= 1 And value <= 2 Then MyBase.Passengers = value Else MessageBox.Show("Passengers must be 1 or 2", _ "Error") End If End Set End Property

689 Overriding Methods Overriding a method is similar to a property
Specify Overridable and Overrides keywords An overridable base class method An overriding derived class method Public Overridable Sub ProcedureName() Public Overridable Function ProcedureName() As DataType Public Overrides Sub ProcedureName() Public Overrides Function ProcedureName() As DataType

690 Overriding the ToString Method
Every programmer created class is derived from a built-in class named Object Object class has a method named ToString which returns a fully-qualified class name Method can be overridden to return a string representation of data stored in an object

691 ToString Override Example
Object class ToString method is Overridable Vehicle class might override the ToString method as shown below ' Overriden ToString method Public Overrides Function ToString() As String ' Return a string representation ' of a vehicle. Dim str As String str = "Passengers: " & intPassengers.ToString & _ " MPG: " & sngMPG.ToString Return str End Function

692 Base & Derived Class Constructors
A constructor (named New) may be defined for both the base class and a derived class When a new object of the derived class is created, both constructors are executed The constructor of the base class will be called first Then the constructor of the derived class will be called

693 Protected Members In addition to Private and Public, the access specifier may be Protected Protected base class members are treated as public to classes derived from this base Protected base class members are treated as private to classes not derived from this base Tutorial 12-5 provides an opportunity to work with base and derived classes


Download ppt "STARTING OUT WITH Visual Basic 2008"

Similar presentations


Ads by Google