SlideShare a Scribd company logo
REVIEW OF CHAPTER 2
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
2
WHAT HAPPENS WHEN PROGRAM IS
RUNNING
1. VB monitors the controls for events
2. If event occurs, it runs procedures assigned to
that event
3. If no event exists, it goes back to #1.
3
INITIAL VISUAL BASIC SCREEN
4
PROPERTIES WINDOW
5
Properties Settings
Selected
control
CONTROL NAME PREFIXES
Control Prefix Example
button btn btnCompute
label lbl lblAddress
text box txt txtAddress
list box lst lstOutput
6
POSITIONING CONTROLS
7
Proximity
line
ALIGNING CONTROLS
8
Snap line
CODE EDITOR
9
Method
Name
box
Class
Name
box
Code Editor
tab
Form Designer
tab
SAMPLE CODE
Public Class frmDemo
Private Sub txtFirst_TextChanged(...)
Handles txtFirst.TextChanged
txtFirst.ForeColor = Color.Blue
End Sub
End Class
10
CHAPTER 3
11
VARIABLES, INPUT, AND OUTPUT
 3.1 Numbers
 3.2 Strings
 3.3 Input and Output
12
ARITHMETIC OPERATIONS
 Numbers are called numeric literals
 Five arithmetic operations in Visual Basic
 + addition
 - subtraction
 * multiplication
 / division
 ^ exponentiation
13
NUMERIC EXPRESSIONS
 2 + 3
 3 * (4 + 5)
 2 ^ 3
14
DISPLAYING NUMBERS
Let n be a number or a numeric expression.
What does the statement
lstBox.Items.Add(n)
do?
15
EXAMPLE 1: FORM
16
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?
17
NUMERIC VARIABLE
18
A numeric variable is a name to which a
number can be assigned.
Examples:
speed
distance
interestRate
balance
VARIABLES
 Declaration:
Dim speed As Double
19
Variable name
Data type
• Assignment:
speed = 50
VARIABLES
20
VARIABLES
21
INITIALIZATION
 Numeric variables are automatically initialized to 0:
Dim varName As Double
 To specify a nonzero initial value
Dim varName As Double = 50
22
NUMERIC EXPRESSIONS
Numeric variables can be used in numeric expressions
Dim balance As Double = 1000
lstBox.Items.Add(1.05 * balance)
23
ASSIGNMENT STATEMENT
Dim numVar1 As Double = 5
Dim numVar2 As Double = 4
numVar1 = 3 * numVar2
lstBox.Items.Add(numVar1)
24
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
25
BUILT-IN FUNCTIONS
 Functions return a value
Math.Sqrt(9) returns 3
Int(9.7) returns 9
Math.Round(2.7) is 3
26
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
27
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
28
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 -
29
THREE TYPES OF ERRORS
 Syntax error
 Run-time error
 Logic error
30
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
31
A TYPE OF RUN-TIME ERROR
Dim numVar As Integer = 1000000
numVar = numVar * numVar
What’s wrong with the above?
32
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?
33
ERROR LIST WINDOW
 Dim m; n As Double
 lstResults.Items.Add(5
 lstResults.Items.Add(a)
34
– VARIABLES, INPUT, AND OUTPUT
 3.1 Numbers
 3.2 Strings
 3.3 Input and Output
35
STRING LITERAL
A string literal is a sequence of
characters surrounded by quotation marks.
Examples:
"hello"
"123-45-6789"
"#ab cde?"
36
STRING LITERAL
A string literal is a sequence of
characters surrounded by quotation marks.
Examples:
Does this work?
“She said: “I’m tired.””
37
STRING VARIABLE
A string variable is a name to which a
string value can be assigned.
Examples:
country
ssn
word
firstName
38
STRING VARIABLE
 Declaration:
Dim firstName As String
39
Variable name
Data type
• Assignment:
firstName = "Fred"
STRING VARIABLE
You can declare a string variable and
assign it a value at the same time.
Dim firstName As String = "Fred"
40
ADD METHOD
Let str be a string literal or variable. Then,
lstBox.Items.Add(str)
displays the value of str in the list box.
41
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)
42
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
43
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.
44
OPTION STRICT -CONTINUED
 Select Options from the Tools menu
 In left pane, expand Projects and Solution
 Select VB Defaults
 Set Option Strict to On
45
OUTPUT
 The contents of a text box is always a string
 Input example
strVar = txtBox.Text
 Output example
txtBox.Text = strVar
46
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)
47
Converts a String to a Double
Converts a number to a string
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
48
AUTO CORRECTION
49
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)
50
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
51
APPENDING
 To append str to the string variable var
var = var & str
 Or as a shortcut
var &= str
52
APPENDING EXAMPLE
Dim var As String = "Good"
var &= "bye"
txtBox.Text = var
53
STRING PROPERTIES AND METHODS
"Visual".Length is 6.
.length calculates the length of the string.
Varname = “blah”
Varname.length
54
STRING PROPERTIES AND METHODS
"Visual".ToUpper is VISUAL
.ToUpper makes everything upper case.
Varname = “blah”
55
STRING PROPERTIES AND METHODS
"123 Hike".ToLower is “123 hike”
.ToLower makes everything lower case
Varname = “Blah”
56
STRING PROPERTIES AND METHODS
"a" & " bcd ".Trim & "efg" is “abcdefg”
.trim removes leading/trailing spaces
Varname = “ blah “
Varname.trim
57
STRING PROPERTIES
 Can apply a method onto a method
 What does this do?
Dim varname As String = "Tim Hortons"
varname.ToUpper.Replace("I", "O").ToLower()
58
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
59
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) ?
60
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.
61
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 = ""
62
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"
63
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
64
INTERNAL DOCUMENTATION
1. Other people can easily understand the program
2. You can understand the program when you read it
later
3. Long programs are easier to read because the
purposes of individual pieces can be determined at
a glance
65
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."
66
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
67
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.)
68
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.
69
COMMENTING
 Commenting is critical
 For yourself and others
 Have to do it right
70
COMMENTING
71
COMMENTING
72
COMMENTING
73
COMMENTING
74
– VARIABLES, INPUT, AND OUTPUT
 3.1 Numbers
 3.2 Strings
 3.3 Input and Output
75
FORMATTING OUTPUT WITH
FUNCTIONS
76
Function String Value
FormatNumber(12345.628, 1) 12,345.6
FormatCurrency(12345.628, 2) $12,345.63
FormatPercent(0.183, 0) 18%
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))
77
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”
78
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.
79
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”
80
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.
81
SAMPLE FILE: PAYROLL.TXT
Mike Jones
9.35
35
John Smith
10.75
33
82
Name
Hourly wage
Number of hours worked
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)
83
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()
84
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
85
Mike Jones
9.35
35
John Smith
10.75
33
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.
86
GETTING INPUT FROM AN INPUT
DIALOG
stringVar = InputBox(prompt, title)
fileName = InputBox("Enter the name " _
& "of the file containing the " & _
"information.", "Name of File")
87
Title
Prompt
USING A MESSAGE BOX FOR OUTPUT
MessageBox.Show(prompt, title)
MessageBox.Show("Nice try, but no
cigar.", _
"Consolation")
88
Title
Prompt
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.
89
Tasks button
MASKED TEXT BOX CONTROL
90
Click the Tasks button to reveal Set
Mask property.
Click Set Mask to invoke Input Mask
dialog box.
INPUT MASK DIALOG BOX
91
MASK
92
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
SAMPLE MASKS
93
State abbreviation: LL
Phone number: 000-0000
Social Security Number: 000-00-0000
License plate: &&&&&&

More Related Content

PPTX
CHAPTER 3- Lesson A
PPS
Visual Basic Review - ICA
PPTX
Vb6.0 intro
PDF
Visual basic
PPTX
Lesson 5 Introduction to Human Computer Interaction
PPT
Introduction to VB.Net By William Lacktano.ppt
PPT
Visual basic 6.0
PDF
Visualbasic tutorial
CHAPTER 3- Lesson A
Visual Basic Review - ICA
Vb6.0 intro
Visual basic
Lesson 5 Introduction to Human Computer Interaction
Introduction to VB.Net By William Lacktano.ppt
Visual basic 6.0
Visualbasic tutorial

Similar to Ch (2)(presentation) its about visual programming (20)

PPTX
CHAPTER 2 (Data types,Variables) in Visual Basic Programming
PPTX
Variables and calculations_chpt_4
PPT
Ms vb
PDF
Visual basic asp.net programming introduction
PPTX
Sharbani bhattacharya VB Structures
PDF
VB PPT by ADI PART2.pdf
PPTX
Presentation on visual basic 6 (vb6)
PPT
Intro_to_VB.PPT
PPTX
Variable and constants in Vb.NET
PPTX
Unit 1 introduction to visual basic programming
PPT
Vb introduction.
PPTX
Visual Programming
PPTX
COM 211 PRESENTATION.pptx
PDF
VB PPT by ADI PART2.pdf
PPTX
CHAPTER 3 - Lesson B
PPT
Visual Basic 6.0
PDF
Visual Basics for Application
PDF
Vb tutorial
PDF
Vb tutorial
CHAPTER 2 (Data types,Variables) in Visual Basic Programming
Variables and calculations_chpt_4
Ms vb
Visual basic asp.net programming introduction
Sharbani bhattacharya VB Structures
VB PPT by ADI PART2.pdf
Presentation on visual basic 6 (vb6)
Intro_to_VB.PPT
Variable and constants in Vb.NET
Unit 1 introduction to visual basic programming
Vb introduction.
Visual Programming
COM 211 PRESENTATION.pptx
VB PPT by ADI PART2.pdf
CHAPTER 3 - Lesson B
Visual Basic 6.0
Visual Basics for Application
Vb tutorial
Vb tutorial
Ad

More from nimrastorage123 (7)

PPTX
Managing Data For Efficiency.pptx and in
PPTX
Visual_Programming_Introduction ABOUT.pptx
PPTX
Theory_of_Automata_Presentation.pptxABOUT
PPT
CHPATER OF VISUAL PROGRAMMING IN WHICH ALL
PPT
INTRODUCTION OF THEORYOF AUTOMATA AND ABOUT IT
PDF
Week 8,9,10 of lab of data communication .pdf
PPTX
DL PRESENTATION by(NIMRA MEMON mscs).pptx
Managing Data For Efficiency.pptx and in
Visual_Programming_Introduction ABOUT.pptx
Theory_of_Automata_Presentation.pptxABOUT
CHPATER OF VISUAL PROGRAMMING IN WHICH ALL
INTRODUCTION OF THEORYOF AUTOMATA AND ABOUT IT
Week 8,9,10 of lab of data communication .pdf
DL PRESENTATION by(NIMRA MEMON mscs).pptx
Ad

Recently uploaded (20)

PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
Pharma ospi slides which help in ospi learning
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
RMMM.pdf make it easy to upload and study
PPTX
Cell Types and Its function , kingdom of life
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
Lesson notes of climatology university.
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
Classroom Observation Tools for Teachers
PDF
A systematic review of self-coping strategies used by university students to ...
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
GDM (1) (1).pptx small presentation for students
Pharma ospi slides which help in ospi learning
2.FourierTransform-ShortQuestionswithAnswers.pdf
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Anesthesia in Laparoscopic Surgery in India
RMMM.pdf make it easy to upload and study
Cell Types and Its function , kingdom of life
Supply Chain Operations Speaking Notes -ICLT Program
Lesson notes of climatology university.
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Classroom Observation Tools for Teachers
A systematic review of self-coping strategies used by university students to ...
Abdominal Access Techniques with Prof. Dr. R K Mishra
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
VCE English Exam - Section C Student Revision Booklet
STATICS OF THE RIGID BODIES Hibbelers.pdf
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf

Ch (2)(presentation) its about visual programming

  • 2. 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 2
  • 3. WHAT HAPPENS WHEN PROGRAM IS RUNNING 1. VB monitors the controls for events 2. If event occurs, it runs procedures assigned to that event 3. If no event exists, it goes back to #1. 3
  • 6. CONTROL NAME PREFIXES Control Prefix Example button btn btnCompute label lbl lblAddress text box txt txtAddress list box lst lstOutput 6
  • 10. SAMPLE CODE Public Class frmDemo Private Sub txtFirst_TextChanged(...) Handles txtFirst.TextChanged txtFirst.ForeColor = Color.Blue End Sub End Class 10
  • 12. VARIABLES, INPUT, AND OUTPUT  3.1 Numbers  3.2 Strings  3.3 Input and Output 12
  • 13. ARITHMETIC OPERATIONS  Numbers are called numeric literals  Five arithmetic operations in Visual Basic  + addition  - subtraction  * multiplication  / division  ^ exponentiation 13
  • 14. NUMERIC EXPRESSIONS  2 + 3  3 * (4 + 5)  2 ^ 3 14
  • 15. DISPLAYING NUMBERS Let n be a number or a numeric expression. What does the statement lstBox.Items.Add(n) do? 15
  • 17. 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? 17
  • 18. NUMERIC VARIABLE 18 A numeric variable is a name to which a number can be assigned. Examples: speed distance interestRate balance
  • 19. VARIABLES  Declaration: Dim speed As Double 19 Variable name Data type • Assignment: speed = 50
  • 22. INITIALIZATION  Numeric variables are automatically initialized to 0: Dim varName As Double  To specify a nonzero initial value Dim varName As Double = 50 22
  • 23. NUMERIC EXPRESSIONS Numeric variables can be used in numeric expressions Dim balance As Double = 1000 lstBox.Items.Add(1.05 * balance) 23
  • 24. ASSIGNMENT STATEMENT Dim numVar1 As Double = 5 Dim numVar2 As Double = 4 numVar1 = 3 * numVar2 lstBox.Items.Add(numVar1) 24
  • 25. 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 25
  • 26. BUILT-IN FUNCTIONS  Functions return a value Math.Sqrt(9) returns 3 Int(9.7) returns 9 Math.Round(2.7) is 3 26
  • 27. 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 27
  • 28. 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 28
  • 29. 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 - 29
  • 30. THREE TYPES OF ERRORS  Syntax error  Run-time error  Logic error 30
  • 31. 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 31
  • 32. A TYPE OF RUN-TIME ERROR Dim numVar As Integer = 1000000 numVar = numVar * numVar What’s wrong with the above? 32
  • 33. 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? 33
  • 34. ERROR LIST WINDOW  Dim m; n As Double  lstResults.Items.Add(5  lstResults.Items.Add(a) 34
  • 35. – VARIABLES, INPUT, AND OUTPUT  3.1 Numbers  3.2 Strings  3.3 Input and Output 35
  • 36. STRING LITERAL A string literal is a sequence of characters surrounded by quotation marks. Examples: "hello" "123-45-6789" "#ab cde?" 36
  • 37. STRING LITERAL A string literal is a sequence of characters surrounded by quotation marks. Examples: Does this work? “She said: “I’m tired.”” 37
  • 38. STRING VARIABLE A string variable is a name to which a string value can be assigned. Examples: country ssn word firstName 38
  • 39. STRING VARIABLE  Declaration: Dim firstName As String 39 Variable name Data type • Assignment: firstName = "Fred"
  • 40. STRING VARIABLE You can declare a string variable and assign it a value at the same time. Dim firstName As String = "Fred" 40
  • 41. ADD METHOD Let str be a string literal or variable. Then, lstBox.Items.Add(str) displays the value of str in the list box. 41
  • 42. 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) 42
  • 43. 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 43
  • 44. 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. 44
  • 45. OPTION STRICT -CONTINUED  Select Options from the Tools menu  In left pane, expand Projects and Solution  Select VB Defaults  Set Option Strict to On 45
  • 46. OUTPUT  The contents of a text box is always a string  Input example strVar = txtBox.Text  Output example txtBox.Text = strVar 46
  • 47. 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) 47 Converts a String to a Double Converts a number to a string
  • 48. 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 48
  • 50. 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) 50
  • 51. 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 51
  • 52. APPENDING  To append str to the string variable var var = var & str  Or as a shortcut var &= str 52
  • 53. APPENDING EXAMPLE Dim var As String = "Good" var &= "bye" txtBox.Text = var 53
  • 54. STRING PROPERTIES AND METHODS "Visual".Length is 6. .length calculates the length of the string. Varname = “blah” Varname.length 54
  • 55. STRING PROPERTIES AND METHODS "Visual".ToUpper is VISUAL .ToUpper makes everything upper case. Varname = “blah” 55
  • 56. STRING PROPERTIES AND METHODS "123 Hike".ToLower is “123 hike” .ToLower makes everything lower case Varname = “Blah” 56
  • 57. STRING PROPERTIES AND METHODS "a" & " bcd ".Trim & "efg" is “abcdefg” .trim removes leading/trailing spaces Varname = “ blah “ Varname.trim 57
  • 58. STRING PROPERTIES  Can apply a method onto a method  What does this do? Dim varname As String = "Tim Hortons" varname.ToUpper.Replace("I", "O").ToLower() 58
  • 59. 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 59
  • 60. 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) ? 60
  • 61. 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. 61
  • 62. 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 = "" 62
  • 63. 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" 63
  • 64. 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 64
  • 65. INTERNAL DOCUMENTATION 1. Other people can easily understand the program 2. You can understand the program when you read it later 3. Long programs are easier to read because the purposes of individual pieces can be determined at a glance 65
  • 66. 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." 66
  • 67. 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 67
  • 68. 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.) 68
  • 69. 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. 69
  • 70. COMMENTING  Commenting is critical  For yourself and others  Have to do it right 70
  • 75. – VARIABLES, INPUT, AND OUTPUT  3.1 Numbers  3.2 Strings  3.3 Input and Output 75
  • 76. FORMATTING OUTPUT WITH FUNCTIONS 76 Function String Value FormatNumber(12345.628, 1) 12,345.6 FormatCurrency(12345.628, 2) $12,345.63 FormatPercent(0.183, 0) 18%
  • 77. 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)) 77
  • 78. 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” 78
  • 79. 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. 79
  • 80. 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” 80
  • 81. 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. 81
  • 82. SAMPLE FILE: PAYROLL.TXT Mike Jones 9.35 35 John Smith 10.75 33 82 Name Hourly wage Number of hours worked
  • 83. 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) 83
  • 84. 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() 84
  • 85. 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 85 Mike Jones 9.35 35 John Smith 10.75 33
  • 86. 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. 86
  • 87. GETTING INPUT FROM AN INPUT DIALOG stringVar = InputBox(prompt, title) fileName = InputBox("Enter the name " _ & "of the file containing the " & _ "information.", "Name of File") 87 Title Prompt
  • 88. USING A MESSAGE BOX FOR OUTPUT MessageBox.Show(prompt, title) MessageBox.Show("Nice try, but no cigar.", _ "Consolation") 88 Title Prompt
  • 89. 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. 89 Tasks button
  • 90. MASKED TEXT BOX CONTROL 90 Click the Tasks button to reveal Set Mask property. Click Set Mask to invoke Input Mask dialog box.
  • 92. MASK 92 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
  • 93. SAMPLE MASKS 93 State abbreviation: LL Phone number: 000-0000 Social Security Number: 000-00-0000 License plate: &&&&&&

Editor's Notes

  • #23: 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.)
  • #24: 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.)
  • #83: 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()
  • #84: 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()
  • #85: 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()
  • #86: 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()
  • #88: 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")