Download presentation
Presentation is loading. Please wait.
Published byDana Gilmore Modified over 6 years ago
1
Required Books An Introduction to Programming Using Visual Basic 2010, (w/VS2010 DVD), 8/E, D.I. Schneider , Prentice-Hall, 2010 Text comes with DVD to install VB at home
2
Academic Honesty Statement
Academic honesty plays a key role in our efforts to maintain a high standard of academic excellence and integrity. Students are advised that ALL acts of intellectual dishonesty will be handled in accordance with the SFU Academic Honesty and Student Conduct Policies ( Students are also encouraged to read the School's policy information page ( Cheaters will be caught 0.
3
Syllabus
4
Syllabus
5
Your background? Any programming? “Expert” at Windows?
Excel formulas (if, lookup, …)? Installing programs?
6
Chapter 1 - Intro Chapter 1
7
Chapter 1 - An Introduction to Computers and Problem Solving
1.2 Windows, Folders, and Files 1.3 Program Development Cycle 1.4 Programming Tools
8
Communicating with the Computer
Machine language low level, hard for humans to understand Visual Basic high level, understood by humans, consists of instructions such as Click, If, Do Usable in other applications (Word, Excel…)
9
Computers and Complicated Tasks
Tasks are broken down into instructions that can be expressed by a computer language A program is a sequence of instructions Programs can be only a few instructions or millions of lines of instructions Examples? In real life? In computers?
10
All Programs Have in Common
Take data and manipulate it to produce a result Input – Process – Output Input Output
11
Hardware and Software Hardware Software
The physical components of a computer Keyboard Disk drive Monitor Software The instructions that tell the computer what to do
12
Programmer and User Programmer – the person who solves the problem and writes the instructions for the computer User – any person who uses the program written by the programmer
13
Problem Solving Developing the solution to a problem
Algorithm – a step by step series of instructions to solve a problem
14
Problem Solving Problems are solved by carefully reading them to determine what data are given and what outputs are requested Then a step-by-step procedure is devised to process the given data and produce the requested output This procedure is called an algorithm Finally, a computer program is written to carry out the algorithm Problems are solved by carefully reading them to determine what data are given and what outputs are requested. Then a step-by-step procedure is devised to process the given data and produce the requested output. This procedure is called an algorithm. Finally, a computer program is written to carry out the algorithm. Algorithms are discussed in Section 2.2.
15
Visual Basic 2010 BASIC originally developed at Dartmouth in the early 1960s Visual Basic created by Microsoft in 1991 Visual Basic 2010 is similar to original Visual Basic, but more powerful
16
XP versus Vista Windows XP Windows Vista
17
1.2 Windows, Folders, and Files
Windows and Its Little Windows Mouse Actions Files and Folders
18
Windows and Its Little Windows
Difference between Windows and windows. Title bar indicates if window is active.
19
Mouse Actions Clicking (single-clicking) means pressing and releasing the left mouse button once. Double-clicking means clicking the left mouse button twice in quick succession 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. 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
20
Mouse Actions 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 Dragging usually moves a Windows object. If you see a sentence that begins “Drag the ”, you need to click on the object and hold 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
21
Files and Folders File: holds programs or data. Its name usually consists of letters, digits, and spaces. Folder: contains files and other folders (called subfolders). Think of a disk as a large folder that contains several smaller folders each with its own name. The naming of folders follow th same rule as naming files Each folder is identified by listing its name preceded by a backslash A filespec typically includes the drive, path and the filename. File is identified by a small directory or folder is identified by a folder icon executable file: is identified by a rectangle with a thin bar across top Go over: How to create a folder to rename a folder to delete a folder or file to Copy a folder or file To move a folder or file
22
Key Terms in using Folders and Files
Example Disk Hard disk, CD File name PAYROLL Extension .TXT Filename PAYROLL.TXT Path TextFiles\PAYROLL.TXT Filespec C:\TextFiles\PAYROLL.TXT Think of a disk as a large folder that contains several smaller folders each with its own name. The naming of folders follow th same rule as naming files Each folder is identified by listing its name preceded by a backslash A filespec typically includes the drive, path and the filename. File is identified by a small directory or folder is identified by a folder icon executable file: is identified by a rectangle with a thin bar across top Go over: How to create a folder to rename a folder to delete a folder or file to Copy a folder or file To move a folder or file
23
Windows Explorer Used to view, organize and manage folders and files.
Manage: copy, move, delete
24
Biographical History of Computing
Chapter 1
25
1800s George Boole – devised Boolean algebra
Charles Babbage – created "analytical engine“ Augusta Ada Byron – first computer programmer Herman Hollerith – founder of company that would become IBM
26
1930s Alan Turing – deciphered German code in WWII; father of artificial intelligence John V. Atanasoff – inventor of first electronic digital special purpose computer
27
1940s Howard Aiken – built large scale digital computer, Mark I
Grace M. Hopper – originated term "debugging"; pioneered development and use of COBOL John Mauchley and J. Presper Eckert – built first large scale general purpose computer, ENIAC
28
1940s continued John von Neumann – developed stored program concept
Maurice V. Wilkes – built EDSAC, first computer to use stored program concept John Bardeen, Walter Brattain, and William Shockley – developed transistor that replaced vacuum tubes
29
1950s John Backus – created Fortran; early user of interpreters and compilers Reynold B. Johnson – invented the disk drive Donald L. Shell – developed efficient sorting algorithm
30
1960s John G. Kemeny and Thomas E. Kurtz – invented BASIC
Corrado Bohm and Guiseppe Jacopini – proved that any program can be written with only 3 structures: sequence, decision, and loops Edsger W. Dijkstra – stimulated move to structured programming by declaring "GOTO" harmful
31
1960s continued Harlan B. Mills – advocated use of structured programming Donald E. Knuth – wrote definitive work on algorithms. Ted Hoff, Stan Mazer, Robert Noyce, and Frederico Faggin – developed first microprocessor
32
1960s continued Douglas Engelbart – invented computer mouse
33
1970s Ted Codd - software architect; laid the groundwork for relational databases Paul Allen and Bill Gates - cofounders of Microsoft Corporation Stephen Wozniak and Stephen Jobs - cofounders of Apple Computer Inc. Dan Bricklin and Dan Fylstra - wrote VisiCalc, the first electronic spreadsheet program
34
1970s continued Dennis Ritchie - creator of the C programming language. Ken Thompson - created the Unix operating system Alan Kay – developer of Smalltalk, a pure object- oriented language Don Chamberlain - created a database programming language, later known as SQL,
35
1980s Phillip “Don” Estridge - at IBM directly responsible for the success of the personal computer. Mitchell D. Kapor - cofounder of Lotus Corporation Tom Button - group product manager for applications programmability at Microsoft; headed the team that developed QuickBasic, QBasic, and Visual Basic.
36
1980s continued Alan Cooper - considered the father of Visual Basic.
Tim Berners–Lee - father of the World Wide Web. Charles Simonyi - father of Word. Bjarne Stroustrup - creator of the C++ programming language. Richard M. Stallman - founded Free Software Foundation
37
1990s Marc Andreessen - inventor of the Web browser.
James Gosling – creator of Java. Linus Torvalds - developed the popular Linux operating system.
38
2000s Sergey M. Brin and Lawrence E. Page – founders of Google
Mark Zuckerberg – founder of Facebook. Steve Chen, Chad Hurley, and Jawed Karim – founders of YouTube.
39
1.3 Program Development Cycle
Performing a Task on the Computer Program Planning
40
Terminology tip A computer program may also be called: Project
Application Solution
41
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 Take big problem, break it down Break it down further Repeat until you get to very fundamental steps
42
Performing a Task on the Computer
Determine Output Identify Input Determine process necessary to turn given Input into desired Output
43
Pictorial representation of the problem solving process
44
Problem-solving: approach like algebra class
How fast is a car traveling if it goes 50 miles in 2 hours? Output: Input: Process:
45
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
46
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
47
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.). 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.
48
Documentation Why is documentation important? 48
49
1.4 Programming Tools Flowcharts Pseudocode Hierarchy Chart
Direction of Numbered NYC Streets Algorithm Class Average Algorithm
50
Programming Tools Three tools are used to convert algorithms into computer programs: Flowchart - Graphically depicts the logical steps to carry out a task and shows how the steps relate to each other. Pseudocode - Uses English-like phrases with some Visual Basic terms to outline the program. Hierarchy chart - Shows how the different parts of a program relate to each other.
51
Problem solving example
How many stamps do you use when mailing a letter? One rule of thumb is to use one stamp for every five sheets of paper or fraction thereof.
52
Algorithm INPUT: 2. PROCESSING: 3. PROCESSING: 4. OUTPUT:
53
Flowcharts Graphically depict the logical steps to carry out a task and show how the steps relate to each other.
54
Flowchart symbols
55
Flowchart symbols continued
56
Flowchart example
57
Pseudocode Uses English-like phrases with some Visual Basic terms to outline the task.
58
Pseudocode example Determine the proper number of stamps for a letter
Read Sheets (input) Set the number of stamps to Sheets / 5 (processing) Round the number of stamps up to the next whole number (processing) Display the number of stamps (output)
59
Hierarchy charts Show how the different parts of a program relate to each other Hierarchy charts may also be called structure charts HIPO (Hierarchy plus Input-Process-Output) charts top-down charts VTOC (Visual Table of Contents) charts All are similar to a company’s organization chart.
60
Hierarchy charts example
61
Divide-and-conquer method
Used in problem solving – take a large problem and break it into smaller problems solving the small ones first Breaks a problem down into modules
62
Statement structures Sequence – follow instructions from one line to the next without skipping over any lines Decision - if the answer to a question is “Yes” then one group of instructions is executed. If the answer is “No,” then another is executed Looping – a series of instructions are executed over and over
63
Sequence flow chart
64
Decision flow chart
65
Looping flow chart
66
Direction of Numbered NYC Streets Algorithm
Problem: Given a street number of a one-way street in New York City, decide the direction of the street, either eastbound or westbound Discussion: in New York City even numbered streets are Eastbound, odd numbered streets are Westbound
67
Flowchart
68
Pseudocode Determine the direction of a numbered NYC street Get street If street is even Then Display Eastbound Else Display Westbound End If
69
Hierarchy Chart
70
Movie Rating Example Kids want to watch the movie, “Avatar”.
Decide whether he or she can watch the movie based on his or her age. Solution?
71
Class Average Algorithm
Problem: Calculate and report the grade- point average for a class Discussion: The average grade equals the sum of all grades divided by the number of students Output: Input: Processing:
72
Flowchart We need a loop to read and then add the grades for each student in the class Inside the loop, we also need to count the number of students in the class grade = sum of grades / number of students
73
Pseudocode Program: Determine the average grade of a class Initialize Counter and Sum to 0 Do While there are more data Get the next Grade Add the Grade to the Sum Increment the Counter Loop Compute Average = Sum / Counter Display Average
74
Hierarchy Chart
75
Comments When tracing a flowchart, start at the start symbol and follow the flow lines to the end symbol Testing an algorithm at the flowchart stage is known as desk checking Flowcharts, pseudocode, and hierarchy charts are program planning tools that are not dependent on the programming language being used
76
Comments continued There are four primary logical programming constructs sequence decision loop unconditional branch Appear in some languages as GOTO statements Involves jumping from one place in a program to another Structured programming uses the sequence, decision, and loop constructs but forbids the unconditional branch There are four primary logical programming constructs: sequence, decision, loop, and unconditional branch. Unconditional branch, which appears in some lan-guages as Goto statements, involves jumping from one place in a program to anoth-er. Structured programming uses the first three constructs but forbids the fourth.
77
Tips and tricks of flowcharts
Flowcharts are time-consuming to write and difficult to update For this reason, professional programmers are more likely to favor pseudocode and hierarchy charts Because flowcharts so clearly illustrate the logical flow of programming techniques, they are a valuable tool in the education of programmers
78
Tips and tricks of pseudocode
There are many styles of pseudocode Some programmers use an outline form Some use a form that looks almost like a programming language The pseudocode in the case studies of this text focus on the primary tasks to be performed by the program and leaves many of the routine details to be completed during the coding process
79
Tips and tricks of hierarchy charts
Many people draw rectangles around each item in a hierarchy chart In the text, rectangles are omitted to encourage the use of hierarchy charts by making them easier to draw
80
For next week Read Chapter 2 & Appendix D Install Visual Studio 2010
81
Programming is useful!
82
Review of Chapter 1
83
Trouble installing/accessing Visual Studio?
84
Review Computer Computer programs
a device that can perform calculations and make logical decisions much faster than humans can Computer programs a sequence of instructions Input—Process—Output (data—manipulate—results) Hardware: physical components (keyboard, screen, mouse, hard drive, memory, DVDs, CPU—Central Processing Unit) Software: programs that run on a computer
85
Review Programmers vs. Users Computer languages:
Machine language: computers understand. High-level language: resembles everyday English. Compilers convert it into machine language. (Visual Basic, C, C++, Java, C#, Fortran, COBOL, …)
86
Review Algorithm: a step by step series of instructions to solve a problem Visual Basic.NET is: Event-driven Object-oriented User-friendly (GUI-based)
87
Visual Basic, Controls, and Events
Chapter 2 Visual Basic, Controls, and Events
88
Visual Basic, Controls, and Events
2.1 An Introduction to Visual Basic 2.2 Visual Basic Controls 2.3 Visual Basic Events
89
Visual Basic 2010 Before VB, a window required hundreds of lines of code Now Fewer instructions Consistent Less time User-friendly
90
Visual Basic 2010 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.
91
Before VB
92
Before VB Program complicated, unfriendly Required parameters
Once input was entered, hard to go back
93
How to Develop a VB Application
Design the Interface for the user Literally draw the GUI Drag buttons/text boxes/etc onto form Determine which events the controls on the window should recognize Write the code for those events. Test
94
What happens when program is running
VB monitors the controls for events If event occurs, it runs procedures assigned to that event If no event exists, it goes back to #1
95
Different Versions of Visual Basic
Version 1.0 – Version 2.0 – 1992 Version 3.0 – Version 4.0 – 1995 Version 5.0 – Version 6.0 – 1998 Visual Basic.NET – (NOT BACKWARD COMPATIBLE WITH EARLIER VERSIONS) Visual Basic 2005 – November 2005 Visual Basic 2008 – November 2007 Visual Basic 2010 – April 2010 Visual Basic 2012 – Sept 2012
96
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
97
Visual Basic Start Page
Point out menu bar; especially file item.
98
Start a New Project
99
New Project Dialog Box
100
Initial Visual Basic Screen
101
Toolbox
102
Toolbox Initiates an Action
Get information (input) Display information (output) Shows what type of information is displayed in the textbox. Displays output/make selections
103
Placing Control Forms 3 Ways to Place a Control from the Toolbox onto the Form Window Double-click Drag and Drop Click, Point, and Drag
104
Text Box Control Used for input and output
When used for output, ReadOnly property is set to True Tasks button Sizing handles
105
Properties Window Press F4 to display the Properties window for the selected control. 105 Categorized view Alphabetical view
106
Properties Window Selected control Properties Settings
107
Some Often Used Properties
Text Autosize Font.Name Font.Size ForeColor BackColor ReadOnly
108
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.
109
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.)
110
Font Property Click on Font in left column.
Click on ellipsis at right of settings box to obtain display shown, Make selections.
111
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
112
Add an "access key"
113
Label Control Used to identify the contents of a text box/button/etc
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
114
List Box Control Initially used to display several pieces of output.
In Chapter 9 used to select from a list.
115
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
116
Control Name Prefixes Control Prefix Example button btn btnCompute
label lbl lblAddress text box txt txtAddress list box lst lstOutput
117
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
118
Fonts Proportional width fonts take up less space for "I" than for "W" – like Microsoft Sans Serif Fixed-width fonts take up the same amount of space for each character – like Courier New Fixed-width fonts are used for tables
119
Excellent walkthroughs in book
Demo the previous Label Button Colours Font Renaming Excellent walkthroughs in book
120
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
121
Positioning Controls Proximity line
122
Aligning Controls Snap line
123
Aligning Controls Snap line
124
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.
125
2.3 Visual Basic Events An Event Procedure Walkthrough
Properties and Event Procedures of the Form The Header of an Event Procedure
126
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
127
controlName.property = setting
Sample Statements General Form: controlName.property = setting txtBox.ForeColor = Color.Red txtBox.Visible = True txtBox.Text = "Hello World" What do the above mean?
128
What events could there be?
Sample Form txtFirst txtSecond btnRed What events could there be?
129
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
130
Examples of Events General Form: controlName.event btnShow.Click
txtBox.TextChanged txtBox.Leave
131
Events Take form, double click on textbox
132
Events Enter area to write code for control
133
Examples of Events Select Event
134
3 steps in creating a VB 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
135
Code Editor Code Editor tab Form Designer tab Class Name box
Method Name box
136
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
137
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.)
138
Double Click on txtFirst
Sample Form txtFirst txtSecond btnRed Double Click on txtFirst
139
Code for Walkthrough Public Class frmDemo Private Sub txtFirst_TextChanged(...) Handles txtFirst.TextChanged End Sub End Class
140
Code for Walkthrough Public Class frmDemo Private Sub txtFirst_TextChanged(...) Handles txtFirst.TextChanged txtFirst.ForeColor = Color.Blue End Sub End Class
141
Automatically pops up to give the programmer help.
IntelliSense Automatically pops up to give the programmer help. txtFirst.
142
Click tab to return to Form Designer
Code Editor Click tab to return to Form Designer
143
Double-click on btnRed
Sample Form txtFirst txtSecond btnRed Double-click on btnRed
144
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
145
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
147
Event Procedure Select txtFirst from Class Name box drop-down list
Select Leave from Method Name box drop-down list
148
Code for Walkthrough Private Sub txtFirst_Leave(...) Handles txtFirst.Leave End Sub
149
Code for Walkthrough Private Sub txtFirst_Leave(...) Handles txtFirst.Leave txtFirst.ForeColor = Color.Black End Sub
150
Header of Event Procedure
Private Sub btnRed_Click(…) Handles btnRed.Click Identifies event Name, can be changed. Private Sub Button_Press(…) Handles btnRed.Click
151
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
152
Altering Properties The following won't work: frmDemo.Text = "Demonstration" The form is referred to by the keyword Me. Me.Text = "Demonstration"
153
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
154
Sample Text File Mike Jones John Smith PAYROLL.TXT
155
Sample Text File Mike Jones 9.35 35 John Smith 10.75 33 name
hourly wage hours worked PAYROLL.TXT
156
Our Text File Convention
PAYROLL.TXT uses one item of data per line. That will be our convention in this book.
157
Use Property Window to View all Possible Events for a Control
button
158
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
159
Run Program
161
Review of Chapter 2
162
How to Develop a VB Application
Design the Interface for the user Literally draw the GUI Drag buttons/text boxes/etc onto form Determine which events the controls on the window should recognize Write the code for those events
163
What happens when program is running
VB monitors the controls for events If event occurs, it runs procedures assigned to that event If no event exists, it goes back to #1.
164
Initial Visual Basic Screen
165
Properties Window Selected control Properties Settings
166
Control Name Prefixes Control Prefix Example button btn btnCompute
label lbl lblAddress text box txt txtAddress list box lst lstOutput
167
Positioning Controls Proximity line
168
Aligning Controls Snap line
169
Code Editor Code Editor tab Form Designer tab Class Name box
Method Name box
170
Sample Code Public Class frmDemo Private Sub txtFirst_TextChanged(...) Handles txtFirst.TextChanged txtFirst.ForeColor = Color.Blue End Sub End Class
171
Chapter 3
172
Variables, Input, and Output
3.1 Numbers 3.2 Strings 3.3 Input and Output
173
Arithmetic Operations
Numbers are called numeric literals Five arithmetic operations in Visual Basic + addition - subtraction * multiplication / division ^ exponentiation
174
Numeric Expressions 2 + 3 3 * (4 + 5) 2 ^ 3
175
Displaying Numbers Let n be a number or a numeric expression.
What does the statement lstBox.Items.Add(n) do?
176
Example 1: Form
177
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 What is the result?
178
A numeric variable is a name to which a number can be assigned.
Examples: speed distance interestRate balance
179
Variables Assignment: speed = 50 Declaration: Dim speed As Double
Data type Variable name Assignment: speed = 50
180
Variables Visual Basic type structure Storage size Value range Boolean
4 bytes True or False Byte 1 byte 0 to 255 (unsigned) Char 2 bytes 0 to (unsigned) Date 8 bytes January 1, 1 CE to December 31, 9999 Decimal 12 bytes +/-79,228,162,514,264,337,593,543,950,335 with no decimal point; Double E308 to E-324 for negative values; E-324 to E308 for positive values
181
Variables Visual Basic type structure Storage size Value range Integer
4 bytes -2,147,483,648 to 2,147,483,647 Long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Object Any type can be stored in a variable of type Object Short 2 bytes -32,768 to 32,767 Single E38 to E-45 for negative values; E-45 to E38 for positive values String 10 bytes + (2 * string length) 0 to approximately two billion Unicode characters
182
Initialization Dim varName As Double Dim varName As Double = 50
Numeric variables are automatically initialized to 0: Dim varName As Double To specify a nonzero initial value Dim varName As Double = 50
183
Numeric Expressions Numeric variables can be used in numeric expressions Dim balance As Double = 1000 lstBox.Items.Add(1.05 * balance) 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.)
184
Assignment Statement Dim numVar1 As Double = 5 Dim numVar2 As Double = 4 numVar1 = 3 * numVar2 lstBox.Items.Add(numVar1) 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.)
185
Incrementing To add 1 to the numeric variable var Or as a shortcut
var = var + 1 Or as a shortcut var += 1 Or as a generalization var += numeric expression
186
Built-in Functions Functions return a value Math.Sqrt(9) returns 3
Int(9.7) returns 9 Math.Round(2.7) is 3
187
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
188
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
189
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 -
190
Three Types of Errors Syntax error Run-time error Logic error
191
Some Types of Syntax Errors
Misspellings lstBox.Itms.Add(3) Omissions lstBox.Items.Add(2 + ) Incorrect punctuation Dim m; n As Integer Displayed as blue underline in VS
192
A Type of Run-time Error
Dim numVar As Integer = numVar = numVar * numVar What’s wrong with the above?
193
A Logical Error Dim average As Double Dim m As Double = 5 Dim n As Double = 10 average = m + n / 2 What’s wrong with the above?
194
Error List Window Dim m; n As Double lstResults.Items.Add(5
lstResults.Items.Add(a)
195
– Variables, Input, and Output
3.1 Numbers 3.2 Strings 3.3 Input and Output
196
String Literal "hello" "123-45-6789" "#ab cde?"
A string literal is a sequence of characters surrounded by quotation marks. Examples: "hello" " " "#ab cde?"
197
“She said: “I’m tired.””
String Literal A string literal is a sequence of characters surrounded by quotation marks. Examples: Does this work? “She said: “I’m tired.””
198
String Variable A string variable is a name to which a string value can be assigned. Examples: country ssn word firstName
199
String Variable Assignment: firstName = "Fred" Declaration:
Dim firstName As String Data type Variable name Assignment: firstName = "Fred"
200
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"
201
Add Method lstBox.Items.Add(str)
Let str be a string literal or variable. Then, lstBox.Items.Add(str) displays the value of str in the list box.
202
String Variable Dim strVar1 As String = "Hello"
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)
203
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
204
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.
205
Option Strict -continued
Select Options from the Tools menu In left pane, expand Projects and Solution Select VB Defaults Set Option Strict to On
206
Text Boxes for Input & Output
The contents of a text box is always a string Input example strVar = txtBox.Text Output example txtBox.Text = strVar
207
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
208
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. Will loose information (everything after the decimal place) Strings can be given a different initial value as follows
209
Auto Correction
210
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)
211
Combining two strings to make a new string
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
212
Appending To append str to the string variable var Or as a shortcut
var = var & str Or as a shortcut var &= str
213
Appending Example Dim var As String = "Good" var &= "bye" txtBox.Text = var
214
String Properties and Methods
"Visual".Length is 6. .length calculates the length of the string. Varname = “blah” Varname.length
215
String Properties and Methods
"Visual".ToUpper is VISUAL .ToUpper makes everything upper case. Varname = “blah”
216
String Properties and Methods
"123 Hike".ToLower is “123 hike” .ToLower makes everything lower case Varname = “Blah”
217
String Properties and Methods
"a" & " bcd ".Trim & "efg" is “abcdefg” .trim removes leading/trailing spaces Varname = “ blah “ Varname.trim
218
String properties Dim varname As String = "Tim Hortons"
Can apply a method onto a method What does this do? Dim varname As String = "Tim Hortons" varname.ToUpper.Replace("I", "O").ToLower()
219
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
220
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) ? “Visual Basic”.Substring(0, 1) ?
221
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.
222
The Empty String The string "" (NOT " "), 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 = ""
223
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"
224
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
225
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
226
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."
227
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
228
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.)
229
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.
230
Commenting Commenting is critical For yourself and others
Have to do it right
231
Commenting
232
Commenting
233
Commenting
234
Commenting
235
– Variables, Input, and Output
3.1 Numbers 3.2 Strings 3.3 Input and Output
236
Formatting Output with Functions
String Value FormatNumber( , 1) 12,345.6 FormatCurrency( , 2) $12,345.63 FormatPercent(0.183, 0) 18%
237
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))
238
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}" Debug.Print(String.Format(fmtStr, "abc", "def", "ghi")) “ abc def ghi”
239
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.
240
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}" Debug.Print(String.Format(fmtStr, "abc", "def", "ghi")) “abc def ghi”
241
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.
242
Sample File: PAYROLL.TXT
Mike Jones John Smith Name Hourly wage Number of hours worked
243
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()
244
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()
245
Example using StreamReader
Mike Jones 9.35 35 John Smith 10.75 33 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: 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()
246
Comment on Example Consider The ampersand automatically converted
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()
247
Getting Input from an Input Dialog
stringVar = InputBox(prompt, title) fileName = InputBox("Enter the name " _ & "of the file containing the " & _ "information.", "Name of File") Title Prompt
248
Using a Message 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
249
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
250
Masked Text Box Control
Click the Tasks button to reveal Set Mask property. Click Set Mask to invoke Input Mask dialog box.
251
Input Mask Dialog Box
252
0 Placeholder for a digit. L Placeholder for a letter.
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
253
State abbreviation: LL Phone number: 000-0000
Sample Masks State abbreviation: LL Phone number: Social Security Number: License plate: &&&&&&
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.