Chapter 1 - An Introduction to Computers and Problem Solving 1.2 Windows, Folders, and Files 1.3 Program Development Cycle 1.4 Programming Tools 1 1
Chapter 1 - VB 2008 by Schneider Visual Basic 2008 BASIC originally developed at Dartmouth in the early 1960s Visual Basic created by Microsoft in 1991 Visual Basic 2008 is similar to original Visual Basic, but more powerful Chapter 1 - VB 2008 by Schneider 2 2
Chapter 1 - VB 2008 by Schneider XP versus Vista Windows XP Windows Vista Chapter 1 - VB 2008 by Schneider 3 3
Chapter 1 - VB 2008 by Schneider Mouse Actions: Hover Drag and drop Click Right-click Double-Click Pointing means moving your mouse across your desk until the mouse pointer is over the desired object on the screen. Hovering means to linger the mouse at a particular place and wait for a message or menu to appear. Clicking (sometimes people say single-clicking) means pressing and releasing the left mouse button once. Whenever a sentence begins “Click on . . . ,” you need to 1. move the mouse pointer until it is at the object you are supposed to click on and 2. press and release the left mouse button. An example of a sentence using this jargon might be “Click on the button marked Yes.” You also will see sentences that begin “Click inside the . . . .” This means to move the mouse pointer until it is inside the boundaries of the object, and then click. Double-clicking means clicking the left mouse button twice in quick succession (that is, pressing it, releasing it, pressing it, and releasing it again quickly so that Windows doesn’t think you single-clicked twice). Whenever a sentence begins “Double-click on . . . ”, you need to 1. move the mouse pointer until it is at the object you are supposed to double-click on and 2. press and release the left mouse button twice in quick succession. For example, you might be instructed to “Double-click on the little box at the far left side of your screen.” Note: An important Windows convention is that clicking selects an object so you can give Windows or the document further directions about it, but double-clicking tells Windows to perform a default operation. For example, double-clicking on a folder will open that folder. Dragging usually moves a Windows object. If you see a sentence that begins “Drag the . . . ”, you need to Chapter 1 - VB 2008 by Schneider 4 4
Chapter 1 - VB 2008 by Schneider 1.3 Program Development Cycle Performing a Task on the Computer Program Planning Chapter 1 - VB 2008 by Schneider 5 5
Chapter 1 - VB 2008 by Schneider Terminology tip A computer program may also be called: Project Application Solution Chapter 1 - VB 2008 by Schneider 6 6
Chapter 1 - VB 2008 by Schneider Program Development Cycle Software refers to a collection of instructions for the computer The computer only knows how to do what the programmer tells it to do Therefore, the programmer has to know how to solve problems Chapter 1 - VB 2008 by Schneider 7 7
Chapter 1 - VB 2008 by Schneider Performing a Task on the Computer Determine Output Identify Input Determine process necessary to turn given Input into desired Output Chapter 1 - VB 2008 by Schneider 8 8
Chapter 1 - VB 2008 by Schneider Problem-solving: approach like algebra class How fast is a car traveling if it goes 50 miles in 2 hours? Output: a number giving the speed in miles per hour Input: the distance and time the car has traveled Process: speed = distance / time Chapter 1 - VB 2008 by Schneider 9 9
Chapter 1 - VB 2008 by Schneider Pictorial representation of the problem solving process Chapter 1 - VB 2008 by Schneider 10 10
Chapter 1 - VB 2008 by Schneider Program Planning A recipe is a good example of a plan Ingredients and amounts are determined by what you want to bake Ingredients are input The way you combine them is the processing What is baked is the output Chapter 1 - VB 2008 by Schneider 11 11
Chapter 1 - VB 2008 by Schneider Program Planning Tips Always have a plan before trying to write a program The more complicated the problem, the more complex the plan must be Planning and testing before coding saves time coding Chapter 1 - VB 2008 by Schneider 12 12
Chapter 1 - VB 2008 by Schneider Program development cycle 1. Analyze: Define the problem. 2. Design: Plan the solution to the problem. 3. Choose the interface: Select the objects (text boxes, buttons, etc.). Chapter 1 - VB 2008 by Schneider 13 13
Chapter 1 - VB 2008 by Schneider Program development cycle continued 4. Code: Translate the algorithm into a programming language. 5. Test and debug: Locate and remove any errors in the program. 6. Complete the documentation: Organize all the materials that describe the program. Chapter 1 - VB 2008 by Schneider 14 14
Overview on .NET .NET is not a single programming language. It includes: Visual Basic Visual J# Visual C++ Visual C# All these languages has the same source code
Why all these programming languages in .NET? There are several programmers that are sensitive to the programming languages they love We can make programming team, with different .NET programming language. Some programming has a strong points that preferable by people
Visual Studio, .NET, and the IDE Visual Studio 2008 is a suite of products that includes the .NET Framework 3.5 and the Integrated Development Environment (IDE) you will be using The .NET Framework supports four programming languages Visual Basic, Visual C#, Visual C++, Visual J# Also COBOL, with more to come The Visual Studio IDE is your interface to .NET -- it is used to develop applications in any of the supported programming languages 1/16/2010 12:05 PM
The .NET Framework Provides a common set of services that can be used when programming in any supported language Enables you to write programs that run on any operating system on any hardware platform Main components … .NET Framework Class Library (FCL) Common Language Runtime (CLR) 1/16/2010 12:06 PM
The .NET Framework (raising the bar) 1/16/2010 12:07 PM
Introduction to The Integrated Development Environment Sometimes the IDE is referred to as Visual Studio – but it is only one part of VS The IDE is the interface between the programmer and the .NET tools he or she uses Includes design components for Console, Web, and Windows development (to name a few) Includes an editor for all .NET languages as well as XML and HTML 8/10/2008 6:34 PM
Chapter 2 - VB 2008 by Schneider Initial Visual Basic Screen Chapter 2 - VB 2008 by Schneider 21 21
Chapter 2 - VB 2008 by Schneider Chapter 2 –Visual Basic, Controls, and Events 2.1 An Introduction to Visual Basic 2.2 Visual Basic Controls 2.3 Visual Basic Events Chapter 2 - VB 2008 by Schneider 22 22
Chapter 2 - VB 2008 by Schneider 2.1 An Introduction to Visual Basic 2008 Why Windows and Why Visual Basic -(GUIs),icons,Menues,buttons - Comparing it with DOS How You Develop a Visual Basic Application The Different Versions of Visual Basic Chapter 2 - VB 2008 by Schneider 23 23
Chapter 2 - VB 2008 by Schneider Visual Basic 2008 Language used to create Windows applications. Provides a Graphical User Interface or GUI. The sequence of instructions executed in the program is controlled by events. Chapter 2 - VB 2008 by Schneider 24 24
Chapter 2 - VB 2008 by Schneider Sample Input Screen Chapter 2 - VB 2008 by Schneider 25 25
Chapter 2 - VB 2008 by Schneider How to Develop a Visual Basic Application Designing the screen of VB project, is a key element of planning VB program Design the Interface for the user. Determine which events the controls on the window should recognize. Write the event procedures for those events. Chapter 2 - VB 2008 by Schneider 26 26
Chapter 2 - VB 2008 by Schneider Different Versions of Visual Basic Version 1.0 – 1991 Version 2.0 – 1992 Version 3.0 – 1993 Version 4.0 – 1995 Version 5.0 – 1997 Version 6.0 – 1998 Visual Basic.NET – 2002 (NOT BACKWARD COMPATIBLE WITH EARLIER VERSIONS) Visual Basic 2005 – November 2005 Visual Basic 2008 – November 2007 Chapter 2 - VB 2008 by Schneider 27 27
Chapter 2 - VB 2008 by Schneider 2.2 Visual Basic Controls Invoking Visual Basic Text Box Control Button Control Label Control List Box Control Name Property Help / Fonts / Auto Hide Positioning and Aligning Controls Chapter 2 - VB 2008 by Schneider 28 28
Chapter 2 - VB 2008 by Schneider Visual Basic Start Page Point out menu bar; especially file item. Chapter 2 - VB 2008 by Schneider 29 29
Chapter 2 - VB 2008 by Schneider Start a New Project Chapter 2 - VB 2008 by Schneider 30 30
Chapter 2 - VB 2008 by Schneider New Project Dialog Box Chapter 2 - VB 2008 by Schneider 31 31
Chapter 2 - VB 2008 by Schneider Initial Visual Basic Screen Chapter 2 - VB 2008 by Schneider 32 32
Chapter 2 - VB 2008 by Schneider Toolbox Chapter 2 - VB 2008 by Schneider 33 33
Chapter 2 - VB 2008 by Schneider 3 Ways to Place a Control from the Toolbox onto the Form Window Double-click Drag and Drop Click, Point, and Drag Chapter 2 - VB 2008 by Schneider 34 34
Chapter 2 - VB 2008 by Schneider Four Controls at Design Time Text box To select a control, click on it. Sizing handles will appear when a control is selected. Chapter 2 - VB 2008 by Schneider 35 35
Chapter 2 - VB 2008 by Schneider Text Box Control Used for input and output When used for output, ReadOnly property is set to True Tasks button Sizing handles Chapter 2 - VB 2008 by Schneider 36 36
Properties Window Press F4 to display the Properties window for the selected control. Categorized view Alphabetical view Chapter 2 - VB 2008 by Schneider 37 37
Chapter 2 - VB 2008 by Schneider Properties Window Selected control Properties Settings Chapter 2 - VB 2008 by Schneider 38 38
Chapter 2 - VB 2008 by Schneider Some Often Used Properties Text Autosize Font.Name Font.Size ForeColor BackColor ReadOnly Chapter 2 - VB 2008 by Schneider 39 39
Chapter 2 - VB 2008 by Schneider Setting Properties Click on property name in left column. Enter its setting into right column by typing or selecting from options displayed via a button or ellipses. Chapter 2 - VB 2008 by Schneider 40 40
Chapter 2 - VB 2008 by Schneider Setting the Text Property Click on Text property. Type your first name The 16 white boxes at the bottom of the grid are used to create custom colors. (Explained in Appendix B.) Chapter 2 - VB 2008 by Schneider 41 41
Chapter 2 - VB 2008 by Schneider Setting the ForeColor Property Click on ForeColor. Click on button at right of settings box. Click on Custom tab to obtain display shown. Click on a color. The 16 white boxes at the bottom of the grid are used to create custom colors. (Explained in Appendix B.) Chapter 2 - VB 2008 by Schneider 42 42
Font Property Click on Font in left column. Click on ellipsis at right of settings box to obtain display shown, Make selections. Chapter 2 - VB 2008 by Schneider 43 43
Chapter 2 - VB 2008 by Schneider Button Control The caption on the button should indicate the effect of clicking on the button. Text property determines caption. To add the button, double-click on the button icon in the ToolBox, or single click and click and drag Chapter 2 - VB 2008 by Schneider 44 44
Chapter 2 - VB 2008 by Schneider Add an "access key" Chapter 2 - VB 2008 by Schneider 45 45
Chapter 2 - VB 2008 by Schneider Label Control Used to identify the contents of a text box. Text property specifies caption. By default, label automatically resizes to accommodate caption on one line. When the AutoSize property is set to False, label can be resized manually. Used primarily to obtain a multi-rowed label. Chapter 2 - VB 2008 by Schneider 46 46
Chapter 2 - VB 2008 by Schneider List Box Control Initially used to display several pieces of output. In Chapter 9 used to select from a list. Does not have a Text property Items property Chapter 2 - VB 2008 by Schneider 47 47
Chapter 2 - VB 2008 by Schneider The Name Property Used by the programmer to refer to a control in code Setting for Name property near top of Properties window. Name must begin with a letter, be less than 215 characters long, and may include numbers and letters. Use appropriate 3- or 4-character naming prefix Chapter 2 - VB 2008 by Schneider 48 48
Chapter 2 - VB 2008 by Schneider Control Name Prefixes Control Prefix Example button btn btnCompute label lbl lblAddress text box txt txtAddress list box lst lstOutput Chapter 2 - VB 2008 by Schneider 49 49
Chapter 2 - VB 2008 by Schneider Renaming the Form Initial name is Form1 The Solution Explorer window lists a file named Form1.vb. To rename the form, change the name of this file to newName.vb newName should begin with prefix frm. Chapter 2 - VB 2008 by Schneider 50 50
Chapter 2 - VB 2008 by Schneider Auto Hide Hides Toolbox when not in use Vertical push pin icon indicates auto hide is disabled. Click the push pin to make it horizontal and enable auto hide. Push pin Chapter 2 - VB 2008 by Schneider 51 51
Chapter 2 - VB 2008 by Schneider Positioning Controls Proximity line Chapter 2 - VB 2008 by Schneider 52 52
Chapter 2 - VB 2008 by Schneider Aligning Controls Snap line Chapter 2 - VB 2008 by Schneider 53 53
Chapter 2 - VB 2008 by Schneider Aligning Controls Snap line Chapter 2 - VB 2008 by Schneider 54 54
Chapter 2 - VB 2008 by Schneider Tab Order Tab index Tab index determines the order in which the control receives the focus while tabbing. Setting of tab order invoked from Edit window. The tab indices determine the order in which controls receive the focus during tabbing. Chapter 2 - VB 2008 by Schneider 55 55
Chapter 2 - VB 2008 by Schneider 2.3 Visual Basic Events An Event Procedure Walkthrough Properties and Event Procedures of the Form The Header of an Event Procedure Chapter 2 - VB 2008 by Schneider 56 56
Chapter 2 - VB 2008 by Schneider Event An event is an action, such as the user clicking on a button Usually, nothing happens in a Visual Basic program until the user does something and generates an event. What happens is determined by statements. Chapter 2 - VB 2008 by Schneider 57 57
controlName.property = setting Sample Statements txtBox.ForeColor = Color.Red txtBox.Visible = True txtBox.Text = "Hello World" General Form: controlName.property = setting Chapter 2 - VB 2008 by Schneider 58 58
Chapter 2 - VB 2008 by Schneider Sample Form txtFirst txtSecond btnRed Chapter 2 - VB 2008 by Schneider 59 59
Chapter 2 - VB 2008 by Schneider Focus When you click on a text box, a cursor appears in the text box, and you can type into the text box. Such a text box is said to have the focus. If you click on another text box, the first text box loses the focus and the second text box receives the focus. Chapter 2 - VB 2008 by Schneider 60 60
Chapter 2 - VB 2008 by Schneider Examples of Events btnShow.Click txtBox.TextChanged txtBox.Leave General Form: controlName.event Chapter 2 - VB 2008 by Schneider 61 61
Chapter 2 - VB 2008 by Schneider The three steps in creating a Visual Basic program: Create the interface; that is, generate, position, and size the objects. Set properties; that is, configure the appearance of the objects. Write the code that executes when events occur. Chapter 2 - VB 2008 by Schneider 62 62
Chapter 2 - VB 2008 by Schneider Code Editor Code Editor tab Form Designer tab Class Name box Method Name box Chapter 2 - VB 2008 by Schneider 63 63
Chapter 2 - VB 2008 by Schneider Structure of an Event Procedure Private Sub objectName_event(...) Handles objectName.event statements End Sub (...) is filled automatically with (ByVal sender As System.Object, ByVal e As System.EventArgs) Header Chapter 2 - VB 2008 by Schneider 64 64
Chapter 2 - VB 2008 by Schneider Create an Outline for an Event Procedure; i.e. header and End Sub Double-click on a control or Use the Class Name and Method Name boxes. (We nearly always use the first method.) Chapter 2 - VB 2008 by Schneider 65 65
Double Click on txtFirst Sample Form txtFirst txtSecond btnRed Double Click on txtFirst Chapter 2 - VB 2008 by Schneider 66 66
Chapter 2 - VB 2008 by Schneider Code for Walkthrough Public Class frmDemo Private Sub txtFirst_TextChanged(...) Handles txtFirst.TextChanged End Sub End Class Chapter 2 - VB 2008 by Schneider 67 67
Chapter 2 - VB 2008 by Schneider Code for Walkthrough Public Class frmDemo Private Sub txtFirst_TextChanged(...) Handles txtFirst.TextChanged txtFirst.ForeColor = Color.Blue End Sub End Class Chapter 2 - VB 2008 by Schneider 68 68
IntelliSense Automatically pops up to give the programmer help. txtFirst. Chapter 2 - VB 2008 by Schneider 69 69
Code Editor Click tab to return to Form Designer Chapter 2 - VB 2008 by Schneider 70 70
Double-click on btnRed Sample Form txtFirst txtSecond btnRed Double-click on btnRed Chapter 2 - VB 2008 by Schneider 71 71
Chapter 2 - VB 2008 by Schneider Code for Walkthrough Public Class frmDemo Private Sub txtFirst_TextChanged(...) Handles txtFirst.TextChanged txtFirst.ForeColor = Color.Blue End Sub Private Sub btnRed_Click(...) Handles btnRed.Click End Class Chapter 2 - VB 2008 by Schneider 72 72
Chapter 2 - VB 2008 by Schneider Code for Walkthrough Public Class frmDemo Private Sub txtFirst_TextChanged(...) Handles txtFirst.TextChanged txtFirst.ForeColor = Color.Blue End Sub Private Sub btnRed_Click(...) Handles btnRed.Click txtFirst.ForeColor = Color.Red End Class Chapter 2 - VB 2008 by Schneider 73 73
Chapter 2 - VB 2008 by Schneider Event Procedure txtFirst.Leave Select txtFirst from Class Name box drop-down list. Select Leave from Method Name box drop-down list. Chapter 2 - VB 2008 by Schneider 74 74
Chapter 2 - VB 2008 by Schneider Code for Walkthrough Private Sub txtFirst_Leave(...) Handles txtFirst.Leave End Sub Private Sub txtFirst_TextChanged(...) Handles txtFirst.TextChanged txtFirst.ForeColor = Color.Blue Private Sub btnRed_Click(...) Handles btnRed.Click txtFirst.ForeColor = Color.Red Chapter 2 - VB 2008 by Schneider 75 75
Chapter 2 - VB 2008 by Schneider Code for Walkthrough Private Sub txtFirst_Leave(...) Handles txtFirst.Leave txtFirst.ForeColor = Color.Black End Sub Private Sub txtFirst_TextChanged(...) Handles txtFirst.TextChanged txtFirst.ForeColor = Color.Blue Private Sub btnRed_Click(...) Handles btnRed.Click txtFirst.ForeColor = Color.Red Chapter 2 - VB 2008 by Schneider 76 76
Private Sub Button_Press(…) Handles btnRed.Click Header of Event Procedure Private Sub btnRed_Click(…) Handles btnRed.Click Identifies event Name, can be changed. Private Sub Button_Press(…) Handles btnRed.Click Chapter 2 - VB 2008 by Schneider 77 77
txtFirst.ForeColor = Color.Red Handling Multiple Events Event procedure can be invoked by two events. Private Sub Happening(...) Handles btnRed.Click,txtSecond.Leave txtFirst.ForeColor = Color.Red End Sub Chapter 2 - VB 2008 by Schneider 78 78
Chapter 2 - VB 2008 by Schneider Altering Properties of the Form The following won't work: frmDemo.Text = "Demonstration" The form is referred to by the keyword Me. Me.Text = "Demonstration" Chapter 2 - VB 2008 by Schneider 79 79
Chapter 2 - VB 2008 by Schneider Text File Holds data to be processed by programs. Can be created, viewed, and managed by the Visual Basic IDE. Create: Use “Add New Item” input dialog box. View: Click on filename in Solution Explorer. Manage: Use Solution Explorer like Windows Explorer. Chapter 2 - VB 2008 by Schneider 80 80
Chapter 2 - VB 2008 by Schneider Sample Text File Mike Jones 9.35 35 John Smith 10.75 33 PAYROLL.TXT Chapter 2 - VB 2008 by Schneider 81 81
Chapter 2 - VB 2008 by Schneider Sample Text File name Mike Jones 9.35 35 John Smith 10.75 33 hourly wage hours worked PAYROLL.TXT Chapter 2 - VB 2008 by Schneider 82 82
Chapter 2 - VB 2008 by Schneider Our Text File Convention PAYROLL.TXT uses one item of data per line. That will be our convention in this book. Chapter 2 - VB 2008 by Schneider 83 83
Chapter 2 - VB 2008 by Schneider Use Property Window to View all Possible Events for a Control Events button Chapter 2 - VB 2008 by Schneider 84 84
Chapter 2 - VB 2008 by Schneider Open and Run an Existing Program Click on Open Project in the File menu. Navigate to the program’s folder. Click on the program’s folder. Double-click on the file with extension .sln. In the Solution Explorer double-click on the file with extension .vb. (The Form Designer will appear.) Press F5 to run the program. Chapter 2 - VB 2008 by Schneider 85 85
Chapter 3 - VB 2008 by Schneider Chapter 3 – Variables, Input, and Output 3.1 Numbers 3.2 Strings 3.3 Input and Output Chapter 3 - VB 2008 by Schneider 86 86
Chapter 3 - VB 2008 by Schneider 3.1 Numbers Arithmetic Operations Variables Incrementing the Value of a Variable Built-In Functions: Math.Sqrt Int Math.Round Chapter 3 - VB 2008 by Schneider 87 87
Chapter 3 - VB 2008 by Schneider Numbers continued The Integer Data Type Multiple Declarations Parentheses Three Types of Errors The Error List Window Chapter 3 - VB 2008 by Schneider 88 88
Chapter 3 - VB 2008 by Schneider Arithmetic Operations Numbers are called numeric literals Five arithmetic operations in Visual Basic + addition - subtraction * multiplication / division ^ exponentiation Chapter 3 - VB 2008 by Schneider 89 89
Chapter 3 - VB 2008 by Schneider Numeric Expressions 2 + 3 3 * (4 + 5) 2 ^ 3 Chapter 3 - VB 2008 by Schneider 90 90
Chapter 3 - VB 2008 by Schneider Displaying Numbers Let n be a number or a numeric expression. The statement lstBox.Items.Add(n) displays the value of n in the list box. Chapter 3 - VB 2008 by Schneider 91 91
Chapter 3 - VB 2008 by Schneider Example 1: Form Chapter 3 - VB 2008 by Schneider 92 92
Chapter 3 - VB 2008 by Schneider Example 1: Code and Output Private Sub btnCompute_Click (...) Handles btnCompute.Click lstResults.Items.Add(5) lstResults.Items.Add(2 * 3) lstResults.Items.Add((2 ^ 3) – 1) End Sub Output 5 in list 6 box 7 Chapter 3 - VB 2008 by Schneider 93 93
A numeric variable is a name to which a number can be assigned. Examples: speed distance interestRate balance Chapter 3 - VB 2008 by Schneider 94 94
Chapter 3 - VB 2008 by Schneider Variables Declaration: Dim speed As Double Variable name Data type Assignment: speed = 50 Chapter 3 - VB 2008 by Schneider 95 95
Chapter 3 - VB 2008 by Schneider Initialization Numeric variables are automatically initialized to 0: Dim varName As Double To specify a nonzero initial value Dim varName As Double = 50 declares a variable named varName to be of type Double. Actually, the Dim statement causes the computer to set aside a location in memory with the name varName. Since varName is a numeric variable, the Dim statement also places the number zero in that memory location. (We say that zero is the initial value or default value of the variable.) Chapter 3 - VB 2008 by Schneider 96 96
Chapter 3 - VB 2008 by Schneider Numeric Expressions Numeric variables can be used in numeric expressions. Dim balance As Double = 1000 lstBox.Items.Add(1.05 * balance) Output: 1050 declares a variable named varName to be of type Double. Actually, the Dim statement causes the computer to set aside a location in memory with the name varName. Since varName is a numeric variable, the Dim statement also places the number zero in that memory location. (We say that zero is the initial value or default value of the variable.) Chapter 3 - VB 2008 by Schneider 97 97
Chapter 3 - VB 2008 by Schneider Assignment Statement Dim numVar1 As Double = 5 Dim numVar2 As Double = 4 numVar1 = 3 * numVar2 lstBox.Items.Add(numVar1) Output: 12 declares a variable named varName to be of type Double. Actually, the Dim statement causes the computer to set aside a location in memory with the name varName. Since varName is a numeric variable, the Dim statement also places the number zero in that memory location. (We say that zero is the initial value or default value of the variable.) Chapter 3 - VB 2008 by Schneider 98 98
Chapter 3 - VB 2008 by Schneider Incrementing To add 1 to the numeric variable var var = var + 1 Or as a shortcut var += 1 Or as a generalization var += numeric expression Chapter 3 - VB 2008 by Schneider 99 99
Chapter 3 - VB 2008 by Schneider Built-in Functions Functions return a value Math.Sqrt(9) returns 3 Math.Sqrt(0) returns 0 Int(9.7) returns 9 Int(2.3) returns 2 Math.Round(2.7) is 3 Math.Round(2.5) is 2 Chapter 3 - VB 2008 by Schneider 100 100
Chapter 3 - VB 2008 by Schneider Integer Data Type Variables of type Double can be assigned both whole numbers and numbers with decimals. The statement Dim varName As Integer declares a numeric variable that can only be assigned whole number values between about -2 billion and 2 billion. Chapter 3 - VB 2008 by Schneider 101 101
Chapter 3 - VB 2008 by Schneider Multiple Declarations Dim a, b As Double Two other types of multiple-declaration statements are Dim a As Double, b As Integer Dim c As Double = 2, b As Integer = 5 Chapter 3 - VB 2008 by Schneider 102 102
Chapter 3 - VB 2008 by Schneider Parentheses Parentheses should be used liberally in numeric expressions. In the absence of parentheses, the operations are carried out in the following order: ^, * and /, + and -. Chapter 3 - VB 2008 by Schneider 103 103
Chapter 3 - VB 2008 by Schneider Three Types of Errors Syntax error Run-time error Logic error Chapter 3 - VB 2008 by Schneider 104 104
Chapter 3 - VB 2008 by Schneider Some Types of Syntax Errors Misspellings lstBox.Itms.Add(3) Omissions lstBox.Items.Add(2 + ) Incorrect punctuation Dim m; n As Integer Chapter 3 - VB 2008 by Schneider 105 105
Chapter 3 - VB 2008 by Schneider A Type of Run-time Error Overflow error Dim numVar As Integer = 1000000 numVar = numVar * numVar Chapter 3 - VB 2008 by Schneider 106 106
Chapter 3 - VB 2008 by Schneider A Logical Error Dim average As Double Dim m As Double = 5 Dim n As Double = 10 average = m + n / 2 Value of average will be 10. Should be 7.5. Chapter 3 - VB 2008 by Schneider 107 107
Chapter 3 - VB 2008 by Schneider Error List Window Dim m; n As Double lstResults.Items.Add(5 lstResults.Items.Add(a) Chapter 3 - VB 2008 by Schneider 108 108
Chapter 3 - VB 2008 by Schneider 3.2 Strings Variables and Strings Option Explicit and Option Strict Using Text Boxes for Input and Output Concatenation String Properties and Methods: Length ToUpper Trim ToLower IndexOf Substring Chapter 3 - VB 2008 by Schneider 109 109
Chapter 3 - VB 2008 by Schneider Strings continued Auto Correction The Empty String Initial Value of a String Widening and Narrowing Internal Documentation Line-Continuation Character Scope of a Variable Chapter 3 - VB 2008 by Schneider 110 110
Chapter 3 - VB 2008 by Schneider String Literal A string literal is a sequence of characters surrounded by quotation marks. Examples: "hello" "123-45-6789" "#ab cde?" Chapter 3 - VB 2008 by Schneider 111 111
Chapter 3 - VB 2008 by Schneider String Variable A string variable is a name to which a string value can be assigned. Examples: country ssn word firstName Chapter 3 - VB 2008 by Schneider 112 112
Chapter 3 - VB 2008 by Schneider String Variable Declaration: Dim firstName As String Data type Variable name Assignment: firstName = "Fred" Chapter 3 - VB 2008 by Schneider 113 113
Dim firstName As String = "Fred" String Variable You can declare a string variable and assign it a value at the same time. Dim firstName As String = "Fred" Chapter 3 - VB 2008 by Schneider 114 114
Chapter 3 - VB 2008 by Schneider Add Method Let str be a string literal or variable. Then, lstBox.Items.Add(str) displays the value of str in the list box. Chapter 3 - VB 2008 by Schneider 115 115
Chapter 3 - VB 2008 by Schneider String Variable You can assign the value of one string variable to another. Dim strVar1 As String = "Hello" Dim strVar2 As String = "Goodbye" strVar2 = strVar1 lstOutput.Items.Add(strVar2) Output: Hello Chapter 3 - VB 2008 by Schneider 116 116
Chapter 3 - VB 2008 by Schneider Variables and Strings Private Sub btnDisplay_Click(...) Handles btnDisplay.Click Dim president As String president = "George Washington" lstOutput.Items.Add("president") lstOutput.Items.Add(president) End Sub Output: president George Washington Chapter 3 - VB 2008 by Schneider 117 117
Chapter 3 - VB 2008 by Schneider Option Strict Visual Basic allows numeric variables to be assigned strings and vice versa, a poor programming practice. To prevent such assignments, set Option Strict to On in the Options dialog box. Chapter 3 - VB 2008 by Schneider 118 118
Chapter 3 - VB 2008 by Schneider Option Strict -continued Select Options from the Tools menu In left pane, expand Projects and Solution Select VB Defaults Set Option Strict to On Chapter 3 - VB 2008 by Schneider 119 119
Chapter 3 - VB 2008 by Schneider Using Text Boxes for Input and Output The contents of a text box is always a string Input example strVar = txtBox.Text Output example txtBox.Text = strVar Chapter 3 - VB 2008 by Schneider 120 120
Data Conversion Because the contents of a text box is always a string, sometimes you must convert the input or output. dblVar = CDbl(txtBox.Text) txtBox.Text = CStr(numVar) Converts a String to a Double Converts a number to a string Chapter 3 - VB 2008 by Schneider 121 121
Chapter 3 - VB 2008 by Schneider Auto Correction Chapter 3 - VB 2008 by Schneider 122 122
Chapter 3 - VB 2008 by Schneider With Option Strict On Dim dblVar As Double, intVar As Integer Dim strVar As String Not Valid: Replace with: intVar = dblVar intVar = CInt(dblVar) dblVar = strVar dblVar = CDbl(strVar) strVar = intVar strVar = CStr(intVar) Chapter 3 - VB 2008 by Schneider 123 123
Chapter 3 - VB 2008 by Schneider Concatenation Combining two strings to make a new string quote1 = "We'll always " quote2 = "have Paris." quote = quote1 & quote2 txtOutput.Text = quote & " - Humphrey Bogart" Displays We'll always have Paris. - Humphrey Bogart Chapter 3 - VB 2008 by Schneider 124 124
Chapter 3 - VB 2008 by Schneider Appending To append str to the string variable var var = var & str Or as a shortcut var &= str Chapter 3 - VB 2008 by Schneider 125 125
Chapter 3 - VB 2008 by Schneider Appending Example Dim var As String = "Good" var &= "bye" txtBox.Text = var OUTPUT: Goodbye Can you concatenate a string with a number and concatenate numbers? yes, the result will be string Chapter 3 - VB 2008 by Schneider 126 126
Chapter 3 - VB 2008 by Schneider String Properties and Methods "Visual".Length is 6. "Visual".ToUpper is VISUAL. "123 Hike".Length is 8. "123 Hike".ToLower is 123 hike. "a" & " bcd ".Trim & "efg" is abcdefg. Chapter 3 - VB 2008 by Schneider 127 127
Chapter 3 - VB 2008 by Schneider Positions in a String Positions of characters in a string are numbered 0, 1, 2, …. Consider the string “Visual Basic”. Position 0: V Position 1: i Position 7: B Substring “al” begins at position 4 Chapter 3 - VB 2008 by Schneider 128 128
Chapter 3 - VB 2008 by Schneider Substring Method Let str be a string. str.Substring(m, n) is the substring of length n, beginning at position m in str. “Visual Basic”.Substring(2, 3) is “sua” “Visual Basic”.Substring(0, 1) is “V” Chapter 3 - VB 2008 by Schneider 129 129
Chapter 3 - VB 2008 by Schneider IndexOf Method Let str1 and str2 be strings. str1.IndexOf(str2) is the position of the first occurrence of str2 in str1. (Note: Has value -1 if str2 is not a substring of str1.) "Visual Basic".IndexOf("is") is 1. "Visual Basic".IndexOf("si") is 9. "Visual Basic".IndexOf("ab") is -1. "Mississippi".IndexOf(“ss“,3) is 5. Chapter 3 - VB 2008 by Schneider 130 130
Chapter 3 - VB 2008 by Schneider The Empty String The string "", which contains no characters, is called the empty string or the zero-length string. The statement lstBox.Items.Add("") skips a line in the list box. The contents of a text box can be cleared with either the statement txtBox.Clear() or the statement txtBox.Text = "" Chapter 3 - VB 2008 by Schneider 131 131
Chapter 3 - VB 2008 by Schneider Initial Value of a String By default the initial value is Nothing Strings can be given a different initial value as follows: Dim name As String = "Fred" Chapter 3 - VB 2008 by Schneider 132 132
Chapter 3 - VB 2008 by Schneider Widening and Narrowing Widening: assigning an Integer value to a Double variable Widening always works. (Every Integer is a Double.) No conversion function needed. Narrowing: assigning a Double value to an Integer variable Narrowing might not work. (Not every Double is an Integer.) Narrowing requires Cint. Strings can be given a different initial value as follows Chapter 3 - VB 2008 by Schneider 133 133
Chapter 3 - VB 2008 by Schneider Comments Private Sub btnCompute_Click (...) Handles btnCompute.Click 'Calculate the balance in an account Dim rate As Double 'Annual rate of interest Dim curBalance As Double 'Current balance Chapter 3 - VB 2008 by Schneider 134 134
Chapter 3 - VB 2008 by Schneider Internal Documentation Other people can easily understand the program. You can understand the program when you read it later. Long programs are easier to read because the purposes of individual pieces can be determined at a glance. Chapter 3 - VB 2008 by Schneider 135 135
Chapter 3 - VB 2008 by Schneider Line-Continuation Character A long line of code can be continued on another line by using an underscore (_) preceded by a space msg = "I'm going to make " & _ "him an offer he can't refuse." Chapter 3 - VB 2008 by Schneider 136 136
Chapter 6 - VB 2008 by Schneider Scope The scope of a variable is the portion of the program that can refer to it. Variables declared inside an event procedure are said to have local scope and are only available in the event procedure in which they are declared. Chapter 6 - VB 2008 by Schneider 137 137
Chapter 6 - VB 2008 by Schneider Scope Variables declared outside an event procedure are said to have class-level scope and are available to every event procedure. Usually declared after Public Class formName (Declarations section of Code Editor.) Chapter 6 - VB 2008 by Schneider 138 138
Chapter 3 - VB 2008 by Schneider Automatic Colorization Comments – green String literals – maroon Keywords – blue Note: Keywords are words such as Sub, Handles, Private, With, and End that have special meaning in Visual Basic. They cannot be used as variable names. Chapter 3 - VB 2008 by Schneider 139 139
Chapter 3 - VB 2008 by Schneider 3.3 Input and Output Formatting Output with Format Functions Formatting Output with Zones Reading Data from Files Getting Input from an Input Dialog Box Using a Message Dialog Box for Output Using a Masked Text Box for Input Chapter 3 - VB 2008 by Schneider 140 140
Chapter 3 - VB 2008 by Schneider Formatting Output with Format Functions Function String Value FormatNumber(12345.628, 1) 12,345.6 FormatCurrency(12345.628, 2) $12,345.63 FormatPercent(0.183, 0) 18% FormatPercent(0.185, 2) 18.50% Chapter 3 - VB 2008 by Schneider 141 141
Chapter 3 - VB 2008 by Schneider Formatting Output with Zones Use a fixed-width font such as Courier New Divide the characters into zones with a format string. Dim fmtStr As String = "{0, 15}{1, 10}{2, 8}" lstOutput.Items.Add(String.Format(fmtStr, _ data0, data1, data2)) Chapter 3 - VB 2008 by Schneider 142 142
Chapter 3 - VB 2008 by Schneider Formatting Output with Zones Example Dim fmtStr As String = "{0, 15}{1, 10}" lstOutput.Items.Add(String.Format(fmtStr, _ “Name”, “Major”)) “Mohammed”, “MIS”)) “Ahmed”, “CIS”)) Chapter 3 - VB 2008 by Schneider 143 143
Chapter 3 - VB 2008 by Schneider Formatting Output with Zones Dim fmtStr As String = "{0, -15}{1, 10}{2, 8}" lstOutput.Items.Add(String.Format(fmtStr, _ data0, data1, data2)) Here, 15 was preceded by a minus sign. This produces left justification in 0th zone. There will be right justification in the other two zones. Chapter 3 - VB 2008 by Schneider 144 144
Dim fmtStr As String = "{0,15:N1}{1,10:C2}{2,8:P0}" Zone Formatting Symbols Symbols: N, C, and P Effect on zone :Nr FormatNumber(data, r) :Cr FormatCurrency(data, r) :Pr FormatPercent(data, r) Dim fmtStr As String = "{0,15:N1}{1,10:C2}{2,8:P0}" Chapter 3 - VB 2008 by Schneider 145 145
Chapter 3 - VB 2008 by Schneider Reading Data from Files Data can be stored in text files and accessed with a StreamReader object. We assume that the text files have one piece of data per line. Chapter 3 - VB 2008 by Schneider 146 146
Chapter 3 - VB 2008 by Schneider Sample File: PAYROLL.TXT Mike Jones 9.35 35 John Smith 10.75 33 Name Hourly wage Number of hours worked Chapter 3 - VB 2008 by Schneider 147 147
Chapter 3 - VB 2008 by Schneider Steps to Use StreamReader Execute a statement of the form Dim readerVar As IO.StreamReader = _ IO.File.OpenText(filespec) or the pair of statements Dim readerVar As IO.StreamReader readerVar = IO.File.OpenText(filespec) 1. Execute a statement of the form Dim readerVar As IO.StreamReader A StreamReader is an object from the Input/Output class that can read a stream of characters coming from a disk or coming over the Internet. The Dim statement declares the variable readerVar to be of type StreamReader. 2. Execute a statement of the form readerVar = IO.File.OpenText(filespec) where filespec identifies the file to be read. This statement establishes a communi-cations link between the computer and the disk drive for reading data from the disk. Data then can be input from the specified file and assigned to variables in the pro-gram. This assignment statement is said to “open the file for input.” Just as with other variables, the declaration and assignment statements in Steps 2 and 3 can be combined into the single statement Dim readerVar As IO.StreamReader = IO.File.OpenText(filespec) 3. Read items of data in order, one at a time, from the file with the ReadLine method. Each datum is retrieved as a string. A statement of the form strVar = readerVar.ReadLine causes the program to look in the file for the next unread line of data and assign it to the variable strVar. The data can be assigned to a numeric variable if it is first converted to a numeric type with a statement such as numVar = CDbl(readerVar.ReadLine) Note: If all the data in a file have been read by ReadLine statements and another item is requested by a ReadLine statement, the item retrieved will have the value Nothing. 4. After the desired items have been read from the file, terminate the communications link set in Step 3 with the statement readerVar.Close() Chapter 3 - VB 2008 by Schneider 148 148
Chapter 3 - VB 2008 by Schneider Steps to Use StreamReader Read items of data in order, one at a time, from the file with the ReadLine method. strVar = readerVar.ReadLine After the desired items have been read from the file, terminate the communications link readerVar.Close() 1. Execute a statement of the form Dim readerVar As IO.StreamReader A StreamReader is an object from the Input/Output class that can read a stream of characters coming from a disk or coming over the Internet. The Dim statement declares the variable readerVar to be of type StreamReader. 2. Execute a statement of the form readerVar = IO.File.OpenText(filespec) where filespec identifies the file to be read. This statement establishes a communi-cations link between the computer and the disk drive for reading data from the disk. Data then can be input from the specified file and assigned to variables in the pro-gram. This assignment statement is said to “open the file for input.” Just as with other variables, the declaration and assignment statements in Steps 2 and 3 can be combined into the single statement Dim readerVar As IO.StreamReader = IO.File.OpenText(filespec) 3. Read items of data in order, one at a time, from the file with the ReadLine method. Each datum is retrieved as a string. A statement of the form strVar = readerVar.ReadLine causes the program to look in the file for the next unread line of data and assign it to the variable strVar. The data can be assigned to a numeric variable if it is first converted to a numeric type with a statement such as numVar = CDbl(readerVar.ReadLine) Note: If all the data in a file have been read by ReadLine statements and another item is requested by a ReadLine statement, the item retrieved will have the value Nothing. 4. After the desired items have been read from the file, terminate the communications link set in Step 3 with the statement readerVar.Close() Chapter 3 - VB 2008 by Schneider 149 149
Example using StreamReader Dim name As String Dim wage, hours As Double Dim sr As IO.StreamReader = _ IO.File.OpenText("PAYROLL.TXT") name = sr.ReadLine wage = CDbl(sr.ReadLine) hours = CDbl(sr.ReadLine) lstBox.Items.Add(name & ": " & wage * hours) OUTPUT: Mike Jones: 327.25 Program’s bin folder/debug subfolder 1. Execute a statement of the form Dim readerVar As IO.StreamReader A StreamReader is an object from the Input/Output class that can read a stream of characters coming from a disk or coming over the Internet. The Dim statement declares the variable readerVar to be of type StreamReader. 2. Execute a statement of the form readerVar = IO.File.OpenText(filespec) where filespec identifies the file to be read. This statement establishes a communi-cations link between the computer and the disk drive for reading data from the disk. Data then can be input from the specified file and assigned to variables in the pro-gram. This assignment statement is said to “open the file for input.” Just as with other variables, the declaration and assignment statements in Steps 2 and 3 can be combined into the single statement Dim readerVar As IO.StreamReader = IO.File.OpenText(filespec) 3. Read items of data in order, one at a time, from the file with the ReadLine method. Each datum is retrieved as a string. A statement of the form strVar = readerVar.ReadLine causes the program to look in the file for the next unread line of data and assign it to the variable strVar. The data can be assigned to a numeric variable if it is first converted to a numeric type with a statement such as numVar = CDbl(readerVar.ReadLine) Note: If all the data in a file have been read by ReadLine statements and another item is requested by a ReadLine statement, the item retrieved will have the value Nothing. 4. After the desired items have been read from the file, terminate the communications link set in Step 3 with the statement readerVar.Close() Chapter 3 - VB 2008 by Schneider 150 150
Chapter 3 - VB 2008 by Schneider Comment on Example Consider lstBox.Items.Add(name & ": " & wage * hours) The ampersand automatically converted wage * hours into a string before concatenating. We didn’t have to convert wage * hours with CStr. 1. Execute a statement of the form Dim readerVar As IO.StreamReader A StreamReader is an object from the Input/Output class that can read a stream of characters coming from a disk or coming over the Internet. The Dim statement declares the variable readerVar to be of type StreamReader. 2. Execute a statement of the form readerVar = IO.File.OpenText(filespec) where filespec identifies the file to be read. This statement establishes a communi-cations link between the computer and the disk drive for reading data from the disk. Data then can be input from the specified file and assigned to variables in the pro-gram. This assignment statement is said to “open the file for input.” Just as with other variables, the declaration and assignment statements in Steps 2 and 3 can be combined into the single statement Dim readerVar As IO.StreamReader = IO.File.OpenText(filespec) 3. Read items of data in order, one at a time, from the file with the ReadLine method. Each datum is retrieved as a string. A statement of the form strVar = readerVar.ReadLine causes the program to look in the file for the next unread line of data and assign it to the variable strVar. The data can be assigned to a numeric variable if it is first converted to a numeric type with a statement such as numVar = CDbl(readerVar.ReadLine) Note: If all the data in a file have been read by ReadLine statements and another item is requested by a ReadLine statement, the item retrieved will have the value Nothing. 4. After the desired items have been read from the file, terminate the communications link set in Step 3 with the statement readerVar.Close() Chapter 3 - VB 2008 by Schneider 151 151
Chapter 8 - VB 2008 by Schneider Chapter 8 – Sequential Files 8.1 Sequential Files 8.2 Using Sequential Files Chapter 8 - VB 2008 by Schneider 152 152
Chapter 8 - VB 2008 by Schneider Section 8.1 – Sequential Files Creating a Sequential File Adding Items to a Sequential File Structured Exception Handling Chapter 8 - VB 2008 by Schneider 153 153
Chapter 8 - VB 2008 by Schneider Sequential Files A sequential file consists of data stored in a text file on disk. May be created with the Visual Basic IDE May also be created programmatically from Visual Basic Chapter 8 - VB 2008 by Schneider 154 154
Chapter 8 - VB 2008 by Schneider Creating a Sequential File Choose a filename – may contain up to 215 characters Select the path for the folder to contain this file Execute a statement like the following: Dim sw As IO.StreamWriter = IO.File.CreateText(filespec) (Opens a file for output.) Chapter 8 - VB 2008 by Schneider 155 155
Chapter 8 - VB 2008 by Schneider Creating a Sequential File… Place lines of data into the file with statements of the form: sw.WriteLine(datum) Close the file: sw.Close() Note: If no path is given for the file, it will be placed in the Debug subfolder of bin. Chapter 8 - VB 2008 by Schneider 156 156
Chapter 8 - VB 2008 by Schneider Example Private Sub btnCreateFile_Click(...) _ Handles btnCreateFile.Click Dim sw As IO.StreamWriter = IO.File.CreateText("PAYROLL.TXT") sw.WriteLine("Mike Jones") 'Name sw.WriteLine(9.35) 'Wage sw.WriteLine(35) ‘Hours worked sw.WriteLine("John Smith") sw.WriteLine(10.75) sw.WriteLine(33) sw.Close() End Sub Chapter 8 - VB 2008 by Schneider 157 157
Chapter 8 - VB 2008 by Schneider File: PAYROLL.TXT Mike Jones 9.35 35 John Smith 10.75 33 Chapter 8 - VB 2008 by Schneider 158 158
Chapter 8 - VB 2008 by Schneider Caution If an existing file is opened for output, Visual Basic will erase the existing file and create a new one. Chapter 8 - VB 2008 by Schneider 159 159
Chapter 8 - VB 2008 by Schneider Adding Items to a Sequential File Execute the statement Dim sw As IO.StreamWriter = IO.File.AppendText(filespec) where sw is a variable name and filespec identifies the file. Place data into the file with the WriteLine method. After all the data have been recorded into the file, close the file with the statement sw.Close() Chapter 8 - VB 2008 by Schneider 160 160
Chapter 8 - VB 2008 by Schneider IO.File.AppendText Will add data to the end of an existing file If a file does not exist, the method will create it. Chapter 8 - VB 2008 by Schneider 161 161
Chapter 8 - VB 2008 by Schneider Sequential File Modes CreateText – open for output OpenText – open for input AppendText – open for append A file should not be opened in two different modes at the same time. Chapter 8 - VB 2008 by Schneider 162 162
Chapter 8 - VB 2008 by Schneider Imports System.IO Simplifies programs that have extensive file handling. Place the statement Imports System.IO at the top of the Code Editor, before the Class frmName statement. Then, there is no need to insert the prefix “IO.” before the words StreamReader, StreamWriter, and File. Chapter 8 - VB 2008 by Schneider 163 163
Chapter 3 - VB 2008 by Schneider Getting Input from an Input Dialog Box stringVar = InputBox(prompt, title) fileName = InputBox("Enter the name " _ & "of the file containing the " & _ "information.", "Name of File") Title Prompt Chapter 3 - VB 2008 by Schneider 164 164
Chapter 3 - VB 2008 by Schneider Using a Message Dialog Box for Output MessageBox.Show(prompt, title) MessageBox.Show("Nice try, but no cigar.", _ "Consolation") Title MsgBox(prompt, , title) is executed, where prompt and title are strings, a message dialog box appears with prompt displayed and the title bar caption title and stays on the screen until the user presses Enter, clicks on the box in the upper-right corner, or clicks OK. For instance, the state-ment MsgBox("Nice try, but no cigar.", , "Consolation") Prompt Chapter 3 - VB 2008 by Schneider 165 165
Chapter 2 - VB 2008 by Schneider Masked Text Box Control Similar to an ordinary text box, but has a Mask property that restricts what can be typed into the masked text box. Tasks button Chapter 2 - VB 2008 by Schneider 166 166
Masked Text Box Control Click the Tasks button to reveal Set Mask property. Click Set Mask to invoke Input Mask dialog box. Chapter 3 - VB 2008 by Schneider 167 167
Chapter 3 - VB 2008 by Schneider Input Mask Dialog Box Chapter 3 - VB 2008 by Schneider 168 168
Mask A Mask setting is a sequence of characters, with 0, L, and & having special meanings. 0 Placeholder for a digit. L Placeholder for a letter. & Placeholder for a character Chapter 3 - VB 2008 by Schneider 169 169
Sample Masks State abbreviation: LL Phone number: 000-0000 Social Security Number: 000-00-0000 License plate: &&&&&& Chapter 3 - VB 2008 by Schneider 170 170
Importing a Text File Highlight program name in Solution Explorer Click on “Add Existing Item” in Project menu Locate text file and double-click on it. (File name will appear in Solution Explorer.) Move file to Debug subfolder of bin folder. Chapter 3 - VB 2008 by Schneider 171 171
Chapter 4 - VB 2008 by Schneider Chapter 4 – Decisions 4.1 Relational and Logical Operators 4.2 If Blocks 4.3 Select Case Blocks Chapter 4 - VB 2008 by Schneider 172 172
Chapter 4 - VB 2008 by Schneider 4.1 Relational and Logical Operators ANSI Values Relational Operators Logical Operators Boolean Data Type Chapter 4 - VB 2008 by Schneider 173 173
Chapter 4 - VB 2008 by Schneider Condition A condition is an expression involving relational (<,=) and/or logical operators (And, Or, and Not) Result of the condition is Boolean – that is, True or False Chapter 4 - VB 2008 by Schneider 174 174
Chapter 4 - VB 2008 by Schneider ANSI Character Set A numeric representation for every key on the keyboard and for other assorted characters. Chapter 4 - VB 2008 by Schneider 175 175
Chapter 4 - VB 2008 by Schneider ANSI Character Set: continued A numeric representation for every key on the keyboard and for other assorted characters. Chapter 4 - VB 2008 by Schneider 176 176
Chapter 4 - VB 2008 by Schneider Chr Function For n between 0 and 255, Chr(n) is the string consisting of the character with ANSI value n. EXAMPLES: Chr(65) is "A" Chr(162) is "¢" Chapter 4 - VB 2008 by Schneider 177 177
Chapter 4 - VB 2008 by Schneider Asc Function For a string str, Asc(str) is ANSI value of the first character of str. EXAMPLES: Asc("A") is 65 Asc("¢25") is 162 txtBox.Text=“32” & chr(176) & “ Fahrenheit” Chapter 4 - VB 2008 by Schneider 178 178
Chapter 4 - VB 2008 by Schneider Relational Operators < less than <= less than or equal to > greater than >= greater than or equal to = equal to <> not equal to ANSI values are used to decide order for strings. Chapter 4 - VB 2008 by Schneider 179 179
Chapter 4 - VB 2008 by Schneider Condition A condition is an expression involving relational and/or logical operators. Result of the condition is True or False. Chapter 4 - VB 2008 by Schneider 180 180
Example When a = 3, b = 4 (a + b) < 2 * a 2 * 3 = 6 3 + 4 = 7 7 is NOT less than 6 and the value of the expression is False Chapter 4 - VB 2008 by Schneider 181 181
Chapter 4 - VB 2008 by Schneider Another Example a = 4 b = 3 c = "hello" d = "bye" ( c.Length – b ) = ( a / 2 ) 5 – 3 = 2 4 / 2 = 2 True because 2 equals 2 “cat”<“dog” “abc”<=“Abc” Chapter 4 - VB 2008 by Schneider 182 182
Chapter 4 - VB 2008 by Schneider Relational Operator Notes Relational operators are binary – they require an operand on both sides of the operator Value of a relational expression will always be True or False Expressions are evaluated from left to right with no order of operations Chapter 4 - VB 2008 by Schneider 183 183
Chapter 4 - VB 2008 by Schneider Logical Operators Used with Boolean expressions Not – makes a False expression True and vice versa And – will yield a True if and only if both expressions are True Or – will yield a True if at least one of both expressions are True Chapter 4 - VB 2008 by Schneider 184 184
Chapter 4 - VB 2008 by Schneider Example 4.3 n = 4, answ = “Y” Are the following expressions true or false? Not (n < 6) (answ = "Y") Or (answ = "y") (answ = "Y") And (answ = "y") Not (answ = "y") Not (n < 6) = False (answ = "Y") Or (answ = "y") = True (answ = "Y") And (answ = "y") = False Not(answ = "y") = True Chapter 4 - VB 2008 by Schneider 185 185
Chapter 4 - VB 2008 by Schneider Boolean Expression An expression that evaluates to either True or False is said to have Boolean data type. Example: The statement txtBox.Text = CStr((2+3)<6) displays True in the text box. Chapter 4 - VB 2008 by Schneider 186 186
Chapter 4 - VB 2008 by Schneider Boolean Variable A variable declared with a statement of the form Dim var As Boolean is said to have Boolean data type. It can assume just the two values True and False. Example: Dim boolVar As Boolean boolVar = 2 < 6 txtBox.Text = CStr(boolVar) displays True in the text box. Chapter 4 - VB 2008 by Schneider 187 187
Chapter 4 - VB 2008 by Schneider Syntax Error The following is NOT a valid way to test if n falls between 2 and 5: (2 < n < 5 ) Chapter 4 - VB 2008 by Schneider 188 188
Chapter 4 - VB 2008 by Schneider Correction to Syntax Error To test if n falls between 2 and 5 use: (2 < n ) And ( n < 5 ) A complete relational expression must be on either side of the logical operators And and Or. And and Or are binary operators requiring two operands Not is a unary operator requiring only one operand Chapter 4 - VB 2008 by Schneider 189 189
Chapter 4 - VB 2008 by Schneider Common Error in Boolean Expressions A common error is to replace the condition Not ( 2 < 3 ) with the condition ( 2 > 3 ) The correct replacement is ( 2 >= 3 ) because >= is the opposite of <, just as <= is the opposite of > Chapter 4 - VB 2008 by Schneider 190 190
Chapter 4 - VB 2008 by Schneider 4.2 If Blocks If Block ElseIf Clauses Chapter 4 - VB 2008 by Schneider 191 191
Chapter 4 - VB 2008 by Schneider If Block The program will take a course of action based on whether a condition is true. If condition Then action1 Else action2 End If Will be executed if condition is true Will be executed if condition is false Chapter 4 - VB 2008 by Schneider 192 192
Chapter 4 - VB 2008 by Schneider Another example If block If condition Then action1 End If Statement2 Statement3 Regardless of whether the condition in the If statement is true or alse, these statements will be executed Chapter 4 - VB 2008 by Schneider 193 193
Chapter 4 - VB 2008 by Schneider Pseudocode and Flowchart for an If Block Chapter 4 - VB 2008 by Schneider 194 194
Chapter 4 - VB 2008 by Schneider Example 1: Form txtFirstNum txtSecondNum txtResult Chapter 4 - VB 2008 by Schneider 195 195
Chapter 4 - VB 2008 by Schneider Example 1: Code Private Sub btnFindLarger_Click(...) _ Handles btnFindLarger.Click Dim num1, num2, largerNum As Double num1 = CDbl(txtFirstNum.Text) num2 = CDbl(txtSecondNum.Text) If num1 > num2 Then largerNum = num1 Else largerNum = num2 End If txtResult.Text = "The larger number is " & largerNum End Sub Chapter 4 - VB 2008 by Schneider 196 196
Chapter 4 - VB 2008 by Schneider Example 1: Output Chapter 4 - VB 2008 by Schneider 197 197
Chapter 4 - VB 2008 by Schneider Example 2: Form Chapter 4 - VB 2008 by Schneider 198 198
Chapter 4 - VB 2008 by Schneider Example 2: Partial Code If costs = revenue Then txtResult.Text = "Break even" Else If costs < revenue Then profit = revenue - costs txtResult.Text = "Profit is " & _ FormatCurrency(profit) & "." loss = costs - revenue txtResult.Text = "Loss is " & _ FormatCurrency(loss) & "." End If Note the nested if statement – the If inside an If. This can be rewritten using the ElseIf construct. Chapter 4 - VB 2008 by Schneider 199 199
Chapter 4 - VB 2008 by Schneider Example 2: Output Chapter 4 - VB 2008 by Schneider 200 200
Chapter 4 - VB 2008 by Schneider Example 3: Form txtAnswer txtSolution Chapter 4 - VB 2008 by Schneider 201 201
Chapter 4 - VB 2008 by Schneider Example 3: Code Private Sub btnEvaluate_Click(...) _ Handles btnEvaluate.Click Dim answer As Double answer = CDbl(txtAnswer.Text) If (answer >= 0.5) And (answer <= 1) Then txtSolution.Text = "Good, " Else txtSolution.Text = "No, " End If txtSolution.Text &= "it holds about 3/4 of" _ & " a gallon." End Sub Chapter 4 - VB 2008 by Schneider 202 202
Chapter 4 - VB 2008 by Schneider Example 3: Output Chapter 4 - VB 2008 by Schneider 203 203
Chapter 4 - VB 2008 by Schneider ElseIf clause If condition1 Then action1 ElseIf condition2 Then action2 ElseIf condition3 Then action3 Else action4 End If An extension of the If block allows for more than two possible alternatives with the inclusion of ElseIf clauses. Note: there is no space between the word "Else" and "If" Only one "End If" is required. Chapter 4 - VB 2008 by Schneider 204 204
Chapter 4 - VB 2008 by Schneider Example 5: Form txtFirstNum txtSecondNum txtResult Chapter 4 - VB 2008 by Schneider 205 205
Chapter 4 - VB 2008 by Schneider Example 5: Code Private Sub btnFindLarger_Click(...) _ Handles btnFindLarger.Click Dim num1, num2 As Double num1 = CDbl(txtFirstNum.Text) num2 = CDbl(txtSecondNum.Text) If (num1 > num2) Then txtResult.Text = "Larger number is " & num1 ElseIf (num2 > num1) Then txtResult.Text = "Larger number is " & num2 Else txtResult.Text = "The two are equal." End If End Sub Note: there is no "if" required after the last Else to determine if the two numbers are equal. There have already been if statements to evaluate if num1 is larger than num2 and if num2 is larger than num1, so if the last Else is reached, there is no other alternative left but that they are both equal. Chapter 4 - VB 2008 by Schneider 206 206
Example:Grade Computation If Score>=90 and Attendance=100 grade=A If Score>=90 and Attendance<100 grade=B If Score>=80 and <=90 and Attendance >=90 Otherwise grade=C Copyright (c) 2003 by Prentice Hall 207
Chapter 4 - VB 2008 by Schneider 208
Chapter 4 - VB 2008 by Schneider Dim score, attendance As Double score = CDbl(txtScore.Text) attendance = CDbl(txtAttendance.Text) If score >= 90 Then If attendance = 100 Then txtGrade.Text = "A" Else txtGrade.Text = "B" End If ElseIf score >= 80 And attendance >= 90 Then txtGrade.Text = "F" Chapter 4 - VB 2008 by Schneider 209
Chapter 4 - VB 2008 by Schneider Comments When one If block is contained inside another If block, the structure is referred to as nested If blocks. Care should be taken to make If blocks easy to understand. Chapter 4 - VB 2008 by Schneider 210 210
Chapter 4 - VB 2008 by Schneider Simplified Nested If Statement If cond1 Then If cond1 And cond2 Then If cond2 Then action action End If End If Less Confusing Nested If Chapter 4 - VB 2008 by Schneider 211 211
Chapter 4 - VB 2008 by Schneider More Comments Some programs call for selecting among many possibilities. Although such tasks can be accomplished with complicated nested If blocks, the Select Case block (discussed in Section 4.3) is often a better alternative. Chapter 4 - VB 2008 by Schneider 212 212
Chapter 4 - VB 2008 by Schneider 4.3 Select Case Blocks A Select Case block is an efficient decision-making structure that simplifies choosing among several actions. It avoids complex nested If constructs. If blocks make decisions based on the truth value of a condition; Select Case choices are determined by the value of an expression called a selector. Each of the possible actions is preceded by a clause of the form Case valueList where valueList itemizes the values of the selector for which the action should be taken. Chapter 4 - VB 2008 by Schneider 213 213
Chapter 4 - VB 2008 by Schneider Select Case Block A decision-making structure that simplifies choosing among several actions. Avoids complex nested If constructs. If blocks make decisions based on the truth value of a condition. Select Case choices are determined by the value of an expression called a selector. A Select Case block is an efficient decision-making structure that simplifies choosing among several actions. It avoids complex nested If constructs. If blocks make decisions based on the truth value of a condition; Select Case choices are determined by the value of an expression called a selector. Each of the possible actions is preceded by a clause of the form Case valueList where valueList itemizes the values of the selector for which the action should be taken. Chapter 4 - VB 2008 by Schneider 214 214
Chapter 4 - VB 2008 by Schneider Select Case Terminology Each of the possible actions is preceded by a clause of the form Case valueList where valueList itemizes the values of the selector for which the action should be taken. Chapter 4 - VB 2008 by Schneider 215 215
Chapter 4 - VB 2008 by Schneider Select Case Syntax The general form of the Select Case block is Select Case selector Case valueList1 action1 Case valueList2 action2 Case Else action of last resort End Select Chapter 4 - VB 2008 by Schneider 216 216
Chapter 4 - VB 2008 by Schneider Rules for Select Case Case Else (and its action) is optional Each value list contains one or more of the following types of items separated by commas: a literal; a variable; an expression; an inequality sign preceded by Is and followed by a literal, variable, or expression; a range expressed in the form a To b, where a and b are literals, variables, or expressions. Chapter 4 - VB 2008 by Schneider 217 217
Chapter 4 - VB 2008 by Schneider Flowchart for Select Case Chapter 4 - VB 2008 by Schneider 218 218
Chapter 4 - VB 2008 by Schneider Example 1: Form txtPosition txtOutcome Chapter 4 - VB 2008 by Schneider 219 219
Chapter 4 - VB 2008 by Schneider Example 1: Code Private Sub btnEvaluate_Click(...) _ Handles btnEvaluate.Click Dim position As Integer = CInt(txtPosition.Text) Select Case position Case 1 txtOutcome.Text = "Win" Case 2 txtOutcome.Text = "Place" Case 3 txtOutcome.Text = "Show" Case 4, 5 txtOutcome.Text = "You almost placed in the money." Case Else txtBox.Text = "Out of the money." End Select End Sub Selector Value Lists Chapter 4 - VB 2008 by Schneider 220 220
Chapter 4 - VB 2008 by Schneider Example 1: Output Chapter 4 - VB 2008 by Schneider 221 221
Chapter 4 - VB 2008 by Schneider Example 2: Code Private Sub btnEvaluate_Click(...) _ Handles btnEvaluate.Click Dim position As Integer = CInt(txtPosition.Text) Select Case position Case 1 To 3 txtOutcome.Text = "In the money. Congratulations" Case Is >= 4 txtOutcome.Text = "Not in the money." End Select End Sub The keyword "To" allows the programmer to specify a range of values in the value list. The keyword "Is" allows the programmer to form a relational expression with the selector Chapter 4 - VB 2008 by Schneider 222 222
Chapter 4 - VB 2008 by Schneider Example 2: Output Chapter 4 - VB 2008 by Schneider 223 223
Chapter 4 - VB 2008 by Schneider Example 3: Partial Code Dim x As Integer = 2, y As Integer = 3, num As integer num = CInt(txtNumber.Text) Select Case num Case y - x, x txtPhrase.Text = "Buckle my shoe." Case Is <= 4 txtPhrase.Text = "Shut the door." Case x + y To x * y txtPhrase.Text = "Pick up sticks." Case 7, 8 txtPhrase.Text = "Lay them straight." Case Else txtPhrase.Text = "Start all over again." End Select Chapter 4 - VB 2008 by Schneider 224 224
Chapter 4 - VB 2008 by Schneider Example 4: Form txtReply Chapter 4 - VB 2008 by Schneider 225 225
Chapter 4 - VB 2008 by Schneider Example 4: Partial Code Select Case firstName Case "THOMAS" txtReply.Text = "Correct." Case "WOODROW" txtReply.Text = "Sorry, his name" _ & " was Thomas Woodrow Wilson." Case "PRESIDENT" txtReply.Text = "Are you for real?" Case Else txtReply.Text = "Nice try." End Select Chapter 4 - VB 2008 by Schneider 226 226
Chapter 4 - VB 2008 by Schneider Example 4: Output Chapter 4 - VB 2008 by Schneider 227 227
Chapter 4 - VB 2008 by Schneider Example 7: Form Chapter 4 - VB 2008 by Schneider 228 228
Chapter 4 - VB 2008 by Schneider Example 7: Form & Output Chapter 4 - VB 2008 by Schneider 229 229
Chapter 4 - VB 2008 by Schneider Example 7: Partial Code Dim season As String, numDays As Integer Select Case season.ToUpper Case "WINTER" numDays = 87 Case "SPRING" numDays = 92 Case "SUMMER", "AUTUMN", "FALL" numDays = 93 End Select Chapter 4 - VB 2008 by Schneider 230 230
Chapter 4 - VB 2008 by Schneider Comments In a Case clause of the form Case b To c, the value of b should be less than or equal to the value of c. The word Is should precede an inequality sign in a value list. If the word Is is accidentally omitted where required, the editor will automatically insert it when checking the line. Chapter 4 - VB 2008 by Schneider 231 231
Chapter 4 - VB 2008 by Schneider Data Type Comment The items in the value list must evaluate to a literal of the same data type as the selector. For instance, if the selector evaluated to a string value, as in Dim firstName As String = txtBox.Text Select Case firstName then the clause Case firstName.Length would be meaningless. Chapter 4 - VB 2008 by Schneider 232 232
Chapter 4 - VB 2008 by Schneider Block-level Scope A variable declared inside an If … Then or Select Case block has block-level scope. The variable cannot be referred to outside the block. Chapter 4 - VB 2008 by Schneider 233 233
Chapter 5 - VB 2008 by Schneider Chapter 5 - General Procedures 5.1 Sub Procedures, Part I 5.2 Sub Procedures, Part II 5.3 Function Procedures 5.4 Modular Design 5.5 A Case Study: Weekly Payroll Chapter 5 - VB 2008 by Schneider 234 234
Chapter 5 - VB 2008 by Schneider 5.1 Sub Procedures, Part I Sub Procedures Variables and Expressions as Arguments Calling Other Sub Procedures Chapter 5 - VB 2008 by Schneider 235 235
Chapter 5 - VB 2008 by Schneider Devices for Modularity Visual Basic has two devices for breaking problems into smaller pieces: Sub procedures Function procedures Chapter 5 - VB 2008 by Schneider 236 236
Chapter 5 - VB 2008 by Schneider Sub Procedures Perform one or more related tasks General syntax Sub ProcedureName() statements End Sub Chapter 5 - VB 2008 by Schneider 237 237
Chapter 5 - VB 2008 by Schneider Calling a Sub Procedure The statement that invokes a Sub procedure is also referred to as a Call statement. A Call statement looks like this: ProcedureName() Chapter 5 - VB 2008 by Schneider 238 238
Chapter 5 - VB 2008 by Schneider Naming Sub Procedures The rules for naming Sub procedures are the same as the rules for naming variables. Chapter 5 - VB 2008 by Schneider 239 239
Chapter 5 - VB 2008 by Schneider Example lstBox.Items.Clear() ExplainPurpose() lstBox.Items.Add("") Sub ExplainPurpose() lstBox.Items.Add("Program displays a sentence") lstBox.Items.Add("identifying a sum.") End Sub Chapter 5 - VB 2008 by Schneider 240 240
Chapter 5 - VB 2008 by Schneider Passing Values You can send values to a Sub procedure Sum(2, 3) Sub Sum(ByVal num1 As Double, ByVal num2 As Double) lstBox.Items.Add("The sum of " & num1 & " and " _ & num2 & " is " & (num1 + num2) & "." End Sub In the Sum Sub procedure, 2 will be stored in num1 and 3 will be stored in num2 Chapter 5 - VB 2008 by Schneider 241 241
Arguments and Parameters Sum(2, 3) Sub Sum(ByVal num1 As Double, ByVal num2 As Double) arguments paramete rs displayed automatica lly Chapter 5 - VB 2008 by Schneider 242 242
Chapter 5 - VB 2008 by Schneider Several Calling Statements ExplainPurpose() Sum(2, 3) Sum(4, 6) Sum(7, 8) Output: Program displays a sentence identifying a sum. The sum of 2 and 3 is 5. The sum of 4 and 6 is 10 The sum of 7 and 8 is 15. Chapter 5 - VB 2008 by Schneider 243 243
Chapter 5 - VB 2008 by Schneider Passing Strings and Numbers Demo("CA", 38) Sub Demo(ByVal state As String, ByVal pop As Double) txtBox,Text = state & " has population " & pop & _ " million." End Sub Note: The statement Demo(38, "CA") would not be valid. The types of the arguments must be in the same order as the types of the parameters. Chapter 5 - VB 2008 by Schneider 244 244
Chapter 5 - VB 2008 by Schneider Variables and Expressions as Arguments Dim s As String = "CA" Dim p As Double = 19 Demo(s, 2 * p) Sub Demo(ByVal state As String, ByVal pop As Double) txtBox.Text = state & " has population " & pop & _ " million." End Sub Note: The variable names in the arguments need not match the parameter names. For instance, s versus state.. Chapter 5 - VB 2008 by Schneider 245 245
Chapter 5 - VB 2008 by Schneider Calling A Sub procedure can call another Sub procedure. Private Sub btnAdd_Click(...) Handles btnAdd.Click Sum(2, 3) End Sub Sub Sum(ByVal num1 As Double, ByVal num2 As Double) DisplayPurpose() lstBox.Items.Add("The sum of " & num1 & " and " _ & num2 & " is " & (num1 + num2) & "." Chapter 5 - VB 2008 by Schneider 246 246
Chapter 5 - VB 2008 by Schneider 5.2 Sub Procedures, Part II Passing by Value Passing by Reference Lifetime and Scope of a Variable Debugging Chapter 5 - VB 2008 by Schneider 247 247
Chapter 5 - VB 2008 by Schneider ByVal and ByRef Parameters in Sub procedure headers are proceeded by ByVal or ByRef ByVal stands for By Value ByRef stands for By Reference Chapter 5 - VB 2008 by Schneider 248 248
Chapter 5 - VB 2008 by Schneider Passing by Value When a variable argument is passed to a ByVal parameter, just the value of the argument is passed. After the Sub procedure terminates, the variable has its original value. Chapter 5 - VB 2008 by Schneider 249 249
Chapter 5 - VB 2008 by Schneider Example Public Sub btnOne_Click (...) Handles _ btnOne.Click Dim n As Double = 4 Triple(n) txtBox.Text = CStr(n) End Sub Sub Triple(ByVal num As Double) num = 3 * num Output: 4 Chapter 5 - VB 2008 by Schneider 250 250
Chapter 5 - VB 2008 by Schneider Same Example: n num Public Sub btnOne_Click (...) Handles _ btnOne.Click Dim num As Double = 4 Triple(num) txtBox.Text = CStr(num) End Sub Sub Triple(ByVal num As Double) num = 3 * num Output: 4 Chapter 5 - VB 2008 by Schneider 251 251
Chapter 5 - VB 2008 by Schneider Passing by Reference When a variable argument is passed to a ByRef parameter, the parameter is given the same memory location as the argument. After the Sub procedure terminates, the variable has the value of the parameter. Chapter 5 - VB 2008 by Schneider 252 252
Chapter 5 - VB 2008 by Schneider Example Public Sub btnOne_Click (...) Handles _ btnOne.Click Dim num As Double = 4 Triple(num) txtBox.Text = CStr(num) End Sub Sub Triple(ByRef num As Double) num = 3 * num Output: 12 Chapter 5 - VB 2008 by Schneider 253 253
Chapter 5 - VB 2008 by Schneider Example: num n Private Sub btnOne_Click(...) Handles _ btnOne_Click Dim n As Double = 4 Triple(n) txtBox.Text = CStr(n) End Sub Sub Triple(ByRef num As Double) num = 3 * num Output: 12 Chapter 5 - VB 2008 by Schneider 254 254
Chapter 5 - VB 2008 by Schneider Lifetime and Scope of a Variable Lifetime: Period during which it remains in memory. Scope: In Sub procedures, defined same as in event procedures. Suppose a variable is declared in procedure A that calls procedure B. While procedure B executes, the variable is alive, but out of scope. Chapter 5 - VB 2008 by Schneider 255 255
Chapter 5 - VB 2008 by Schneider Debugging Programs with Sub procedures are easier to debug Each Sub procedure can be checked individually before being placed into the program Chapter 5 - VB 2008 by Schneider 256 256
Chapter 5 - VB 2008 by Schneider 5.3 Function Procedures User-Defined Functions Having Several Parameters User-Defined Functions Having No Parameters User-Defined Boolean-valued Functions Comparing Function Procedures with Sub Procedures Named Constants Chapter 5 - VB 2008 by Schneider 257 257
Chapter 5 - VB 2008 by Schneider Some Built-In Functions Function Example Input Output Int Int(2.6) is 2 number Math.Round Math.Round(1.23,1) is 1.2 number, number FormatPercent FormatPercent(.12) is 12.00% string FormatNumber FormatNumber(12345.628, 1) is 12,345.6 Chapter 5 - VB 2008 by Schneider 258
Chapter 5 - VB 2008 by Schneider Function Procedures Function procedures (aka user-defined functions) always return one value Syntax: Function FunctionName(ByVal var1 As Type1, _ ByVal var2 As Type2, _ …) As dataType statement(s) Return expression End Function Chapter 5 - VB 2008 by Schneider 259 259
Chapter 5 - VB 2008 by Schneider Example: Form txtFullNam e ByVal is used in function parameters so the function will not inadvertently return more than one value Value in return statement is sent back to the place where the function was called – the function call "becomes" that value – which must then be stored, or printed, or used in some way by the calling routine. There is a one to one relationship between the arguments being passed to the function and the parameters that the function receives txtFirstNam e Chapter 5 - VB 2008 by Schneider 260 260
Chapter 5 - VB 2008 by Schneider Example: Code Private Sub btnDetermine_Click(...) _ Handles btnDetermine.Click Dim name As String name = txtFullName.Text txtFirstName.Text = FirstName(name) End Sub Function FirstName(ByVal name As String) As String Dim firstSpace As Integer firstSpace = name.IndexOf(" ") Return name.Substring(0, firstSpace) End Function Function call The "As String" at the end of the line which begins "Function First Name" is the data type of the value being returned from this function Return statement Chapter 5 - VB 2008 by Schneider 261 261
Chapter 5 - VB 2008 by Schneider Example: Form txtSideOn e txtSideT wo ByVal is used in function parameters so the function will not inadvertently return more than one value Value in return statement is sent back to the place where the function was called – the function call "becomes" that value – which must then be stored, or printed, or used in some way by the calling routine. There is a one to one relationship between the arguments being passed to the function and the parameters that the function receives txtHyp Chapter 5 - VB 2008 by Schneider 262 262
Chapter 5 - VB 2008 by Schneider Example: Code Private Sub btnCalculate_Click(...) _ Handles btnCalculate.Click Dim a, b As Double a = CDbl(txtSideOne.Text) b = CDbl(txtSideTwo.Text) txtHyp.Text = CStr(Hypotenuse(a, b)) End Sub Function Hypotenuse(ByVal a As Double, _ ByVal b As Double) As Double Return Math.Sqrt(a ^ 2 + b ^ 2) End Function ByVal is used in function parameters so the function will not inadvertently return more than one value Value in return statement is sent back to the place where the function was called – the function call "becomes" that value – which must then be stored, or printed, or used in some way by the calling routine. There is a one to one relationship between the arguments being passed to the function and the parameters that the function receives Chapter 5 - VB 2008 by Schneider 263 263
Chapter 5 - VB 2008 by Schneider User-Defined Function Having No Parameters Private Sub btnDisplay_Click(...) _ Handles btnDisplay.Click txtBox.Text = Saying() End Sub Function Saying() As String Dim strVar As String strVar = InputBox("What is your" _ & " favorite saying?") Return strVar End Function Chapter 5 - VB 2008 by Schneider 264 264
Chapter 5 - VB 2008 by Schneider Comparing Function Procedures with Sub Procedures Subs are accessed using a Call statement Functions are called where you would expect to find a literal or expression For example: result = functionCall lstBox.Items.Add (functionCall) Chapter 5 - VB 2008 by Schneider 265 265
Chapter 5 - VB 2008 by Schneider Functions vs. Procedures Both can perform similar tasks Both can call other subs and functions Use a function when you want to return one and only one value Chapter 5 - VB 2008 by Schneider 266 266
Chapter 5 - VB 2008 by Schneider 5.4 Modular Design Top-Down Design Structured Programming Advantages of Structured Programming Chapter 5 - VB 2008 by Schneider 267 267
Chapter 5 - VB 2008 by Schneider Design Terminology Large programs can be broken down into smaller problems "divide-and-conquer" approach called "stepwise refinement" Stepwise refinement is part of top-down design methodology Chapter 5 - VB 2008 by Schneider 268 268
Chapter 5 - VB 2008 by Schneider Top-Down Design General problems are at the top of the design Specific tasks are near the end of the design Top-down design and structured programming are techniques to enhance programmers' productivity Chapter 5 - VB 2008 by Schneider 269 269
Chapter 5 - VB 2008 by Schneider Top-Down Design Criteria The design should be easily readable and emphasize small module size. Modules proceed from general to specific as you read down the chart. The modules, as much as possible, should be single minded. That is, they should only perform a single well-defined task. Modules should be as independent of each other as possible, and any relationships among modules should be specified. Chapter 5 - VB 2008 by Schneider 270 270
Chapter 5 - VB 2008 by Schneider Top-Level Design HIPO Chart Chapter 5 - VB 2008 by Schneider 271 271
Chapter 5 - VB 2008 by Schneider Detailed HIPO Chart Chapter 5 - VB 2008 by Schneider 272 272
Chapter 5 - VB 2008 by Schneider Structured Programming Control structures in structured programming: Sequences: Statements are executed one after another. Decisions: One of two blocks of program code is executed based on a test for some condition. Loops (iteration): One or more statements are executed repeatedly as long as a specified condition is true. Chapter 5 - VB 2008 by Schneider 273 273
Chapter 5 - VB 2008 by Schneider Advantages of Structured Programming Goal to create correct programs that are easier to write understand modify "GOTO –less" programming Chapter 5 - VB 2008 by Schneider 274 274
Chapter 5 - VB 2008 by Schneider Comparison of Flow Charts Chapter 5 - VB 2008 by Schneider 275 275
Chapter 5 - VB 2008 by Schneider Easy to Write Allows programmer to first focus on the big picture and take care of the details later Several programmers can work on the same program at the same time Code that can be used in many programs is said to be reusable Chapter 5 - VB 2008 by Schneider 276 276
Chapter 5 - VB 2008 by Schneider Easy to Debug Procedures can be checked individually A driver program can be set up to test modules individually before the complete program is ready Using a driver program to test modules (or stubs) is known as stub testing Chapter 5 - VB 2008 by Schneider 277 277
Chapter 5 - VB 2008 by Schneider Easy to Understand Interconnections of the procedures reveal the modular design of the program. The meaningful procedure names, along with relevant comments, identify the tasks performed by the modules. The meaningful variable names help the programmer to recall the purpose of each variable. Chapter 5 - VB 2008 by Schneider 278 278
Chapter 5 - VB 2008 by Schneider Easy to Change Because a structured program is self- documenting, it can easily be deciphered by another programmer. Chapter 5 - VB 2008 by Schneider 279 279
Chapter 5 - VB 2008 by Schneider Object-Oriented Programming an encapsulation of data and code that operates on the data objects have properties, respond to methods, and raise events. Chapter 5 - VB 2008 by Schneider 280 280
Chapter 6 - VB 2008 by Schneider Chapter 6 – Repetition 6.1 Do Loops 6.2 Processing Lists of Data with Do Loops 6.3 For...Next Loops 6.4 A Case Study: Analyze a Loan Chapter 6 - VB 2008 by Schneider 281 281
Chapter 6 - VB 2008 by Schneider 6.1 Do Loops A loop is one of the most important structures in programming. Used to repeat a sequence of statements a number of times. The Do loop repeats a sequence of statements either as long as or until a certain condition is true. Chapter 6 - VB 2008 by Schneider 282 282
Do Loop Syntax Do While condition statement(s) Loop Condition is tested, If it is true, the loop is run. If it is false, the statements following the Loop statement are executed. Do While condition statement(s) Loop These statements are inside the body of the loop and are run if the condition above is true. A Do statement precedes the sequence of statements, and a Loop statement follows the sequence of statements. The condition, preceded by either the word “While” or the word “Until”, follows the word “Do” or the word “Loop”. Chapter 6 - VB 2008 by Schneider 283 283
Chapter 6 - VB 2008 by Schneider Pseudocode and Flow Chart for a Do Loop Chapter 6 - VB 2008 by Schneider 284 284
Chapter 6 - VB 2008 by Schneider Example 1 Private Sub btnDisplay_Click(...) _ Handles btnDisplay.Click 'Display the numbers from 1 to 7 Dim num As Integer = 1 Do While num <= 7 lstNumbers.Items.Add(num) num += 1 'Add 1 to the value of num Loop End Sub Num is the "loop control variable" because based on the value of num, the loop will either continue or stop. Note that the value of the loop control variable must change inside the loop. Chapter 6 - VB 2008 by Schneider 285 285
Chapter 6 - VB 2008 by Schneider Example: Repeat Request as Long as Response in Incorrect Dim passWord As String = "" Do While passWord <> "SHAZAM" passWord = InputBox("What is the password?") passWord = passWord.ToUpper Loop passWord is the loop control variable because the value stored in passWord is what is tested to determine if the loop should continue or stop. Chapter 6 - VB 2008 by Schneider 286 286
Post Test Loop Do statement(s) Loop Until condition Loop is executed once and then the condition is tested. If it is false, the loop is run again. If it is frue, the statements following the Loop statement are executed. If condition is true, then the program continues with the line after the Loop statement. If condition is false, then the entire process is repeated beginning with the Do statement. In other words, the statements inside the loop are executed once and then are repeatedly executed until the condition is true. Chapter 6 - VB 2008 by Schneider 287 287
Chapter 6 - VB 2008 by Schneider Example: Repeat Request Until Proper Response is Given Do passWord = InputBox("What is the password?") passWord = passWord.ToUpper Loop Until passWord = "SHAZAM" Chapter 6 - VB 2008 by Schneider 288 288
Chapter 6 - VB 2008 by Schneider Pseudocode and Flowchart for a Post-Test Loop Chapter 6 - VB 2008 by Schneider 289 289
Chapter 6 - VB 2008 by Schneider Example 4: Form txtAmount txtWhen Chapter 6 - VB 2008 by Schneider 290 290
Chapter 6 - VB 2008 by Schneider Example 4: Code Private Sub btnCalculate_Click(...) Handles btnCalculate.Click Dim balance As Double, numYears As Integer balance = CDbl(txtAmount.Text) Do While balance < 1000000 balance += 0.06 * balance numYears += 1 Loop txtWhen.Text = "In " & numYears & _ " years you will have a million dollars." End Sub Chapter 6 - VB 2008 by Schneider 291 291
Chapter 6 - VB 2008 by Schneider Example 4: Output Chapter 6 - VB 2008 by Schneider 292 292
Chapter 6 - VB 2008 by Schneider Comments Be careful to avoid infinite loops – loops that never end. Visual Basic allows for the use of either the While keyword or the Until keyword at the top or the bottom of a loop. This textbook will use only While at the top and only Until at the bottom. Chapter 6 - VB 2008 by Schneider 293 293
Chapter 6 - VB 2008 by Schneider 6.2 Processing Lists of Data with Do Loops Peek Method Counters and Accumulators Flags Nested Loops Chapter 6 - VB 2008 by Schneider 294 294
Chapter 6 - VB 2008 by Schneider Processing Lists of Data with Do Loops Display all or selected items from lists Search lists for specific items Perform calculations on the numerical entries of a list Chapter 6 - VB 2008 by Schneider 295 295
Chapter 6 - VB 2008 by Schneider Peek Method Data to be processed are often retrieved from a file by a Do loop To determine if we have reached the end of the file from which we are reading, we use the Peek method. Chapter 6 - VB 2008 by Schneider 296 296
Chapter 6 - VB 2008 by Schneider Peek Example Suppose a file has been opened as a StreamReader object named sr. sr.Peek is the ANSI value of the first character of the line about to be read with ReadLine. If the end of the file has been reached, the value of sr.Peek is -1 Chapter 6 - VB 2008 by Schneider 297 297
Chapter 6 - VB 2008 by Schneider Example 1: Display the Total Contents of a File Dim sr As IO.StreamReader = _ IO.File.OpenText("PHONE.TXT") lstNumbers.Items.Clear() Do While sr.Peek <> -1 name = sr.ReadLine phoneNum = sr.ReadLine lstNumbers.Items.Add(name & " " _ & phoneNum) Loop sr.Close() Chapter 6 - VB 2008 by Schneider 298 298
Chapter 6 - VB 2008 by Schneider Pseudocode and Flowchart for Processing Data from a File Chapter 6 - VB 2008 by Schneider 299 299
Chapter 6 - VB 2008 by Schneider Example 2: Form txtName txtNumber Chapter 6 - VB 2008 by Schneider 300 300
Chapter 6 - VB 2008 by Schneider Example 2: Partial Code Do While (name <> txtName.Text) _ And (sr.Peek <> -1) name = sr.ReadLine phoneNum = sr.ReadLine Loop As long as the name being searched for has not been found AND the end of the file has not been reached, the loop will continue Chapter 6 - VB 2008 by Schneider 301 301
Chapter 6 - VB 2008 by Schneider Counters and Accumulators A counter is a numeric variable that keeps track of the number of items that have been processed. An accumulator is a numeric variable that totals numbers. Chapter 6 - VB 2008 by Schneider 302 302
Chapter 6 - VB 2008 by Schneider File COINS.TXT 1 5 10 25 Count the number of coins and determine the total value Chapter 6 - VB 2008 by Schneider 303 303
Chapter 6 - VB 2008 by Schneider Example 3: Partial Code Dim numCoins As Integer = 0 Dim sum As Integer = 0 Dim coin As String Do While sr.Peek <> -1 coin = sr.ReadLine numCoins += 1 sum += CDbl(coin) Loop sum is an accumulator. It is used to total up the values of the coins. numCoins is a counter, it increases by 1 each time through the loop Chapter 6 - VB 2008 by Schneider 304 304
Chapter 6 - VB 2008 by Schneider Flags A flag is a variable that keeps track of whether a certain situation has occurred. The data type most suited to flags is Boolean. Chapter 6 - VB 2008 by Schneider 305 305
Chapter 6 - VB 2008 by Schneider Example 4: Form The file WORDS.TXT contains words from a spelling bee, one word per line. Count the words and determine whether they are in alphabetical order. Chapter 6 - VB 2008 by Schneider 306 306
Chapter 6 - VB 2008 by Schneider Example 4: Partial Code Dim word1 As String = "" Dim orderFlag As Boolean = True Do While (sr.Peek <> -1) word2 = sr.ReadLine wordCounter += 1 If word1 > word2 Then orderFlag = False End If word1 = word2 Loop This program counts the number of words in the file WORDS.TXT and then reports whether the words are in alphabetical order. In each execution of the loop, a word is compared to the next word in the list. The flag variable, called orderFlag, is initially assigned the value True and is set to False if a pair of adjacent words is out of order. Chapter 6 - VB 2008 by Schneider 307 307
Chapter 6 - VB 2008 by Schneider Nested Loops Statements inside a loop can contain another loop. Chapter 6 - VB 2008 by Schneider 308 308
Chapter 6 - VB 2008 by Schneider More About Flags When flagVar is a variable of Boolean type, the statements If flagVar = True Then and If flagVar = False Then can be replaced by If flagVar Then If Not flagVar Then Chapter 6 - VB 2008 by Schneider 309 309
Chapter 6 - VB 2008 by Schneider Flags continued The statements Do While flagVar = True and Do While flagVar = False can be replaced by Do While flagVar Do While Not flagVar Chapter 6 - VB 2008 by Schneider 310 310
Chapter 6 - VB 2008 by Schneider 6.3 For…Next Loops Nested For … Next Loops Local Type Inference Chapter 6 - VB 2008 by Schneider 311 311
Chapter 6 - VB 2008 by Schneider For…Next Loops Used when we know how many times we want the loop to execute A counter controlled loop Chapter 6 - VB 2008 by Schneider 312 312
Chapter 6 - VB 2008 by Schneider Sample For i As Integer = 1 To 5 lstTable.Items.Add(i & " " & i ^ 2) Next The loop control variable, i, is initialized to 1 tested against the stop value, 5 incremented by 1 at the Next statement Chapter 6 - VB 2008 by Schneider 313 313
Chapter 6 - VB 2008 by Schneider Similar Do While Loop i = 1 Do While i <= 5 lstTable.Items.Add(i & " " & i ^ 2) i += 1 Loop Note how much more simple the For loop is Chapter 6 - VB 2008 by Schneider 314 314
Chapter 6 - VB 2008 by Schneider For…Next Loop Syntax Chapter 6 - VB 2008 by Schneider 315 315
Chapter 6 - VB 2008 by Schneider Example 1: Output Yr is the control variable 2002 is the start value 2006 is the stop value Yr will keep being increased by 1 at the Next statement until yr is > 2006 Chapter 6 - VB 2008 by Schneider 316 316
Chapter 6 - VB 2008 by Schneider Example 1: Code Dim pop as Double = 300000 Dim fmtStr As String = "{0,4}{1,12:N0}" For yr As Integer = 2008 To 2012 lstPop.Items.Add(String.Format( _ fmtStr, yr, pop) pop += 0.03 * pop Next Yr is the control variable 2002 is the start value 2006 is the stop value Yr will keep being increased by 1 at the Next statement until yr is > 2006 Chapter 6 - VB 2008 by Schneider 317 317
Chapter 6 - VB 2008 by Schneider Example 2 Control variable Data type Start value Stop value Amount to add to i For i As Integer = 0 To n Step s lstValues.Items.Add(i) Next Start value must be less than or equal to the stop value when there is a positive step value Chapter 6 - VB 2008 by Schneider 318 318
Chapter 6 - VB 2008 by Schneider Example with Negative Step For j As Integer = 10 To 1 Step -1 lstBox.Items.Add(j) Next lstBox.Items.Add("Blastoff") Start value must be >= the stop value when there is a NEGATIVE step value Chapter 6 - VB 2008 by Schneider 319 319
Chapter 6 - VB 2008 by Schneider Example: Nested Loops For i As Integer = 65 To 70 For j As Integer = 1 To 25 lstBox.Items.Add(Chr(i) & j) Next OUTPUT: A1 A2 A3 : Outer loop Inner loop Chapter 6 - VB 2008 by Schneider 320 320
Chapter 6 - VB 2008 by Schneider For and Next Pairs For and Next statements must be paired. If one is missing, the automatic syntax checker will complain with a wavy underline and a message such as “A ‘For’ must be paired with a ‘Next’.” Chapter 6 - VB 2008 by Schneider 321 321
Chapter 6 - VB 2008 by Schneider Start, Stop, and Step values Consider a loop beginning with For i As Integer = m To n Step s. The loop will be executed exactly once if m equals n no matter what value s has. The loop will not be executed at all if m is greater than n and s is positive, or if m is less than n and s is negative. Chapter 6 - VB 2008 by Schneider 322 322
Chapter 6 - VB 2008 by Schneider Altering the Control Variable The value of the control variable should not be altered within the body of the loop. Doing so might cause the loop to repeat indefinitely or have an unpredictable number of repetitions. Chapter 6 - VB 2008 by Schneider 323 323
Chapter 6 - VB 2008 by Schneider Non-integer Step Values Can lead to round-off errors with the result that the loop is not executed the intended number of times. We will only use Integers for all values in the header. Chapter 6 - VB 2008 by Schneider 324 324
Chapter 7 - VB 2008 by Schneider Chapter 7 – Arrays 7.1 Creating and Accessing Arrays 7.2 Using Arrays 7.3 Some Additional Types of Arrays 7.4 Sorting and Searching 7.5 Two-Dimensional Arrays Chapter 7 - VB 2008 by Schneider 325 325
Chapter 7 - VB 2008 by Schneider 7.1 Creating and Accessing Arrays Declaring an Array Variable The Load Event Procedure The GetUpperBound Method ReDim Statement Using an Array as a Frequency Table Assignment Statement for Arrays User-Defined Array-Valued Functions Chapter 7 - VB 2008 by Schneider 326 326
Chapter 7 - VB 2008 by Schneider Simple and Array Variables A variable (or simple variable) is a name to which Visual Basic can assign a single value. An array variable is a collection of simple variables of the same type to which Visual Basic can efficiently assign a list of values. Chapter 7 - VB 2008 by Schneider 327 327
Chapter 7 - VB 2008 by Schneider Example Suppose that you want to evaluate the exam grades for 30 students and to display the names of the students whose scores are above average. Private Sub btnDisplay_Click(...) _ Handles btnDisplay.Click Dim student0 As String, score0 As Double Dim student1 As String, score1 As Double Dim student2 As String, score2 As Double Chapter 7 - VB 2008 by Schneider 328 328
Using Arrays Dim student(29) As String Dim score(29) As Double Upper bound of subscripts in the array Dim student(29) As String Dim score(29) As Double Array name Data type Chapter 7 - VB 2008 by Schneider 329 329
Chapter 7 - VB 2008 by Schneider Putting Values into an Array student(0) = "Tom Brown" subscript Read: "student sub zero equals Tom Brown" Which means that the string "Tom Brown" is being stored at the first location in the array called student… because all arrays begin counting at 0. Chapter 7 - VB 2008 by Schneider 330 330
Chapter 7 - VB 2008 by Schneider Array Terminology Dim arrayName(n) As DataType 0 is the "lower bound" of the array n is the "upper bound" of the array – the last available subscript in this array The number of elements, n + 1, is the size of the array Chapter 7 - VB 2008 by Schneider 331 331
Chapter 7 - VB 2008 by Schneider Example 1: Form mtxtNumber txtWinner Chapter 7 - VB 2008 by Schneider 332 332
Chapter 7 - VB 2008 by Schneider Example 1 Private Sub btnWhoWon_Click(...) _ Handles btnWhoWon.Click Dim teamName(3) As String Dim n As Integer 'Place Super Bowl Winners into the array teamName(0) = "Packers" teamName(1) = "Packers" teamName(2) = "Jets" teamName(3) = "Chiefs" 'Access array n = CInt(txtNumber.Text) txtWinner.Text = teamName(n - 1) End Sub Note that the array is created and the array is loaded each and every time the user clicks on the Who Won button. See example 2 for an improvement where the array is only loaded once. Chapter 7 - VB 2008 by Schneider 333 333
Chapter 7 - VB 2008 by Schneider Example 1: Output Chapter 7 - VB 2008 by Schneider 334 334
Chapter 7 - VB 2008 by Schneider Load Event Procedure Occurs as the Form loads in memory Private Sub frmName_Load(...) _ Handles MyBase.Load The keyword MyBase refers to the form being loaded. This event procedure is a good place to assign values to an array. Chapter 7 - VB 2008 by Schneider 335 335
Chapter 7 - VB 2008 by Schneider Example 2 Dim teamName(3) As String Private Sub btnWhoWon_Click(...) Handles btnWhoWon.Click Dim n As Integer n = CInt(txtNumber.Text) txtWinner.Text = teamName(n - 1) End Sub Private Sub frmBowl_Load(...) Handles MyBase.Load 'Place Super Bowl Winners into the array teamName(0) = "Packers" teamName(1) = "Packers" teamName(2) = "Jets" teamName(3) = "Chiefs" Chapter 7 - VB 2008 by Schneider 336 336
Chapter 7 - VB 2008 by Schneider Initializing Arrays Arrays may be initialized when they are created: Dim arrayName() As varType = {value0, _ value1, value2, ..., valueN} declares an array having upper bound N and assigns value0 to arrayName(0), value1 to arrayName(1), ..., and valueN to arrayName(N). Chapter 7 - VB 2008 by Schneider 337 337
Chapter 7 - VB 2008 by Schneider GetUpperBound Method The value of arrayName.GetUpperBound(0) is the upper bound of arrayName(). Chapter 7 - VB 2008 by Schneider 338 338
Chapter 7 - VB 2008 by Schneider Example Dim teamName() As String = {"Packers", _ "Packers", "Jets", "Chiefs"} txtBox.Text = CStr(teamName.GetUpperBound(0)) Output: 3 Chapter 7 - VB 2008 by Schneider 339 339
Chapter 7 - VB 2008 by Schneider ReDim Statement The size of an array may be changed after it has been created. ReDim arrayName(m) where arrayName is the name of the already declared array and m is an Integer literal, variable, or expression, changes the upper bound of the array to m. Note the size of the array may change after the array is created, but not the data type. Chapter 7 - VB 2008 by Schneider 340 340
Chapter 7 - VB 2008 by Schneider Preserve Keyword ReDim arrayName(m) resets all values to their default. This can be prevented with the keyword Preserve. ReDim Preserve arrayName(m) resizes the array and retains as many values as possible. Chapter 7 - VB 2008 by Schneider 341 341
Chapter 7 - VB 2008 by Schneider Example 4: Using an Array as a Frequency Table Chapter 7 - VB 2008 by Schneider 342 342
Chapter 7 - VB 2008 by Schneider Example 4: Code Private Sub btnAnalyze_Click(...) Handles btnAnalyze.Click 'Count occurrences of the various letters in a sentence Dim sentence, letter As String Dim index, charCount(25) As Integer 'Examine and tally each letter of the sentence sentence = (txtSentence.Text).ToUpper For letterNum As Integer = 1 To sentence.Length letter = sentence.Substring(letterNum - 1, 1) If (letter >= "A") And (letter <= "Z") Then index = Asc(letter) - 65 'The ANSI value of "A" is 65 charCount(index) += 1 End If Next Chapter 7 - VB 2008 by Schneider 343 343
Chapter 7 - VB 2008 by Schneider Example 4: Code Continued 'List the tally for each letter of alphabet lstCount.Items.Clear() For i As Integer = 0 To 25 letter = Chr(index + 65) If charCount(index) > 0 Then lstCount.Items.Add(letter & " " & _ charCount(i)) End If Next End Sub Chapter 7 - VB 2008 by Schneider 344 344
Chapter 7 - VB 2008 by Schneider Example 4 Output Chapter 7 - VB 2008 by Schneider 345 345
Chapter 7 - VB 2008 by Schneider Out of Bounds Error The following code references an array element that doesn't exist. This will cause an error. Chapter 7 - VB 2008 by Schneider 346 346
Chapter 7 - VB 2008 by Schneider Assignment Statement for Arrays If arrayOne() and arrayTwo() have been declared with the same data type, then the statement arrayOne = arrayTwo makes arrayOne() an exact duplicate of arrayTwo(). Actually, they share the same location in memory, Chapter 7 - VB 2008 by Schneider 347 347
Chapter 7 - VB 2008 by Schneider User-Defined Array-Valued Functions Headers have the form Function FunctionName(ByVal var1 As Type1, _ ByVal var2 As Type2, ...) As DataType() Chapter 7 - VB 2008 by Schneider 348 348
Chapter 7 - VB 2008 by Schneider 7.2 Using Arrays Ordered Arrays Using Part of an Array Merging Two Ordered Arrays Passing Arrays to Procedures Chapter 7 - VB 2008 by Schneider 349 349
Chapter 7 - VB 2008 by Schneider Ordered Arrays An array has ascending order if [each element] ≤ [next element]. An array has descending order if [each element] ≥ [next element]. An array is ordered if it has ascending or descending order. Chapter 7 - VB 2008 by Schneider 350 350
Chapter 7 - VB 2008 by Schneider Searching Ordered Arrays Ordered arrays can be searched more efficiently than unordered arrays. For instance, when searching an array having ascending order, you can terminate the search when you find an element whose value is ≥ the sought- after value. Chapter 7 - VB 2008 by Schneider 351 351
Chapter 7 - VB 2008 by Schneider Example 1: Task Given a name input by the user, determine if it is in an increasing list of ten names, Chapter 7 - VB 2008 by Schneider 352 352
Chapter 7 - VB 2008 by Schneider Flowchart for a Search of an Increasing Array Chapter 7 - VB 2008 by Schneider 353 353
Chapter 7 - VB 2008 by Schneider Example 1: Code Dim nom() As String = {"AL", "BOB", "CARL", "DON", "ERIC", _ "FRED", "GREG", "HERB", "IRA", "JACK"} Private Sub btnSearch_Click(...) Handles btnSearch.Click Dim name2Find As String Dim n As Integer = -1 'Subscript of the array name2Find = txtName.Text.ToUpper Do n += 1 'Add 1 to n Loop Until (nom(n) >= name2Find) Or (n = 9) If nom(n) = name2Find Then txtResult.Text = "Found." Else txtResult.Text = "Not found." End If End Sub Chapter 7 - VB 2008 by Schneider 354 354
Chapter 7 - VB 2008 by Schneider Example 1: Output Chapter 7 - VB 2008 by Schneider 355 355
Chapter 7 - VB 2008 by Schneider Using Part of an Array Sometimes we do not know how many elements will be needed in an array. We can declare a large array, say of 100 elements, and use a counter variable to record the number of elements used. In Example 2, the names are an unknown number of companies is placed into an array. Chapter 7 - VB 2008 by Schneider 356 356
Chapter 7 - VB 2008 by Schneider Example 2: Output txtCompany Chapter 7 - VB 2008 by Schneider 357 357
Chapter 7 - VB 2008 by Schneider Example 2: Code 'Demonstrate using part of an array Dim stock(99) As String Dim counter As Integer Private Sub btnRecord_Click(...) Handles btnRecord.Click If (counter < 99) Then counter += 1 'Increment counter by 1 stock(counter - 1) = txtCompany.Text txtCompany.Clear() txtCompany.Focus() txtNumber.Text = CStr(counter) Else MessageBox.Show("No space to record more companies.") End If End Sub Chapter 7 - VB 2008 by Schneider 358 358
Chapter 7 - VB 2008 by Schneider Example 2: Code Continued Private Sub btnSummarize_Click(...) _ Handles btnSummarize.Click 'List companies that were recorded lstStocks.Items.Clear() For i As Integer = 0 To counter - 1 lstStocks.Items.Add(stock(i)) Next End Sub Chapter 7 - VB 2008 by Schneider 359 359
Chapter 7 - VB 2008 by Schneider Merging Two Ascending Arrays To consolidate the two lists into a single ordered third list: Compare the two names at the top of the first and second lists. If one name alphabetically precedes the other, copy it onto the third list and cross it off its original list. If the names are the same, copy the name onto the third list and cross out the name from the first and second lists. Repeat Step 1 with the current top names until you reach the end of either list. Copy the names from the remaining list into the third list. Chapter 7 - VB 2008 by Schneider 360 360
Chapter 7 - VB 2008 by Schneider Passing Arrays to Procedures An array declared in a procedure is local to that procedure An entire array can be passed to a Sub or Function procedure The Call statement uses the name of the array without parentheses. The header of the Sub of Function procedure uses the name with empty set of parentheses. Chapter 7 - VB 2008 by Schneider 361 361
Chapter 7 - VB 2008 by Schneider Example 4 This example uses a Function procedure to add up the numbers in an array. The GetUpperBound method is used to determine how many numbers are in the array. Chapter 7 - VB 2008 by Schneider 362 362
Chapter 7 - VB 2008 by Schneider Example 4 Private Sub btnCompute_Click(...) Handles btnCompute.Click Dim score() As Integer = {85, 92, 75, 68, 84, 86, _ 94, 74, 79, 88} txtAverage.Text = CStr(Sum(score) / 10) End Sub Function Sum(ByVal s() As Integer) As Integer Dim total As Integer = 0 For index As Integer = 0 To s.GetUpperBound(0) total += s(index) Next Return total End Function Notice that the function call is written Sum(score), not Sum(score()), and that the parameter declaration is written ByVal s() As Integer, not ByVal s As Integer. Chapter 7 - VB 2008 by Schneider 363 363
Chapter 7 - VB 2008 by Schneider Sequential Search Searching successive elements of an ordered list beginning with the first element is called a sequential search. An efficient alternative to the sequential search is the binary search, which is considered in Section 7.4. Chapter 7 - VB 2008 by Schneider 364 364
Chapter 7 - VB 2008 by Schneider Passing an Array Element A single element of an array can be passed to a procedure just like any ordinary numeric or string variable. Private Sub btnDisplay_Click(...) Handles _ btnDisplay.Click Dim num(20) As Integer num(5) = 10 lstOutput.Items.Add(Triple(num(5))) End Sub Private Function Triple(ByVal x As Integer) As Integer Return 3 * x End Function Chapter 7 - VB 2008 by Schneider 365 365
Chapter 7 - VB 2008 by Schneider 7.3 Some Additional Types of Arrays Control Arrays Array of Structures Displaying and Comparing Structure Values Chapter 7 - VB 2008 by Schneider 366 366
Chapter 7 - VB 2008 by Schneider Control Arrays Control arrays are arrays of controls, such as labels, text boxes, etc. They are created in much the same way as any other array: Dim arrayName(n) As ControlType or Dim arrayName() As ControlType Chapter 7 - VB 2008 by Schneider 367 367
Chapter 7 - VB 2008 by Schneider Control Arrays continued The following statements declare control arrays. Dim lblTitle(10) As Label Dim txtNumber(8) As TextBox Dim btnAmount() As Button Chapter 7 - VB 2008 by Schneider 368 368
Chapter 7 - VB 2008 by Schneider Example 2: Form TextBox1 TextBox5 txtTotal Chapter 7 - VB 2008 by Schneider 369 369
Chapter 7 - VB 2008 by Schneider Example 1 Array of controls Dim lblDept(4) As Label Dim txtDept(4) As TextBox Private Sub frmSales_Load(...) Handles MyBase.Load lblDept(0) = Label1 lblDept(1) = Label2 lblDept(2) = Label3 lblDept(3) = Label4 lblDept(4) = Label5 txtDept(0) = TextBox1 txtDept(1) = TextBox2 txtDept(2) = TextBox3 txtDept(3) = TextBox4 txtDept(4) = TextBox5 Placing controls into arrays Chapter 7 - VB 2008 by Schneider 370 370
Chapter 7 - VB 2008 by Schneider Example 1 continued For depNum As Integer = 1 To 5 lblDept(depNum - 1).Text = "Department " & depNum txtDept(depNum).Clear() Next End Sub Private Sub btnCompute_Click(...) _ Handles btnCompute.Click Dim totalSales As Double = 0 totalSales += CDbl(txtDept(depNum - 1).Text) txtTotal.Text = FormatCurrency(totalSales) Chapter 7 - VB 2008 by Schneider 371 371
Chapter 7 - VB 2008 by Schneider Example 1 Output Chapter 7 - VB 2008 by Schneider 372 372
Chapter 7 - VB 2008 by Schneider Structures A way of grouping heterogeneous data together Also called a UDT (User Defined Type) Sample structure definition: Structure College Dim name As String Dim state As String Dim yearFounded As Integer End Structure Chapter 7 - VB 2008 by Schneider 373 373
Chapter 7 - VB 2008 by Schneider Structure Definition Each subvariable in a structure is called a member. To declare a variable of a structure type: Dim college1 As College Each member is accessed via variable name.member name college1.state = "Maryland" Chapter 7 - VB 2008 by Schneider 374 374
Chapter 7 - VB 2008 by Schneider Example 2 Structure College Dim name As String Dim state As String Dim yearFounded As Integer End Structure Dim college1, college2, collegeOlder As College Private Sub btnFirst_Click(...) Handles btnFirst.Click Dim prompt As String college1.name = InputBox("Enter name of college.", "Name") college1.state = InputBox("Enter state.", "State") prompt = "Enter the year the first college was founded." college1.yearFounded = CInt(InputBox(prompt, "Year")) End Sub Chapter 7 - VB 2008 by Schneider 375 375
Chapter 7 - VB 2008 by Schneider Structure Members Integer, String, Double, etc. Another User Defined Type Arrays Must not specify range Range must be set using ReDim Chapter 7 - VB 2008 by Schneider 376 376
Chapter 7 - VB 2008 by Schneider Example 4 This example gathers information about a student and determines when the student will be eligible to graduate. Chapter 7 - VB 2008 by Schneider 377 377
Chapter 7 - VB 2008 by Schneider Example 4 Structure FullName Dim firstName As String Dim lastName As String End Structure Structure Student Dim name As FullName Dim credits() As Integer Private Sub btnGet_Click(...) Handles btnGet.Click Dim numYears As Integer Dim person As Student Structure "FullName" contained, or nested, inside Student Chapter 7 - VB 2008 by Schneider 378 378
Chapter 7 - VB 2008 by Schneider Example 4 continued txtResult.Clear() person.name.firstName = InputBox("First Name:") person.name.lastName = InputBox("Second Name:") numYears = CInt(InputBox("Number of years " & _ "completed:")) ReDim person.credits(numYears - 1) For i As Integer = 0 To numYears - 1 person.credits(i)=CInt(InputBox("Credits in year " _ & i + 1)) Next DetermineStatus(person) End Sub Chapter 7 - VB 2008 by Schneider 379 379
Chapter 7 - VB 2008 by Schneider Example 4 continued Sub DetermineStatus(ByVal person As Student) Dim total As Integer = 0 For i As Integer = 0 To person.credits.GetUpperBound(0) total += person.credits(i) Next If (total >= 120) Then txtResult.Text = person.name.firstName & " " & _ person.name.lastName & " has enough credits" & _ " to graduate." Else person.name.lastName & " needs " & _ (120 - total) & " more credits to graduate." End If End Sub Chapter 7 - VB 2008 by Schneider 380 380
Chapter 7 - VB 2008 by Schneider 7.4 Sorting and Searching Bubble Sort Shell Sort Searching Chapter 7 - VB 2008 by Schneider 381 381
Chapter 7 - VB 2008 by Schneider Sorting Sorting is an algorithm for ordering an array. We discuss two sorting algorithms: bubble sort Shell sort Both use the swap algorithm: temp = varl varl = var2 var2 = temp Chapter 7 - VB 2008 by Schneider 382 382
Chapter 7 - VB 2008 by Schneider Example 1 Output txtFirstWord txtSecondWord txtResult Chapter 7 - VB 2008 by Schneider 383 383
Chapter 7 - VB 2008 by Schneider Example 1 Swap Algorithm Private Sub btnAlphabetize_Click(...) _ Handles btnAlphabetize.Click Dim firstWord, secondWord, temp As String firstWord = txtFirstWord.Text secondWord = txtSecondWord.Text If (firstWord > secondWord) Then temp = firstWord firstWord = secondWord secondWord = temp End If txtResult.Text = firstWord & " before " & _ secondWord End Sub Chapter 7 - VB 2008 by Schneider 384 384
Chapter 7 - VB 2008 by Schneider Bubble Sort Algorithm: n Items Compare the first and second items. If they are out of order, swap them. Compare the second and third items. If they are out of order, swap them. Repeat this pattern for all remaining pairs. The final comparison and possible swap are between the next-to- last and last items. Chapter 7 - VB 2008 by Schneider 385 385
Chapter 7 - VB 2008 by Schneider Bubble Sort Algorithm The last item will be at its proper place. Do another pass through first n – 1 items. Repeat this process with one less item for each pass until a pass uses only the first and second items. Chapter 7 - VB 2008 by Schneider 386 386
Chapter 7 - VB 2008 by Schneider Shell Sort Algorithm Begin with a gap of g = Int(n/2) Compare items 0 and g, 1 and 1 + g, . . ., n - g and n. Swap any pairs that are out of order. Repeat Step 2 until no swaps are made for gap g. Halve the value of g. Repeat Steps 2, 3, and 4 until the value of g is 0. Chapter 7 - VB 2008 by Schneider 387 387
Chapter 7 - VB 2008 by Schneider Searching Sequential search starts at the beginning of a list and keeps looking one by one until the item is found or the end of the list is reached. For a sequential search, the list need not be sorted. Chapter 7 - VB 2008 by Schneider 388 388
Chapter 7 - VB 2008 by Schneider Binary Search Usually more efficient than sequential search List must be sorted Chapter 7 - VB 2008 by Schneider 389 389
Chapter 7 - VB 2008 by Schneider Binary Search: Algorithm Given: an array in ascending order and a sought-after value, quarry, that may be in the array. Repeatedly halve the range of indices where quarry might be found. Halving routine looks at the middle value of the current range and compares it to quarry with =, >, and <. If middle value = quarry, then search is over. If middle value > quarry, then we can limit our search to the half of the range below the middle value. If middle value < quarry, then we can limit our search to the half of the range above the middle value. Chapter 7 - VB 2008 by Schneider 390 390
Chapter 7 - VB 2008 by Schneider Binary Search: Variables first – lower limit of range of values to search last – upper limit of range of values to search middle = Int((first + last) / 2) a() – ordered array to be searched foundFlag – True when quarry is found Note: If quarry is not in the array, eventually last will be greater than first. Note: Initially first = 0 and last = a.GetUpperBound(0) Chapter 7 - VB 2008 by Schneider 391 391
Chapter 7 - VB 2008 by Schneider Binary Search: Code Do While (first <= last) And (Not FoundFlag) middle = CInt((first + last) / 2) Select Case a(middle) Case quarry foundFlag = True Case Is > quarry last = middle – 1 Case Is < quarry first = middle + 1 End Select Loop Chapter 7 - VB 2008 by Schneider 392 392
Chapter 7 - VB 2008 by Schneider Binary Search: Notes If a binary search ends with foundFlag = True, the subscript of the found item might be useful. This would be the case if the array were an array of structures that was ordered with respect to one of its members. The binary search would serve as an efficient table lookup process. Chapter 7 - VB 2008 by Schneider 393 393
Chapter 7 - VB 2008 by Schneider 7.5 Two Dimensional Arrays One-dimensional arrays store a list of items of the same type Two-dimensional arrays store a table of items of the same type. Consider the rows of the table as numbered 0, 1, 2, ,,, m and the columns numbered 0, 1, 2, …, n. Then the array is declared with the statement Dim arrayName(m, n) As DataType and the item in the ith row, jth column is denoted arrayName(i,j) Chapter 7 - VB 2008 by Schneider 394 394
Chapter 7 - VB 2008 by Schneider Road-Mileage Table Chicago LA NY Philly 2054 802 738 2786 2706 100 Dim rm(3, 3) As Double rm(0,0)=0, rm(0,1)=2054, rm(1,2)=2786 Chapter 7 - VB 2008 by Schneider 395 395
Chapter 7 - VB 2008 by Schneider Populating a Two-Dimensional Array Dim rm(3, 3) As Double Private Sub frmDistances_Load(...) Handles MyBase.Load 'Fill two-dimensional array with intercity mileages Dim sr As IO.StreamReader = _ IO.File.OpenText("DISTANCE.TXT") For row As Integer = 0 To 3 For col As Integer = 0 To 3 rm(row, col) = CDbl(sr.ReadLine) Next sr.Close() End Sub Chapter 7 - VB 2008 by Schneider 396 396
Chapter 7 - VB 2008 by Schneider Notes on Two-Dimensional Arrays An unsized two-dimensional array can be declared with a statement of the form Dim arrayName(,) As varType and a two-dimensional array can be declared and initialized at the same time with a statement of the form Dim arrayName(,) As varType = {{ROW0}, {ROW1},... {ROWm}} Chapter 7 - VB 2008 by Schneider 397 397
Chapter 7 - VB 2008 by Schneider ReDim and Two-Dimensional Arrays An already-created array can be resized with ReDim arrayName(r, s) which loses the current contents, or with ReDim Preserve arrayName(r, s) When Preserve is used, only the column can be resized. ReDim cannot change the number of dimensions in an array. Chapter 7 - VB 2008 by Schneider 398 398
Chapter 8 - VB 2008 by Schneider Chapter 8 – Sequential Files 8.1 Sequential Files 8.2 Using Sequential Files Chapter 8 - VB 2008 by Schneider 399 399
Chapter 8 - VB 2008 by Schneider Section 8.1 – Sequential Files Creating a Sequential File Adding Items to a Sequential File Structured Exception Handling Chapter 8 - VB 2008 by Schneider 400 400
Chapter 8 - VB 2008 by Schneider Sequential Files A sequential file consists of data stored in a text file on disk. May be created with the Visual Basic IDE May also be created programmatically from Visual Basic Chapter 8 - VB 2008 by Schneider 401 401
Chapter 8 - VB 2008 by Schneider Creating a Sequential File Choose a filename – may contain up to 215 characters Select the path for the folder to contain this file Execute a statement like the following: Dim sw As IO.StreamWriter = IO.File.CreateText(filespec) (Opens a file for output.) Chapter 8 - VB 2008 by Schneider 402 402
Chapter 8 - VB 2008 by Schneider Creating a Sequential File… Place lines of data into the file with statements of the form: sw.WriteLine(datum) Close the file: sw.Close() Note: If no path is given for the file, it will be placed in the Debug subfolder of bin. Chapter 8 - VB 2008 by Schneider 403 403
Chapter 8 - VB 2008 by Schneider Example Private Sub btnCreateFile_Click(...) _ Handles btnCreateFile.Click Dim sw As IO.StreamWriter = IO.File.CreateText("PAYROLL.TXT") sw.WriteLine("Mike Jones") 'Name sw.WriteLine(9.35) 'Wage sw.WriteLine(35) ‘Hours worked sw.WriteLine("John Smith") sw.WriteLine(10.75) sw.WriteLine(33) sw.Close() End Sub Chapter 8 - VB 2008 by Schneider 404 404
Chapter 8 - VB 2008 by Schneider File: PAYROLL.TXT Mike Jones 9.35 35 John Smith 10.75 33 Chapter 8 - VB 2008 by Schneider 405 405
Chapter 8 - VB 2008 by Schneider Caution If an existing file is opened for output, Visual Basic will erase the existing file and create a new one. Chapter 8 - VB 2008 by Schneider 406 406
Chapter 8 - VB 2008 by Schneider Adding Items to a Sequential File Execute the statement Dim sw As IO.StreamWriter = IO.File.AppendText(filespec) where sw is a variable name and filespec identifies the file. Place data into the file with the WriteLine method. After all the data have been recorded into the file, close the file with the statement sw.Close() Chapter 8 - VB 2008 by Schneider 407 407
Chapter 8 - VB 2008 by Schneider IO.File.AppendText Will add data to the end of an existing file If a file does not exist, the method will create it. Chapter 8 - VB 2008 by Schneider 408 408
Chapter 8 - VB 2008 by Schneider Sequential File Modes CreateText – open for output OpenText – open for input AppendText – open for append A file should not be opened in two different modes at the same time. Chapter 8 - VB 2008 by Schneider 409 409
Chapter 8 - VB 2008 by Schneider Avoiding Errors Attempting to open a non-existent file for input brings up a message box titled: FileNotFoundException There is a method to determine if a file exists before attempting to open it: IO.File.Exists(filespec) will return a True if the file exists Chapter 8 - VB 2008 by Schneider 410 410
Chapter 8 - VB 2008 by Schneider Testing for the Existence of a File Dim sr As IO.StreamReader If IO.File.Exists(filespec) Then sr = IO.File.OpenText(filespec) Else message = "Either no file has yet been " message &= "created or the file named" message &= filespec & " is not found." MessageBox.Show(message, "File Not Found") End If Chapter 8 - VB 2008 by Schneider 411 411
Chapter 8 - VB 2008 by Schneider Deleting Information from a Sequential File An individual item of a file cannot be changed or deleted directly. A new file must be created by reading each item from the original file and recording it, with the single item changed or deleted, into the new file. The old file is then erased, and the new file renamed with the name of the original file. Chapter 8 - VB 2008 by Schneider 412 412
IO.File.Delete(filespec) IO.File.Move(oldfilespec, newfilespec) Delete and Move Methods Delete method: IO.File.Delete(filespec) Move method (to change the filespec of a file): IO.File.Move(oldfilespec, newfilespec) Note: The IO.File.Delete and IO.File.Move methods cannot be used with open files. Chapter 8 - VB 2008 by Schneider 413 413
Chapter 8 - VB 2008 by Schneider Imports System.IO Simplifies programs that have extensive file handling. Place the statement Imports System.IO at the top of the Code Editor, before the Class frmName statement. Then, there is no need to insert the prefix “IO.” before the words StreamReader, StreamWriter, and File. Chapter 8 - VB 2008 by Schneider 414 414
Chapter 8 - VB 2008 by Schneider Structured Exception Handling Two types of problems in code: Bugs – something wrong with the code the programmer has written Exceptions – errors beyond the control of the programmer Programmer can use the debugger to find bugs; but must anticipate exceptions in order to be able to keep the program from terminating abruptly. Chapter 8 - VB 2008 by Schneider 415 415
Chapter 8 - VB 2008 by Schneider How Visual Basic Handles Exceptions An unexpected problem causes Visual Basic first to throw an exception then to handle it. If the programmer does not explicitly include exception-handling code in the program, then Visual Basic handles an exception with a default handler. The default exception handler terminates execution, displays the exception’s message in a dialog box and highlights the line of code where the exception occurred. Chapter 8 - VB 2008 by Schneider 416 416
Chapter 8 - VB 2008 by Schneider Exception Example If the user enters a word or leaves the input box blank in the following program, an exception will be thrown: Dim taxCredit As Double Private Sub btnComputeCredit_Click(...) _ Handles btnComputeCredit.Click Dim numDependants As Integer numDependants = CInt(InputBox( _ "How many dependants do you have?")) taxCredit = 1000 * numDependants End Sub A user with no dependants might just leave the input box blank and press the OK button. If so, VB.NET terminates the program and displays the dialog box shown in Figure 8.2. (The problem was caused by the fact that the default value in an input box, Nothing, cannot be converted to an integer. Strings and text boxes also have Nothing as their default value.) It also highlights the third line of code since the exception was thrown while executing the CInt() function. The program also would have crashed had the user typed in an answer like “TWO”. Chapter 8 - VB 2008 by Schneider 417 417
Chapter 8 - VB 2008 by Schneider Exception Handled by Visual Basic Chapter 8 - VB 2008 by Schneider 418 418
Chapter 8 - VB 2008 by Schneider Try-Catch-Finally Block Dim taxCredit As Double Private Sub btnComputeCredit_Click(...) Handles btnComputeCredit.Click Dim numDependents As Integer, message As String Try numDependents = CInt(InputBox("How many dependents?")) Catch message = "You did not answer the question " _ & " with an integer value. We will " _ & " assume your answer is zero." MessageBox.Show(message) numDependents = 0 Finally taxCredit = 1000 * numDependents End Try End Sub This type of exception handling is known as data validation Chapter 8 - VB 2008 by Schneider 419 419
Chapter 8 - VB 2008 by Schneider Catch Blocks Visual Basic allows Try-Catch-Finally blocks to have one or more specialized Catch clauses that only trap a specific type of exception. The general form of a specialized Catch clause is Catch exp As ExceptionName where the variable exp will be assigned the name of the exception. The code in this block will be executed only when the specified exception occurs. Chapter 8 - VB 2008 by Schneider 420 420
Chapter 8 - VB 2008 by Schneider Try Catch Block Syntax Try normal code Catch exc1 As FirstException exception-handling code for FirstException Catch exc2 As SecondException exception-handling code for SecondException . Catch exception-handling code for any remaining exceptions Finally clean-up code End Try The normal code is the code that you want to monitor for exceptions. As with a Select Case block, the Catch clauses are considered one at a time until the proper exception is located. The last Catch clause in the preceding code functions like the Case Else clause. The clean-up code in the Finally block always executes last regardless of whether any exception-handling code has executed. Chapter 8 - VB 2008 by Schneider 421 421
Chapter 8 - VB 2008 by Schneider Exception Handling and File Errors Exception handling can also catch file access errors. File doesn't exist causes an IO.FileNotFoundException If an attempt is made to delete an open file, IO.IOException is thrown. Chapter 8 - VB 2008 by Schneider 422 422
Chapter 8 - VB 2008 by Schneider 8.2 Using Sequential Files Sorting Sequential Files CSV Format Merging Sequential Files Control Break Processing Chapter 8 - VB 2008 by Schneider 423 423
Chapter 8 - VB 2008 by Schneider 8.2 Sorting Sequential Files Read data from file into an array of structures. Sort the data based on chosen member in structure. Write sorted data to file. Chapter 8 - VB 2008 by Schneider 424 424
Chapter 8 - VB 2008 by Schneider CSV File Format Comma Separated Values Records are stored on one line with a comma between each field Example: Mike Jones,9.35,35 John Smith,10.75,33 A record holds all the data about a single individual. Each item of data is called a field. Chapter 8 - VB 2008 by Schneider 425 425
Chapter 8 - VB 2008 by Schneider LSV File Format Line Separated Values Each value appears on its own line Up to now, this is the only type of file we have been using. Chapter 8 - VB 2008 by Schneider 426 426
Chapter 8 - VB 2008 by Schneider Split Function Facilitates working with CSV formatted files. Split can convert a line containing commas into a String array. The 0th element contains the text preceding the first comma, the 1st element contains the text between the first and second commas, ..., and the last element contains the text following the last comma. Chapter 8 - VB 2008 by Schneider 427 427
Chapter 8 - VB 2008 by Schneider Split Example For instance, suppose the String array employees() has been declared without an upper bound, and the String variable line has the value “Bob,23.50,45”. employees = line.Split(","c) sets the size of employees() to 3 sets employees(0) = “Bob” employees (1) = “23.50” employees(2) = “45”. Chapter 8 - VB 2008 by Schneider 428 428
Chapter 8 - VB 2008 by Schneider Split Comments Employees = line.Split(","c) In this example, the character comma is called the delimiter for the Split function, and the letter c specifies that the comma has data type Character instead of String. (If Option Strict is Off, the letter c can be omitted.) Any character can be used as a delimiter. If no character is specified, the Split function will use the space character as delimiter. Chapter 8 - VB 2008 by Schneider 429 429
Chapter 8 - VB 2008 by Schneider Example 2 Private Sub btnConvert_Click(...) _ Handles btnConvert.Click Dim stateData(), line As String line = "California, 1850, Sacramento, Eureka" stateData = line.Split(","c) For i As Integer = 0 To stateData.GetUpperBound(0) stateData(i) = stateData(i).Trim 'Get rid 'of extraneous spaces lstOutput.Items.Add(stateData(i)) Next End Sub Chapter 8 - VB 2008 by Schneider 430 430
Chapter 8 - VB 2008 by Schneider Example 2 Output California 1850 Sacramento Eureka Chapter 8 - VB 2008 by Schneider 431 431
Chapter 8 - VB 2008 by Schneider Example 3: Convert a CSV Format File to an LSV Format Private Sub btnConvert_Click(...) Handles btnConvert.Click Dim line, fields(), fromFile, toFile As String Dim sr As IO.StreamReader Dim sw As IO.StreamWriter fromFile = InputBox("Name of original file:", _ "Convert from CSV to LSV") toFile = InputBox("Name of converted file:", _ sr = IO.File.OpenText(fromFile) sw = IO.File.CreateText(toFile) Do While (sr.Peek() <> -1) line = sr.ReadLine() fields = line.Split(","c) The following program converts any CSV file to an LSV file and then displays the contents of the new file. We will assume that the file to be converted is located in the bin folder for the program. Chapter 8 - VB 2008 by Schneider 432 432
Chapter 8 - VB 2008 by Schneider Example 3 continued For i As Integer = 0 To fields.GetUpperBound(0) sw.WriteLine(fields(i).Trim) Next Loop sr.Close() sw.Close() sr = IO.File.OpenText(toFile) Do While sr.Peek <> -1 lstFile.Items.Add(sr.ReadLine) End Sub Chapter 8 - VB 2008 by Schneider 433 433
Chapter 8 - VB 2008 by Schneider Example 3: Input File California, 1850, Sacramento, Eureka New York, 1788, Albany, Excelsior Run, press the button, and respond to the two requests with csvSTATES.TXT and STATES.TXT. Assume that the file csvSTATES.TXT contains the two lines “California, 1850, Sacramento, Eureka” and “New York, 1788, Albany, Excelsior”. The following will be displayed in the list box.] Chapter 8 - VB 2008 by Schneider 434 434
Chapter 8 - VB 2008 by Schneider Example 3: Output File California 1850 Sacramento Eureka New York 1788 Albany Excelsior Run, press the button, and respond to the two requests with csvSTATES.TXT and STATES.TXT. Assume that the file csvSTATES.TXT contains the two lines “California, 1850, Sacramento, Eureka” and “New York, 1788, Albany, Excelsior”. The following will be displayed in the list box.] Chapter 8 - VB 2008 by Schneider 435 435
Chapter 8 - VB 2008 by Schneider Join Function The reverse of the Split function is the Join function Join concatenates the elements of a string array into a string containing the elements separated by a specified delimiter. Dim greatLakes() As String = _ {"Huron","Ontario","Michigan","Erie","Superior"} Dim lakes As String lakes = Join(greatLakes, ",") txtOutput.Text = lakes OUTPUT: Huron,Ontario,Michigan,Erie,Superior Caution when working with Split and Join, the 0th element is always used. Chapter 8 - VB 2008 by Schneider 436 436
Chapter 8 - VB 2008 by Schneider Merging Ordered Sequential Files Algorithm Open the two ordered files for input, and open a third file for output. Try to get an item of data from each file. Repeat the following steps until an item of data is not available in one of the files: If one item precedes the other, write it into the third file and try to get another item of data from its file. If the two items are identical, write one into the third file and try to get another item of data from each of the two ordered files. Chapter 8 - VB 2008 by Schneider 437 437
Chapter 8 - VB 2008 by Schneider Merge Algorithm continued At this point, an item of data has most likely been retrieved from one of the files and not yet written to the third file. In this case, write that item and all remaining items in that file to the third file. Close the three files. Chapter 8 - VB 2008 by Schneider 438 438
Chapter 8 - VB 2008 by Schneider Control Break Processing Used to create subtotals When there is special significance to the changing of the value of a certain variable, that variable is called a control variable Each change of its value is called a break. Chapter 8 - VB 2008 by Schneider 439 439
Chapter 8 - VB 2008 by Schneider Data for Example 5 Month Day Address Price January 9 102 Elm St $203,000 January 20 1 Main St $315,200 January 25 5 Maple St $123,450 February 15 1 Center St $100,000 February 23 2 Vista Dr $145,320 March 15 5 Rodeo Cir $389,100 Chapter 8 - VB 2008 by Schneider 440 440
Chapter 8 - VB 2008 by Schneider Task for Example 5 Display sales by month and display the monthly subtotals. Chapter 8 - VB 2008 by Schneider 441 441
Chapter 8 - VB 2008 by Schneider Output for Example 5 Chapter 8 - VB 2008 by Schneider 442 442
Chapter 8 - VB 2008 by Schneider Comments Files to be processed can be opened and closed within a single procedure. Files can also be opened just once the instant the program is run and stay open until the program is terminated. To open a file once, open it in the form’s Load procedure and put the Close method and End statement in the click event procedure for a button labeled “Quit.” Chapter 8 - VB 2008 by Schneider 443 443
Chapter 9 - VB 2008 by Schneider Chapter 9 – Additional Controls and Objects 9.1 List Boxes, Combo Boxes, and the File-Opening Control 9.2 Seven Elementary Controls 9.3 Four Additional Objects 9.4 Graphics Chapter 9 - VB 2008 by Schneider 444 444
Chapter 9 - VB 2008 by Schneider 9.1 List Boxes, Combo Boxes, and the File-Opening Control The List Box Control Filling a List Box at Design Time Using an Array to Fill a List Box The Combo Box Control The OpenFileDialog Control Chapter 9 - VB 2008 by Schneider 445 445
Chapter 9 - VB 2008 by Schneider The List Box Control Items can be placed into the list at design time or run time The Sorted property allows items in the list to be sorted automatically If the Sorted property is set to True, then the following will place an item into the list in order and assign the index of its position to num: num = lstBox.Items.Add(str) Chapter 9 - VB 2008 by Schneider 446 446
Chapter 9 - VB 2008 by Schneider Useful Properties of the List Box The total number of items in a list box is given by lstBox.Items.Count Note: Each item in lstBox is identified by an index number from 0 to lstBox.Items.Count – 1 The index number of the currently highlighted item is given by: lstBox.SelectedIndex lstBox.Items.Count-1 is the value of the last subscript (index) because the list starts at 0. If no item is highlighted, the value of SelectedIndex is –1. Chapter 9 - VB 2008 by Schneider 447 447
Chapter 9 - VB 2008 by Schneider More List Box Properties lstBox.Items() is the list of items in the list box. The value of the item with an index of n is: lstBox.Items(n) The data type of the elements in the lstBox.Items() array is Object. To display the first element of lstBox.Items in a text box: txtBox.Text = CStr(lstBox.Items(0)) Chapter 9 - VB 2008 by Schneider 448 448
Chapter 9 - VB 2008 by Schneider Currently Highlighted Item in a List Boxes The currently highlighted item can be obtained as: lstBox.Items(lstBox.SelectedIndex) or lstBox.Text Chapter 9 - VB 2008 by Schneider 449 449
Chapter 9 - VB 2008 by Schneider Removing Items from a List Box To delete an item at a given location: lstBox.Items.RemoveAt(n) To delete the first occurrence of an item: lstBox.Items.Remove(str) To remove everything from a list box: lstBox.Items.Clear() Chapter 9 - VB 2008 by Schneider 450 450
Chapter 9 - VB 2008 by Schneider List Box Events Three main types of events with list boxes: Click – the user clicks on an item in the list box SelectedIndexChanged - the user clicks on an item or uses the arrow keys to select it DoubleClick - the user double-clicks on an item All three events are triggered when the user double-clicks on an item. Chapter 9 - VB 2008 by Schneider 451 451
Chapter 9 - VB 2008 by Schneider Example 1: Form lstOxys txtSelected Chapter 9 - VB 2008 by Schneider 452 452
Chapter 9 - VB 2008 by Schneider Example 1: Code Private Sub lstOxys_SelectedIndexChanged(...) _ Handles lstOxys.SelectedIndexChanged txtSelected.Text = CStr(lstOxys.SelectedItem) End Sub Private Sub btnAdd_Click(...) Handles btnAdd.Click Dim item As String item = InputBox("Item to Add:") lstOxys.Items.Add(item) Private Sub lstOxys_DoubleClick(...) _ Handles lstOxys.DoubleClick lstOxys.Items.RemoveAt(lstOxys.SelectedIndex) txtSelected.Clear() Chapter 9 - VB 2008 by Schneider 453 453
Chapter 9 - VB 2008 by Schneider Filling a List Box at Design Time Select the Items property of the list box. Click on the ellipsis button on the right side of the Settings box. (A window titled String Collection Editor will be displayed.) Type in the first item, and press Enter. Repeat Step 3 for each of the other items. When you are finished entering items, click on the OK button. Chapter 9 - VB 2008 by Schneider 454 454
Chapter 9 - VB 2008 by Schneider Using an Array to Fill a List Box The statement lstBox.DataSource = arrayName fills the list box with the elements of the array. Chapter 9 - VB 2008 by Schneider 455 455
Chapter 9 - VB 2008 by Schneider The Combo Box Control A list box combined with a text box The user has the option of filling the text box by selecting from a list or typing directly into the list box. Essentially same properties, events, and methods as a list box Chapter 9 - VB 2008 by Schneider 456 456
The Combo Box Control Three types of combo boxes in the DropDownStyle property: DropDown (and DropDownList) combo box Simple combo box Chapter 9 - VB 2008 by Schneider 457 457
Chapter 9 - VB 2008 by Schneider Example 2 Private Sub btnDisplay_Click(...) _ Handles btnDisplay.Click txtDisplay.Text = cboTitle.Text & " " & txtName.Text End Sub txtName txtName cboTitle cboTitle txtDisplay txtDisplay Chapter 9 - VB 2008 by Schneider 458 458
Chapter 9 - VB 2008 by Schneider The OpenFileDialog Control Implements the standard File Open dialog box Found in the Dialogs section of the Toolbox When you place the control on the form, it will not be visible. The icon and default name will appear in a pane below the Main area. Chapter 9 - VB 2008 by Schneider 459 459
An Open File Dialog Box 460 460
Chapter 9 - VB 2008 by Schneider The Filter Property Determines what appears in the “Files of type:” combo box, and what types of files will be displayed. The setting has the general form text for combo box|*.ext Example: Text Files (*.TXT)|*.TXT Chapter 9 - VB 2008 by Schneider 461 461
Chapter 9 - VB 2008 by Schneider Using the OpenFileDialog Control To display the control: OpenFileDialog1.ShowDialog() After the Open button has been pressed, the file name selected and its complete filespec will be contained in the property: OpenFileDialog1.FileName Chapter 9 - VB 2008 by Schneider 462 462
Chapter 9 - VB 2008 by Schneider Example 3: Task Select a text file and display its contents. Note: The Filter property of OpenFileDialog1 is set to Text Files (*.TXT)|*.TXT Chapter 9 - VB 2008 by Schneider 463 463
Chapter 9 - VB 2008 by Schneider Example 3: Code Private Sub btnSelect_Click(...) Handles _ btnSelect.Click Dim textFile As String OpenFileDialog1.ShowDialog() textFile = OpenFileDialog1.FileName Dim sr As IO.StreamReader = _ IO.File.OpenText(textFile) Do While sr.Peek <> -1 lstOutput.Items.Add(sr.ReadLine) Loop sr.Close() End Sub Chapter 9 - VB 2008 by Schneider 464 464
Chapter 9 - VB 2008 by Schneider 9.2 Seven Elementary Controls The Group Box Control The Check Box Control The Radio Button Control The Timer Control The Picture Box Control The Horizontal and Vertical Scroll Bar Controls Chapter 9 - VB 2008 by Schneider 465 465
Chapter 9 - VB 2008 by Schneider The Group Box Control Group boxes are passive objects used to group other objects together. When you drag a group box, the attached controls follow as a unit. To attach a control to a group box, create the group box, then drag the control you want to attach into the group box. Chapter 9 - VB 2008 by Schneider 466 466
Text property of the group box Group Box Example Text property of the group box Three attached controls: Button1 Button2 Button3 Chapter 9 - VB 2008 by Schneider 467 467
Chapter 9 - VB 2008 by Schneider The Check Box Control Consists of a small square and a caption Presents the user with a Yes/No choice During run time, clicking on the check box toggles the appearance of a check mark. Checked property is True when the check box is checked and False when it is not CheckedChanged event is triggered when the user clicks on the check box Chapter 9 - VB 2008 by Schneider 468 468
Chapter 9 - VB 2008 by Schneider Example 1: Form Chapter 9 - VB 2008 by Schneider 469 469
Example 1: Code Private Sub Tally(...) Handles chkDrugs.CheckedChanged, _ chkDental.CheckedChanged, chkVision.CheckedChanged, _ chkMedical.CheckChanged Dim sum As Double = 0 If chkDrugs.Checked Then sum += 12.51 End If If chkDental.Checked Then sum += 9.68 If chkVision.Checked Then sum += 1.5 If chkMedical.Checked Then sum += 25.25 txtTotal.Text = FormatCurrency(sum) End Sub 470 470
Chapter 9 - VB 2008 by Schneider Example 1: Output Chapter 9 - VB 2008 by Schneider 471 471
Chapter 9 - VB 2008 by Schneider The Radio Button Control Consists of a small circle with a caption (that is set by the Text property) Normally several radio buttons are attached to a group box Gives the user a single choice from several options Clicking on one radio button removes the selection from another Chapter 9 - VB 2008 by Schneider 472 472
Chapter 9 - VB 2008 by Schneider Radio Button Properties To determine if the button is on or off radButton.Checked has value True if button in on. To turn a radio button on radButton.Checked = True Chapter 9 - VB 2008 by Schneider 473 473
Chapter 9 - VB 2008 by Schneider Example 2: Form radCandidate1 radCandidate2 txtVote Chapter 9 - VB 2008 by Schneider 474 474
Chapter 9 - VB 2008 by Schneider Example 2: Code Private Sub btnVote_Click(...) Handles btnVote.Click If radCandidate1.Checked Then txtVote.Text = "You voted for Kennedy." ElseIf radCandidate2.Checked Then txtVote.Text = "You voted for Nixon." Else txtVote.Text = "You voted for neither." End If End Sub Chapter 9 - VB 2008 by Schneider 475 475
Chapter 9 - VB 2008 by Schneider Example 2: Output Chapter 9 - VB 2008 by Schneider 476 476
Chapter 9 - VB 2008 by Schneider The Timer Control Invisible during run time Triggers an event after a specified period of time The Interval property specifies the time period – measured in milliseconds To begin timing, set the Enabled property to True To stop timing, set the Enabled property to False The event triggered each time Timer1.Interval elapses is called Timer1.Tick. Chapter 9 - VB 2008 by Schneider 477 477
Chapter 9 - VB 2008 by Schneider Example 3: Form txtSeconds OBJECT PROPERTY SETTING tmrWatch Interval 100 Enabled False Chapter 9 - VB 2008 by Schneider 478 478
Chapter 9 - VB 2008 by Schneider Example 3: Code Private Sub btnStart_Click(...) Handles btnStart.Click txtSeconds.Text = "0" 'Reset watch tmrWatch.Enabled = True End Sub Private Sub btnStop_Click(...) Handles btnStop.Click tmrWatch.Enabled = False Private Sub tmrWatch_Tick(...) Handles tmrWatch.Tick txtSeconds.Text = CStr((CDbl(txtSeconds.Text) + 0.1)) Chapter 9 - VB 2008 by Schneider 479 479
Chapter 9 - VB 2008 by Schneider Example 3: Output Chapter 9 - VB 2008 by Schneider 480 480
Chapter 9 - VB 2008 by Schneider Pixels The graphics unit of measurement is called a pixel. To get a feel for pixel measurement, place a picture box on a form and look at the picture box’s Size property. The two numbers in the setting give the width and height of the picture box in pixels. Chapter 9 - VB 2008 by Schneider 481 481
Chapter 9 - VB 2008 by Schneider Coordinates in a Picture Box Each point in a picture box is identified by a pair of coordinates, (x, y). y pixels (x, y) x pixels Chapter 9 - VB 2008 by Schneider 482 482
Chapter 9 - VB 2008 by Schneider The Picture Box Control Designed to hold drawings and pictures To draw a blue rectangle inside the picture box with the upper left hand corner having coordinates (x, y), width w, and height h: picBox.CreateGraphics. DrawRectangle(Pens.Blue, x, y, w, h) Chapter 9 - VB 2008 by Schneider 483 483
Chapter 9 - VB 2008 by Schneider The Picture Box Control To draw a blue circle with diameter d: picBox.CreateGraphics. DrawEllipse(Pens.Blue, x, y, d, d) The numbers x and y give the coordinates of the upper-left corner of a rectangle having the circle inscribed in it. Chapter 9 - VB 2008 by Schneider 484 484
Chapter 9 - VB 2008 by Schneider Picture Box Containing a Red Circle picBox.CreateGraphics. DrawEllipse(Pens.Red, 35, 35, 70, 70) Chapter 9 - VB 2008 by Schneider 485 485
Chapter 9 - VB 2008 by Schneider Picture Box Properties A picture can be placed in a picture box control with the Image property. Prior to setting the Image property, set the SizeMode property. AutoSize will cause the picture box control to be resized to fit the picture. StretchImage will cause the picture to be resized to fit the picture box control. Chapter 9 - VB 2008 by Schneider 486 486
Chapter 9 - VB 2008 by Schneider Picture Box at Run Time A picture also can be assigned to a picture box control at run time: picBox.Image = Image.FromFile(filespec) The SizeMode property can be altered at run time with a statement such as picBox.SizeMode = PictureBoxSizeMode.AutoSize Chapter 9 - VB 2008 by Schneider 487 487
Chapter 9 - VB 2008 by Schneider The Horizontal and Vertical Scroll Bars Chapter 9 - VB 2008 by Schneider 488 488
Chapter 9 - VB 2008 by Schneider Scroll Bar Behavior When the user clicks on one of the arrow buttons, the scroll box moves a small amount toward that button. When the user clicks between the scroll box and one of the arrow buttons, the scroll box moves a large amount toward that button. The user can also move the scroll box by dragging it. Chapter 9 - VB 2008 by Schneider 489 489
Chapter 9 - VB 2008 by Schneider Scroll Bar Properties The main properties of a scroll bar control are Minimum Maximum Value SmallChange, LargeChange hsbBar.Value, a number between hsbBar.Minimum and hsbBar.Maximum, gives the location of the scroll box, hsbBar.Value is a number between hsbBar.Minimum and hsbBar.Maximum determined by the position of the left of the scroll box. If the left side of the scroll box is halfway between the two arrows, then hsbBar.Value is a number halfway between hsbBar.Minimum and hsbBar.Maximum. Chapter 9 - VB 2008 by Schneider 490 490
Chapter 9 - VB 2008 by Schneider Scroll Bar Notes The setting for the Minimum property must be less than the setting for the Maximum property. The Minimum property determines the values for the left and top arrow buttons. The Maximum property determines the values for the right and bottom arrow buttons. The Scroll event is triggered whenever any part of the scroll bar is clicked. Chapter 9 - VB 2008 by Schneider 491 491
Chapter 9 - VB 2008 by Schneider 9.3 Four Additional Objects The Clipboard Object The Random Class The MainMenu Control Multiple Forms Chapter 9 - VB 2008 by Schneider 492 492
Chapter 9 - VB 2008 by Schneider The Clipboard Object Used to copy information from one place to another Maintained by Windows, so it can even be used with programs outside Visual Basic A portion of memory that has no properties or events Chapter 9 - VB 2008 by Schneider 493 493
Chapter 9 - VB 2008 by Schneider Using the Clipboard Object To place something in the Clipboard: Clipboard.SetText(str) To get something out of the Clipboard: str = Clipboard.GetText To delete the contents of the Clipboard: Clipboard.SetText("") Chapter 9 - VB 2008 by Schneider 494 494
Chapter 9 - VB 2008 by Schneider The Random Class A random number generator declared with the statement: Dim randomNum As New Random() If m and n are whole numbers and m < n then the following generates a whole number between m and n (including m, but excluding n) randomNum.Next(m, n) Chapter 9 - VB 2008 by Schneider 495 495
Chapter 9 - VB 2008 by Schneider Example 1 Private Sub btnSelect_Click(...) Handles _ btnSelect.Click 'Display three randomly chosen digits Dim randomNum As New Random() Dim num1, num2, num3 As Integer num1 = randomNum.Next(0, 10) num2 = randomNum.Next(0, 10) num3 = randomNum.Next(0, 10) txtNumbers.Text = num1 & " " & num2 & " " & num3 End Sub Chapter 9 - VB 2008 by Schneider 496 496
Chapter 9 - VB 2008 by Schneider Example 1: Output Chapter 9 - VB 2008 by Schneider 497 497
The MenuStrip Control Used to create menus like the following: Top-level menu Second-level menu Chapter 9 - VB 2008 by Schneider 498 498
Chapter 9 - VB 2008 by Schneider Menu Events Each menu item responds to the Click event Click event is triggered by the mouse Alt + access key Shortcut key Chapter 9 - VB 2008 by Schneider 499 499
Chapter 9 - VB 2008 by Schneider Multiple Forms Visual Basic programs can contain more than one form To add the new form, select Add Windows Form from the Project menu, to invoke the Add New Items dialog box. Chapter 9 - VB 2008 by Schneider 500 500
Chapter 9 - VB 2008 by Schneider Add New Items dialog box Chapter 9 - VB 2008 by Schneider 501 501
Chapter 9 - VB 2008 by Schneider Add New Items dialog box Select Windows Form from the Installed Templates pane. Optionally type in a name. Press the Add button. Chapter 9 - VB 2008 by Schneider 502 502
Chapter 9 - VB 2008 by Schneider Solution Explorer Both forms will be accessible through Solution Explorer. Chapter 9 - VB 2008 by Schneider 503 503
Chapter 9 - VB 2008 by Schneider Variables and Multiple Forms Variables declared in the Declarations section of a form with Public, instead of Dim, will be available to all forms in the program. When a Public variable is used in another form, it is referred to by an expression such as secondForm.variableName Chapter 9 - VB 2008 by Schneider 504 504
Chapter 9 - VB 2008 by Schneider Example 3: frmIncome txtTotIncome Chapter 9 - VB 2008 by Schneider 505 505
Example 3: frmSources FormBorderStyle property set to FixedDialog Chapter 9 - VB 2008 by Schneider 506 506
Chapter 9 - VB 2008 by Schneider Example 3: frmIncome’s Code Private Sub btnDetermine_Click(...) Handles _ btnDetermine.Click 'Instantiate the second form Dim secondForm As New frmSources() secondForm.ShowDialog() 'Show the second 'form and wait until it closes. Then execute 'the rest of the code in this procedure. txtTotIncome.Text = _ FormatCurrency(secondForm.sum) End Sub Chapter 9 - VB 2008 by Schneider 507 507
Chapter 9 - VB 2008 by Schneider Example 3: frmSource’s Code Public sum As Double 'Holds the sum of the 'text boxes' values Private Sub btnCompute_Click(...) Handles _ btnCompute.Click 'Store total into the Public variable sum sum = CDbl(txtWages.Text) + _ CDbl(txtIntIncome.Text) + _ CDbl(txtDivIncome.Text) 'Close the form as it is not needed anymore Me.Close() End Sub Chapter 9 - VB 2008 by Schneider 508 508
Chapter 9 - VB 2008 by Schneider 9.4 Graphics Graphics Objects Lines, Rectangles, Circles, and Sectors Pie Charts Bar Charts Animation Chapter 9 - VB 2008 by Schneider 509 509
Dim gr As Graphics = picBox.CreateGraphics Graphics Objects Our objective is to draw bar charts and pie charts in a picture box. A statement of the form Dim gr As Graphics = picBox.CreateGraphics declares gr to be a Graphics object for the picture box picBox. Chapter 9 - VB 2008 by Schneider 510 510
Chapter 9 - VB 2008 by Schneider Pixels The graphics unit of measurement is called a pixel. To get a feel for pixel measurement, place a picture box on a form and look at the picture box’s Size property. The two numbers in the setting give the width and height in pixels. Chapter 9 - VB 2008 by Schneider 511 511
Chapter 9 - VB 2008 by Schneider Coordinates in a Picture Box Each point in a picture box is identified by a pair of coordinates, (x, y). y pixels (x, y) x pixels Chapter 9 - VB 2008 by Schneider 512 512
Chapter 9 - VB 2008 by Schneider Display Text in Picture Box Dim gr As Graphics = picBox.CreateGraphics gr.DrawString(string, Me.Font, _ Brushes.Color, x, y) Displays string in the picture box. The upper- left corner of the text has coordinates (x, y), the font used is the Form’s font, and the color of the text is specified by color. Note: IntelliSense will provide a list of colors. Chapter 9 - VB 2008 by Schneider 513 513
Chapter 9 - VB 2008 by Schneider Display Text Dim gr As Graphics = picBox.CreateGraphics Dim strVar As String = "Hello" gr.DrawString(strVar, Me.Font, Brushes.Blue, 4, 30) gr.DrawString("World",Me.Font, Brushes.Red, 35, 50) Chapter 9 - VB 2008 by Schneider 514 514
Chapter 9 - VB 2008 by Schneider Draw a Line in a Picture Box Dim gr As Graphics = picBox.CreateGraphics gr.DrawLine(Pens.Color, x1, y1, x2, y2) draws a line in the specified color from (x1, y1) to (x2, y2). Note: IntelliSense will provide a list of colors. Chapter 9 - VB 2008 by Schneider 515 515
Chapter 9 - VB 2008 by Schneider Draw a Line Dim gr As Graphics = picBox.CreateGraphics gr.DrawLine(Pens.Blue, 50, 20, 120, 75) Chapter 9 - VB 2008 by Schneider 516 516
Chapter 9 - VB 2008 by Schneider Draw a Solid Rectangle in a Picture Box Dim gr As Graphics = picBox.CreateGraphics gr.FillRectangle(Brushes.Color, x, y, w, h) draws a solid rectangle of width w and height h in the color specified and having the point with coordinates (x, y) as its upper-left corner. Note: IntelliSense will provide a list of colors. Chapter 9 - VB 2008 by Schneider 517 517
Chapter 9 - VB 2008 by Schneider Draw a Solid Rectangle in a Picture Box Dim gr As Graphics = picBox.CreateGraphics gr.FillRectangle(Brushes.Blue, 50, 20, 70, 55) Chapter 9 - VB 2008 by Schneider 518 518
Chapter 9 - VB 2008 by Schneider Draw a Solid Ellipse in a Picture Box Dim gr As Graphics = picBox.CreateGraphics gr.FillEllipse(Brushes.Color, x, y, w, h) draws a solid ellipse in the color specified inscribed in the rectangle described by the values x, y, w, and h. Note: When w = h, the ellipse is a circle. This is the only type of ellipse we will consider. Chapter 9 - VB 2008 by Schneider 519 519
Draw a Solid Ellipse The statement gr.FillEllipse(Brushes.Color, _ a - r, b - r, 2 * r, 2 * r) draws a solid circle in the color specified with center (a, b) and radius r. For example, gr.FillEllipse(Brushes.Blue, _ 80 - 40, 50 - 40, 2 * 40, 2 * 40) Draws a solid blue circle of radius 40 and center (80, 50). 520 520
Chapter 9 - VB 2008 by Schneider A Sector of a Circle A sector of a circle (shown below as upper-left sector) is specified by two angles, θ1 (the start angle) and θ2 (the sweep angle). Chapter 9 - VB 2008 by Schneider 521 521
Chapter 9 - VB 2008 by Schneider Start and Sweep Angles Chapter 9 - VB 2008 by Schneider 522 522
Chapter 9 - VB 2008 by Schneider Draw a Sector The statement gr.FillPie(Brushes.Color, a - r, b - r, _ 2 * r, 2 * r, startAngle, sweepAngle) draws a solid sector of a circle with center (a, b), radius r, and having the specified startAngle and sweepAngle. The color of the sector is determined by the value of Color. Chapter 9 - VB 2008 by Schneider 523 523
Chapter 9 - VB 2008 by Schneider Brushes, Pens, and Fonts Variables can be used for brushes, pens, and fonts. For example, the statement gr.FillRectangle(Brushes.Blue, 50,20,70,55) can be replaced with Dim br As Brush = Brushes.Blue gr.FillRectangle(br, 50, 20, 70, 55) Chapter 9 - VB 2008 by Schneider 524 524
Chapter 9 - VB 2008 by Schneider Single Data Type Numeric variables used in Draw and Fill statements must be of type Integer or Single. The Single data type is similar to the Double type, but has a smaller range (-3.4∙1038 to 3.4∙1038). CSng converts other data types to the Single data type. Chapter 9 - VB 2008 by Schneider 525 525
Chapter 9 - VB 2008 by Schneider Financing Public Schools Data Amount (in billions) Percent Federal $33 8% State $206 49% Local $180 43% Chapter 9 - VB 2008 by Schneider 526 526
Chapter 9 - VB 2008 by Schneider Financing Public Schools Pie Chart Chapter 9 - VB 2008 by Schneider 527 527
Chapter 9 - VB 2008 by Schneider Create the Pie Chart Dim gr As Graphics = picBox.CreateGraphics Dim percent() As Single = {.08, .49, .43} Dim br() As Brush = {Brushes.Blue, _ Brushes.Red, Brushes.Tan} Dim sumOfSweepAngles As Single = 0 For i As Integer = 0 To 2 gr.FillPie(br(i), 5, 5, 200, 200, _ sumOfSweepAngles, percent(i) * 360) sumOfSweepAngles += percent(i) * 360 Next Chapter 9 - VB 2008 by Schneider 528 528
Chapter 9 - VB 2008 by Schneider Financing Public Schools Bar Chart Chapter 9 - VB 2008 by Schneider 529 529
Chapter 9 - VB 2008 by Schneider Financing Public Schools Bar Chart Suppose the x-axis is 110 pixels below the top of the picture box. Let the unit for the rectangle heights be .5 pixels. Then the top of a rectangle corresponding to the quantity q is 110 – q/2 pixels from the top of the picture box. Chapter 9 - VB 2008 by Schneider 530 530
Chapter 9 - VB 2008 by Schneider Create the Bar Chart Dim gr As Graphics = picBox.CreateGraphics Dim quantity() As Single = {33, 206, 180} 'Draw x-axis gr.DrawLine(Pens.Black, 40, 110, 210, 110) 'Draw y-axis gr.DrawLine(Pens.Black, 40, 110, 40, 0) For i As Integer = 0 To 2 gr.FillRectangle(Brushes.Blue, _ 60 + i * 40, (110 – quantity(i) / 2), _ 20, quantity(i) / 2) Next Chapter 9 - VB 2008 by Schneider 531 531
Chapter 9 - VB 2008 by Schneider Animation Place an image into a picture box, and move the picture box a small distance with each tick of a Timer control. Chapter 9 - VB 2008 by Schneider 532 532
Chapter 9 - VB 2008 by Schneider Move Ball The following code moves the ball along a diagonal with each tick of the timer. Private Sub Timer1_Tick(...) Handles _ Timer1.Tick picBall.Left += 1 picBall.Top += 1 End Sub Chapter 9 - VB 2008 by Schneider 533 533
Chapter 10 – Database Management 10.1 An Introduction to Databases 10.2 Relational Databases and SQL Ch. 10 - VB 2008 by Schneider 534 534
10.1 An Introduction to Databases Database Explorer Accessing a Database with a Data Table Binding a List Box to a Data Table Importing an Existing Database into a program Ch. 10 - VB 2008 by Schneider 535 535
Sample Table – Cities Table Ch. 10 - VB 2008 by Schneider 536 536
Sample Table – Countries Table Ch. 10 - VB 2008 by Schneider 537 537
Database Terminology A table is a rectangular array of data. Each column of the table, called a field, contains the same type of information. Each row, called a record, contains all the information about one entry in the database. Ch. 10 - VB 2008 by Schneider 538 538
Database Management Software (DBMS) Used to create databases Databases can contain one or more related tables Examples of DBMS include Access and Oracle Ch. 10 - VB 2008 by Schneider 539 539
Database Explorer A tool provided by Visual Basic Express to examine any database. Invoked from the View menu Allows you to determine the names of the tables (and their fields) and view the contents of any table. Other edition of Visual Basic provide an analogous tool called Server Explorer. Ch. 10 - VB 2008 by Schneider 540 540
Databases Provided The Add Connection dialog box is used by Database Explorer to connect to a database. The databases used in this book can be found in the folder Programs\Ch10\MajorDatabases. Ch. 10 - VB 2008 by Schneider 541 541
Add Connection Dialog Box 542 542
Database Explorer Window after Connection to MEGACITIES.MDB 543 543
Cities Table as Displayed by Database Explorer 544 544
Data Table Object A DataTable object holds the contents of a table as a rectangular array. A data table is similar to a two- dimensional array; it has rows and columns. Ch. 10 - VB 2008 by Schneider 545 545
DataTable Variable The following declares a DataTable variable Dim dt As New DataTable() Ch. 10 - VB 2008 by Schneider 546 546
(Boilerplate to be inserted into every program in chapter.) Connecting with a DataTable Dim dt As New DataTable() Dim connStr As String = _ "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=MEGACITIES.MDB" Dim sqlStr As String = "SELECT * FROM Cities" Dim dataAdapter As New _ OleDb.OleDbDataAdapter(sqlStr, connStr) dataAdapter.Fill(dt) dataAdapter.Dispose() (Boilerplate to be inserted into every program in chapter.) Ch. 10 - VB 2008 by Schneider 547 547
Properties of the DataTable After the six lines of boilerplate code are executed, the number of records in the table is given by dt.Rows.Count The number of columns in the table is given by dt.Columns.Count The records are numbered 0 through dt.Rows.Count – 1 The fields are numbered 0 through dt.Columns.Count – 1 Ch. 10 - VB 2008 by Schneider 548 548
More Properties The name of the jth field is given by dt.Columns(j) The entry in the jth field of the ith record is dt.Rows(i)(j) The entry in the specified field of the ith record is dt.Rows(i)(fieldName) Ch. 10 - VB 2008 by Schneider 549 549
Example 1: Form Display one record at a time from the Cities table. Ch. 10 - VB 2008 by Schneider 550 550
Example 1: Partial Code Dim dt As New DataTable() Dim rowIndex As Integer = 0 Private Sub frmCities_Load(...) Handles _ MyBase.Load (Last five statements of boilerplate) UpdateTextBoxes() End Sub Sub UpdateTextBoxes() 'Display contents of row specified by rowIndex variable txtCity.Text = CStr(dt.Rows(rowIndex)("city")) txtCountry.Text = CStr(dt.Rows(rowIndex)("country")) txtPop2005.Text = CStr(dt.Rows(rowIndex)("pop2005")) txtPop2015.Text = CStr(dt.Rows(rowIndex)("pop2015")) Ch. 10 - VB 2008 by Schneider 551 551
Example 1: Partial Code cont. Private Sub btnNext_Click(...) Handles btnNext.Click 'Show the next record if current one is not the last If (rowIndex < dt.Rows.Count - 1) Then rowIndex += 1 'Increase rowIndex by 1 UpdateTextBoxes() End If End Sub Private Sub btnPrevious_Click(...) Handles _ btnPrevious.Click 'Show previous record if current one is not the first If (rowIndex > 0) Then rowIndex = rowIndex - 1 Ch. 10 - VB 2008 by Schneider 552 552
Example 1: Partial Code cont. Private Sub btnFind_Click(...) Handles btnFind.Click Dim cityName As String Dim cityFound As Boolean = False cityName=InputBox("Enter name of city to search for.") For i As Integer = 0 To (dt.Rows.Count - 1) If CStr(dt.Rows(i)("city")) = cityName Then cityFound = True rowIndex = i UpdateTextBoxes() End If Next If (Not cityFound) Then MessageBox.Show("Cannot find requested city") End Sub Ch. 10 - VB 2008 by Schneider 553 553
Example 1: Output Ch. 10 - VB 2008 by Schneider 554 554
Example 2: Form Display Cities table along with percentage growth. Ch. 10 - VB 2008 by Schneider 555 555
Example 2: Code Private Sub btnShow_Click(...) Handles btnShow.Click Dim fmtStr As String="{0,-15}{1,-10}{2,7:N1}{3,7:N1}{4,7:P0}" Dim percentIncrease As Double (Six statements of boilerplate) lstDisplay.Items.Add(String.Format(fmtStr, "CITY", _ "COUNTRY", "2005", "2015", "INCR.")) For i As Integer = 0 To dt.Rows.Count - 1 percentIncrease = (CDbl(dt.Rows(i)("pop2015")) - _ CDbl(dt.Rows(i)("pop2005"))) / CDbl(dt.Rows(i)("pop2005")) lstDisplay.Items.Add(String.Format(fmtStr, dt.Rows(i)(0), _ dt.Rows(i)(1),dt.Rows(i)(2),dt.Rows(i)(3),percentIncrease)) Next End Sub Ch. 10 - VB 2008 by Schneider 556 556
Example 2: Output Ch. 10 - VB 2008 by Schneider 557 557
Bound Controls A data table that is bound to a list box can transfer information automatically into the list box. The following statement binds a list box to a data table: lstBox.DataSource = dt The contents of a specified field can be displayed in the list box by: lstBox.DisplayMember = "country" Ch. 10 - VB 2008 by Schneider 558 558
Example 3: Form Display the list of countries. When the user clicks on a country, its monetary unit should be displayed. Ch. 10 - VB 2008 by Schneider 559 559
Example 3: Code Dim dt As New DataTable() Private Sub frmCountries_Load(...) Handles MyBase.Load (Last five statements of boilerplate) lstCountries.DataSource = dt 'Bind list box lstCountries.DisplayMember = "country" End Sub Private Sub lstCountries_SelectedIndexChanged(...) _ Handles lstCountries.SelectedIndexChanged txtMonetaryUnit.Text = _ CStr(dt.Rows(lstCountries.SelectedIndex)("monetaryUnit") Ch. 10 - VB 2008 by Schneider 560 560
Example 3: Output Ch. 10 - VB 2008 by Schneider 561 561
Chapter 3 - VB 2008 by Schneider Importing a Database Highlight program name in Solution Explorer Click on “Add Existing Item” in Project menu Locate database file and double-click on it. (File will appear in Solution Explorer.) Move file to Debug subfolder of bin folder. Chapter 3 - VB 2008 by Schneider 562 562
10.2 Relational Databases and SQL Primary and Foreign Keys SQL Four SQL Requests The DataGridView Control Changing the Contents of a Database Calculated Columns with SQL Ch. 10 - VB 2008 by Schneider 563 563
Primary Keys A primary key is used to uniquely identify each record. Databases of student enrollments in a college usually use a field of Social Security numbers as the primary key. Why wouldn't names be a good choice as a primary key? Ch. 10 - VB 2008 by Schneider 564 564
Primary Key Fields Specified when database is created. Every record must have an entry in the primary-key field. Two records cannot have the same entry in the primary-key field. This pair of requirements is called the Rule of Entity Integrity. Ch. 10 - VB 2008 by Schneider 565 565
Two or More Tables When a database contains two or more tables, the tables are usually related. For instance, the two tables Cities and Countries are related by their country field. Notice that every entry in Cities.country appears uniquely in Countries.country and Countries.country is a primary key. We say that Cities.country is a foreign key of Countries.country. Ch. 10 - VB 2008 by Schneider 566 566
Foreign Keys Foreign keys can be specified when a table is first created. Visual Basic will insist on the Rule of Referential Integrity. This Rule says that each value in the foreign key must also appear in the primary key of the other table. Ch. 10 - VB 2008 by Schneider 567 567
Join A foreign key allows Visual Basic to link (or join) together two tables from a relational database When the two tables Cities and Countries from MEGACITIES.MDB are joined based on the foreign key Cities.country, the result is the table in the next slide. The record for each city is expanded to show its country’s population and its monetary unit. Ch. 10 - VB 2008 by Schneider 568 568
A Join of Two Tables Ch. 10 - VB 2008 by Schneider 569 569
SQL Structured Query Language developed for use with relational databases Very powerful language Allows for the request of specified information from a database Allows displaying of information from database in a specific format Ch. 10 - VB 2008 by Schneider 570 570
Four SQL Requests Show the records of a table in a specified order or SELECT * FROM Table1 ORDER BY field1 ASC or SELECT * FROM Table1 ORDER BY field1 DESC Specifies ASCending Or DESCending * means "all fields" Ch. 10 - VB 2008 by Schneider 571 571
Show just the records that meet certain criteria * means "all fields" Specified Criteria SELECT * FROM Table1 WHERE criteria Name of the table where the records are found Ch. 10 - VB 2008 by Schneider 572 572
Join the tables together connected by a foreign key, and present the records as in previous requests SELECT * FROM Table1 INNER JOIN Table2 ON foreign field = primary field WHERE criteria Ch. 10 - VB 2008 by Schneider 573 573
Make available just some of the fields of either the basic tables or the joined table. SELECT field1, field2, . . ., fieldN FROM Table1 WHERE criteria Ch. 10 - VB 2008 by Schneider 574 574
Criteria Clause A string containing a condition of the type used with If blocks. Uses the standard operators <, >, and = Also can use the operator LIKE. LIKE uses the wildcard characters “_” and “%” to compare a string to a pattern. Ch. 10 - VB 2008 by Schneider 575 575
Examples using LIKE An underscore character stands for a single character in the same position as the underscore character. The pattern “B_d” is matched by “Bid”, “Bud”, and “Bad”. A percent sign stands for any number of characters in the same position as the asterisk. The pattern “C%r” is matched by “Computer”, “Chair”, and “Car”. Ch. 10 - VB 2008 by Schneider 576 576
SELECT Clause SELECT fields FROM clause fields is either * (to indicate all fields) or a sequence of the fields to be available (separated by commas) clause is either a single table or a join of two tables Ch. 10 - VB 2008 by Schneider 577 577
Join clause A join of two tables is indicated by a clause of the form table1 INNER JOIN table2 ON foreign key of table1=primary key of table2 Appending WHERE criteria to the end of the sentence restricts the records to those satisfying criteria. Appending ORDER BY field(s) ASC (or DESC) presents the records ordered by the specified field or fields. Ch. 10 - VB 2008 by Schneider 578 578
General SQL statements SELECT www FROM xxx WHERE yyy ORDER BY zzz SELECT www FROM xxx is always present May be accompanied by one or both of WHERE yyy and ORDER BY zzz. The xxx portion might contain an INNER JOIN phrase. Ch. 10 - VB 2008 by Schneider 579 579
More on SQL statements The single quote, rather than the normal double quote, is used to surround strings. Fields may be specified with the table they come from by tableName.fieldName Ch. 10 - VB 2008 by Schneider 580 580
Virtual Tables SQL statements create a new “virtual” table from existing tables. SELECT city, pop2015 FROM Cities WHERE pop2015>=20 Results in “virtual” table city pop2015 Bombay 22.6 Delhi 20.9 Mexico City 20.6 Sao Paulo 20.0 Tokyo 36.2 581 581
Another Virtual Table SELECT * FROM Countries WHERE country LIKE 'I%' ORDER BY pop2005 ASC Results in “virtual” table country pop2005 monetaryUnit Indonesia 222.8 rupiah India 103.4 rupee Ch. 10 - VB 2008 by Schneider 582 582
Views “Virtual” tables don’t exist physically. For all practical purposes, Visual Basic acts as if they did. You may also see a “virtual” table called a view. Ch. 10 - VB 2008 by Schneider 583 583
The DataGridView Control The DataGridView, displays the values for an entire view in a table format similar to the table displayed by Database Explorer. The prefix for the name of a DataGridView control is dgv. After a data table has been filled, the statement dgvDisplay.DataSource = dt displays the contents of the data table dt. Ch. 10 - VB 2008 by Schneider 584 584
Example 1: Form dgvDisplay Ch. 10 - VB 2008 by Schneider 585 585
Example 1: Code Private Sub frmCities_Load(...) Handles MyBase.Load UpdateGrid("Select * From Cities") End Sub Private Sub btnOrderbyPop_Click(...) Handles btnOrderbyPop.Click UpdateGrid("Select * From Cities Order By pop2005 ASC") Private Sub btnShowMonUnit_Click(...) _ Handles btnShowMonUnit.Click UpdateGrid("SELECT city, Cities.country, " & _ "Cities.pop1995, monetaryUnit " & _ "FROM Cities INNER JOIN Countries " & _ "ON Cities.country=Countries.country " & _ "ORDER BY city ASC") Ch. 10 - VB 2008 by Schneider 586 586
Example 1: Code continued Sub UpdateGrid(ByVal sqlStr As String) Dim dt As New DataTable() Dim connStr As String ="Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source = MEGACITIES.MDB" Dim dataAdapter As New OleDb.OleDbDataAdapter(sqlStr, connStr) dataAdapter.Fill(dt) dataAdapter.Dispose() dgvDisplay.DataSource = dt End Sub Ch. 10 - VB 2008 by Schneider 587 587
Click on the “Show Monetary Unit” button. Example 1: Output Click on the “Show Monetary Unit” button. 588 588
Example 2: Form txtCountry dgvDisplay Ch. 10 - VB 2008 by Schneider 589 589
Example 2: Code Private Sub btnFindCities_Click(...) _ Handles btnFindCities.Click UpdateGrid("SELECT city FROM Cities WHERE" & _ "country = '" & txtCountry.Text & _ "' ORDER BY city ASC") End Sub Sub UpdateGrid(ByVal sqlStr As String) (Boilerplate, except for Dim sqlStr statement) If dt.Rows.Count = 0 Then MessageBox.Show("No cities from that country " & _ "in the database") Else dgvDisplay.DataSource = dt End If Ch. 10 - VB 2008 by Schneider 590 590
Example 2: Output Ch. 10 - VB 2008 by Schneider 591 591
Changing the Contents of a Database Data grid views can also be used to add, modify, and delete records from a database. After a DataAdapter has been created, the statement Dim commandBuilder As New _ OleDbCommandBuilder(dataAdapter) will automatically generate the commands used for the Insert, Update, and Delete operations. Ch. 10 - VB 2008 by Schneider 592 592
Using the DataAdapter to Change a Database If changes is an Integer variable, then the statement changes = dataAdapter.Update(dt) will store all of the insertions, updates, and deletions made in the data table to the database and assign the number of records changed to the variable changes. Ch. 10 - VB 2008 by Schneider 593 593
Example 3: Form dgvDisplay Ch. 10 - VB 2008 by Schneider 594 594
Example 3: Partial Code Dim connStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=MEGACITIES.MDB" Dim sqlStr As String = "SELECT * FROM Cities" Dim dt As New DataTable() Private Sub btnLoad_Click(...) Handles btnLoad.Click dt.Clear() Dim dataAdapter As New OleDb.OleDbDataAdapter(sqlStr, connStr) dataAdapter.Fill(dt) dataAdapter.Dispose() dgvDisplay.DataSource = dt End Sub Ch. 10 - VB 2008 by Schneider 595 595
Example 3: Code continued Private Sub btnSave_Click(...) Handles btnSave.Click Dim changes As Integer Dim dataAdapter As New OleDb.OleDbDataAdapter(sqlStr, connStr) Dim commandBuilder As New _ OleDb.OleDbCommandBuilder(dataAdapter) changes = dataAdapter.Update(dt) dataAdapter.Dispose() If changes > 0 Then MessageBox.Show(changes & " changed rows.") Else MessageBox.Show ("No changes made.") End If End Sub Ch. 10 - VB 2008 by Schneider 596 596
Calculated Columns with SQL In the SQL statement SELECT field1, field2,..., fieldN FROM Table1 one of the field listings can be an expression involving other fields, followed by a clause of the form “AS header”. If so, a new column will be created whose values are determined by the expression and having the stated header. For instance, using sqlStr = "SELECT city, Round(pop2015-pop2005, 1)" & _ "AS popGrowth FROM Cities" to fill the table produces the output shown in the next slide. Ch. 10 - VB 2008 by Schneider 597 597
Calculated Columns with SQL Ch. 10 - VB 2008 by Schneider 598 598
Comments SQL statements are case insensitive. When the LIKE operator is used, the “pattern” must appear on the right of the operator. SELECT * FROM Cities WHERE city LIKE 'S%' cannot be replaced with SELECT * FROM Cities WHERE 'S%' LIKE city An expression such as “[letter1-letter2]” is a placeholder for any letter from letter1 to letter2. Ch. 10 - VB 2008 by Schneider 599 599