Foundation of Computer Programming Visual Basic 6.0 Programming Instructor: Mr. Nguyen Cao Tri [email protected] http://www.dit.hcmut.edu.vn/~caotri Documents: Course syllabus, lecture’s slide, samples can be found at http://www.dit.hcmut.edu.vn/~caotri/VB6 Ho Chi.
Download ReportTranscript Foundation of Computer Programming Visual Basic 6.0 Programming Instructor: Mr. Nguyen Cao Tri [email protected] http://www.dit.hcmut.edu.vn/~caotri Documents: Course syllabus, lecture’s slide, samples can be found at http://www.dit.hcmut.edu.vn/~caotri/VB6 Ho Chi.
Slide 1
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
Print
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
Print
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print
Print flag
Print number
Print name
Print
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
Print
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 2
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
Print
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
Print
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print
Print flag
Print number
Print name
Print
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
Print
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 3
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
Print
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
Print
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print
Print flag
Print number
Print name
Print
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
Print
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 4
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
Print
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
Print
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print
Print flag
Print number
Print name
Print
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
Print
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 5
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
Print
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
Print
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print
Print flag
Print number
Print name
Print
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
Print
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 6
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
Print
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
Print
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print
Print flag
Print number
Print name
Print
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
Print
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 7
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
Print
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
Print
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print
Print flag
Print number
Print name
Print
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
Print
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 8
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
Print
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
Print
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print
Print flag
Print number
Print name
Print
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
Print
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 9
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
Print
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
Print
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print
Print flag
Print number
Print name
Print
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
Print
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 10
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
Print
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
Print
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print
Print flag
Print number
Print name
Print
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
Print
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 11
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
Print
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
Print
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print
Print flag
Print number
Print name
Print
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
Print
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 12
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
Print
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
Print
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print
Print flag
Print number
Print name
Print
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
Print
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 13
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
Print
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
Print
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print
Print flag
Print number
Print name
Print
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
Print
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 14
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
Print
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
Print
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print
Print flag
Print number
Print name
Print
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
Print
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 15
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
Print
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
Print
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print
Print flag
Print number
Print name
Print
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
Print
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 16
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
Print
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
Print
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print
Print flag
Print number
Print name
Print
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
Print
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 17
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
Print
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
Print
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print
Print flag
Print number
Print name
Print
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
Print
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 18
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
Print
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
Print
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print
Print flag
Print number
Print name
Print
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
Print
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 19
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
Print
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
Print
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print
Print flag
Print number
Print name
Print
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
Print
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 20
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
Print
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
Print
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print
Print flag
Print number
Print name
Print
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
Print
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 21
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
Print
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
Print
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print
Print flag
Print number
Print name
Print
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
Print
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 22
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
Print
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
Print
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print
Print flag
Print number
Print name
Print
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
Print
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 23
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
Print
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
Print
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print
Print flag
Print number
Print name
Print
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
Print
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 24
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
Print
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
Print
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print
Print flag
Print number
Print name
Print
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
Print
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 25
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If then Statement;
If then Statement 1
else Statement 2;
Case of
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While do Statement;
Repeat Statement until;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P C <= E
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if then
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if then
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print flag
Print number
Print name
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 2
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print flag
Print number
Print name
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 3
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print flag
Print number
Print name
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 4
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print flag
Print number
Print name
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 5
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print flag
Print number
Print name
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 6
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print flag
Print number
Print name
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 7
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print flag
Print number
Print name
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 8
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print flag
Print number
Print name
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 9
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print flag
Print number
Print name
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 10
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print flag
Print number
Print name
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 11
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print flag
Print number
Print name
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 12
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print flag
Print number
Print name
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 13
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print flag
Print number
Print name
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 14
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print flag
Print number
Print name
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 15
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print flag
Print number
Print name
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 16
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print flag
Print number
Print name
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 17
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print flag
Print number
Print name
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 18
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print flag
Print number
Print name
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 19
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print flag
Print number
Print name
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 20
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print flag
Print number
Print name
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 21
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print flag
Print number
Print name
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 22
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print flag
Print number
Print name
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 23
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print flag
Print number
Print name
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 24
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while
statements
Loop
While/Wend
Example
Dim product As integer
product = 1
Do while product <= 1000
product = product * 2
print product
Loop
||
Do while/Loop
What’s on form
4 8 16 32 64 128 256 512 1024
Department of Information Technology
Nguyễn Cao Trí – [email protected]
38
Do until/Loop structure
Syntax
Do until
statements
Loop
Statements
Condition
Example
Dim product As integer
product = 1
Do until product >1000
product = product * 2
print product
Loop
No
Yes
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
39
For/Next structure
Syntax
For counter=startValue To endValue Step Stepsize
statements
Next counter
Example
For j = 2 to 80 step 5
a= a+2
Next j
Counter = StartValue
Counter = Counter + Stepsize
statements
** Stepsize = 1 is default
value
Counter > endValue
Yes
No
Department of Information Technology
Nguyễn Cao Trí – [email protected]
40
Sample of For/Next
For years = 1 To 10 Step 1
amount = principal * (1 + interestRate) ^ years
lstDisplay.AddItem Format$(years, "@@@@") &
vbTab & Format$(Format$(amount, "Currency"),
_String$(17, "@"))
Next years
Department of Information Technology
Nguyễn Cao Trí – [email protected]
41
Select Case structure
Syntax
Select Case mAccessCode
Case Is < 1000
message = "Access Denied"
Beep
Case 1645 To 1689
message = "Technician
Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To
1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Department of Information Technology
Nguyễn Cao Trí – [email protected]
42
Do/loop while structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop While counter <= 10
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Department of Information Technology
Nguyễn Cao Trí – [email protected]
43
Do/Loop Until structure
Syntax
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
Loop Until counter >= 10
Do
Statements
Loop While
Condition
Yes
No
Result
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Statements
Do
Loop Until
Condition
No
Yes
Department of Information Technology
Nguyễn Cao Trí – [email protected]
44
Exit Do / Exit For
counter = 1
Do
Print counter & Space$(2);
counter = counter + 1
if n = 5 then
Exit Do
Loop Until counter >= 10
Result:
12345
Result:
12345
For x=1 to 10
if x=5 then
exit for
end if
print x
next x
Why do exit do and exit be used.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
45
Variable & Constant – Logical operators
Dim VariableName As DataType
Const ConstantName = value As DataType
Logical operators
NOT
AND
OR
Where ‘s Logical operators used
Department of Information Technology
Nguyễn Cao Trí – [email protected]
46
Visual Basic Data type
Data type
Bytes
Range
Boolean
2
True or False
Byte
1
0 to 255
Currency
8
-922337203685477.5808 to 922337203685477.5807
Date
8
1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)
Double
8
-1.79769313486232E308 to -4.94065645841247E-324 (Negative)
1.79769313486232E308 to 4.94065645841247E-324 (Positive)
Integer
2
-32767 to 32768
Long
4
-2147483648 to 2147483648
Object
4
Any Object type (See Chapter 16)
Single
4
-3.402823E38 to -1.401298E-45
3.402823E38 to 1.401298E-45
String
10+
0 to ~2000000000 characters.
Variant
16
Any value within the ranges listed above. (See chapter 21)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
47
LAB Works
All Samples from text book
Exercises at end of chapters
Assignment Calculator application
Your own applications (option)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
48
SUB & Function procedure
Procedure in VB
Sub/Function
Recursive
Ho Chi Minh City University of Technology - Department of Information Technology
Module programming
What’s module?
Why do we need to write program in module?
Modules in Visual Basic
Even procedure
Visual basic procedure
SUB procedure
Function procedure
What should be used ?
Visual basic procedures
Sub/function procedures
Department of Information Technology
Nguyễn Cao Trí – [email protected]
50
SUB procedure
Create new procedure:
In code windows, select menu
Tools-> Add Procedure
Public Sub
MyProcedure()
Your process code’s
here
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
51
SUB procedure sample
Public Sub MyProcedure2(textstr As String)
Print textstr
End Sub
Public Sub MyProcedure()
Print "welcome to my procedure"
End Sub
Private Sub Command1_Click()
MyProcedure
End Sub
Private Sub Command2_Click()
MyProcedure2 "Hello, this is procedure 2“
Call MyProcedure2 (“Hello from call method”)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
52
Function Procedure
Function procedure return a value after called
The process of create a function procedure as the same as SUB procedure.
Sample structure of function
Public Function MyFunction(X As Integer) As Integer
MyFunction = X ^ 3
End Function
Call a function
Private Sub Command3_Click()
Dim output As Integer
output = MyFunction(3)
Print "Return value of MyFunction"
Print output
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
53
Call By Value & Call by reference
What’s call by Value?
What’s call by Reference?
Call by Value vs. Call by Reference
How to write a procedure as call by value /
reference?
Private Sub Procedurename ( A as integer , byval b as integer)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
54
Sample of Call by value and Call by Reference
Private Sub Command1_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyVal " & a
callbyVal a
Print "Value of a after call callbyVal " & a
End Sub
Private Sub Command2_Click()
Dim a As Integer
a = 30
Print "Value of a before call callbyRef " & a
callbyref a
Print "Value of a after call callbyRef " & a
End Sub
Private Sub Command3_Click()
Dim a, b As Integer
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b
Print "call ByValandByref and tranfer A as byVal and b as Byref"
ByValandByRef a, b
Print "Value of a,b after ByvalandByref called " & a & " " & b
End Sub
Private Sub callbyVal(ByVal x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Private Sub callbyref(x As Integer)
x=x^2
Print "Value of x (has been tranfer as a) within
procedure " & x
End Sub
Public Sub ByValandByRef(ByVal x As Integer, y
As Integer)
x=x^2
y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
&" "&y
End Sub
Private Sub Command4_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
55
Sample of Call by value and Call by Reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
56
Exit Sub and Exit Function
Why do we need exit sub and exit Function?
Statement
Exit SUB
Exit Function
Generate random number
Scope of variable and const in Sub and Function
Using Rnd function .
Rnd return a random number between 0 and 1 (but not 1)
Local scope (Private scope)
Module scope
Public scope
Overdrive declaration
Department of Information Technology
Nguyễn Cao Trí – [email protected]
57
Recursion vs. Iteration
What ‘s recursion?
Recursion part
Stop recursion condition
Sample of recursion: n factorial defined
Recursion :
Iteration :
n! = n * (n-1)!
0! =1
n! = 1*2*3*……..*n
Benefit of Recursion
The weakness of recursion in programming
Hanoi tower solution
Department of Information Technology
Nguyễn Cao Trí – [email protected]
58
Optional arguments
Private Sub FooBar ( y as Boolean, Optional z as long)
Calling
Call FooBar
Call FooBar (True)
Call FooBar (True ,10)
Default Value of Optional arguments
Number : 0 Boolean : False
Setting default value for Optional argument
Private Sub FooBar ( y as boolean, Optional z as long = 8)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
59
Named Arguments
Public Sub Display (flag As Boolean, number As Long, name As String)
Print flag
Print number
Print name
End Sub
Private Sub Command1_Click()
Print "call as normal arguments"
Call Display (True, 32000, "String value")
Print "call as named arguments"
Call Display (name:="String Value", flag:=True, number:=3200)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
60
Code modules
What’s code modules
Create code module
Department of Information Technology
Nguyễn Cao Trí – [email protected]
61
Review
Visual programming & Even base programming
Control Structure of Visual basic
Data type in VB 6.0
Other operators
SUB Procedure & Function procedure
Recursion
LAB
Department of Information Technology
Nguyễn Cao Trí – [email protected]
62
Array structure
Introduce Array structure
Understand using array structure; sort, search,..
Multi dimensions
Dynamic array
Ho Chi Minh City University of Technology - Department of Information Technology
Array in Visual Basic
What’s an array structure?
What are they used for?
12 24 32
1
87 16 34
5
Declaring an array in Visual Basic
Dim ArrayVariable (Index) As Datatype
Index= number of Items -1 ( starting index 0)
Dim ArrayVariable (Lbound to Ubound) As Datatype
Default
Example :
Lbound =0
Ubound = Number of Items -1
Dim myarray(9) As Integer
Dim Mysecondarray (1 to 10) As Integer
Access to Item of array :
Arrayname(index)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
64
Using array - sample
Dim MyArray(9) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
65
Array index and Option Base
Lbound of array is default set to 0.
Changing this default lbound by:
Oversize array by number of item +1 and ignore
item(0)
Changing base default set by using Option base in
general declaration
Option Base 1
Option Base is accept 0 or 1 only
Using specification declaration of array
Dim MyArray(1 to 10) As Integer
Dim OtherArray( -10 to 20) As integer
Department of Information Technology
Nguyễn Cao Trí – [email protected]
66
Using array - sample
Option Base 1
Dim MyArray(10) As Integer
Private Sub txtStep_Change()
Dim Step As Integer
Dim x As Integer
Step = txtStep
x=1
For x = LBound(MyArray) To UBound(MyArray)
MyArray(x) = x * Step
Next x
End Sub
Private Sub cmdPrint_Click()
Step = txtinput
Print "Index Item Value"
x=1
For x = LBound(MyArray) To UBound(MyArray)
Print " " & x & "
" & MyArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
67
Passing Array to Procedure
Passing array as an argument of an procedure by array
name with empty parentheses
Dim Myarray(20) As Integer
Private Sub ModifyArray ( a() As Integer)
Call ModifyArray ( Myarray() )
Passing one Item of array to procedure
Private Sub PassOneItem ( n As Integer)
Call PassOneItem (Myarray(10))
Using array Items : Array Items can be using as single
variable of the same datatype
Myarray(5) = x + 3
Myarray(7) = MyArray(3)+ 5*Myarray(7)
By default array is passing by reference. Using Byval
option if need
Department of Information Technology
Nguyễn Cao Trí – [email protected]
68
Passing array sample
Dim mArray(-5 To 5) As Integer
Private Sub cmdArray_Click()
Dim x As Integer
Call Initialize
Call ModifyArray(mArray())
Call PrintModified
End Sub
Private Sub cmdElement_Click()
Dim x As Integer
Call Initialize
For x = LBound(mArray) To UBound(mArray)
Call ModifyElement(mArray(x))
Next x
Call PrintModified
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub ModifyArray(a() As Integer)
Dim x As Integer
For x = LBound(a) To UBound(a)
a(x) = a(x) * 2
Next x
End Sub
Private Sub ModifyElement(element As Integer)
element= element * 5
End Sub
Private Sub Initialize()
Dim x As Integer
lstOriginal.Clear
lstModified.Clear
For x = LBound(mArray) To UBound(mArray)
mArray(x) = x
lstOriginal.AddItem mArray(x)
Next x
End Sub
Private Sub PrintModified()
Dim x As Integer
For x = LBound(mArray) To UBound(mArray)
lstModified.AddItem mArray(x)
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
69
Passing array sample
Passing full array
Passing Item by item
Department of Information Technology
Nguyễn Cao Trí – [email protected]
70
Sorting array
What is sorted array ?
Basic activities on Array
Search: Linear search , binary search
Sort : bubble sort , Quick Sort
Why do we have to sort an array?
Bubble Sort (Example incremental sort)
1.
2.
3.
4.
Finding the biggest item, put it at end of array
Assume that array have one item less
Repeat step 1 until the assumed array has only 1
items
Array has been sorted
Department of Information Technology
Nguyễn Cao Trí – [email protected]
71
Bubble Sort in Visual basic
Department of Information Technology
Nguyễn Cao Trí – [email protected]
72
Bubble Sort Code View
Option Base 1
Dim mArray(10) As Integer
Private Sub cmdGenerate_Click()
Dim x As Integer
Call lstOriginal.Clear
Erase mArray
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd())
Call lstOriginal.AddItem(mArray(x))
Next x
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True
cmdSort2.Enabled = True
End Sub
Private Sub cmdSort_Click()
Dim x As Integer
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x))
Next x
cmdSort.Enabled = False
End Sub
' Module modBubble.bas
Option Explicit
Public Sub BubbleSort(theArray() As Integer)
Dim pass As Integer, compare As Integer
Dim hold As Integer
For pass = 1 To (UBound(theArray) - 1)
For compare = 1 To (UBound(theArray) - 1)
If theArray(compare) > theArray(compare + 1) Then
hold = theArray(compare)
theArray(compare) = theArray(compare + 1)
theArray(compare + 1) = hold
End If
Next compare
Next pass
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
73
Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
74
Linear Search Code View
Private Sub cmdSearch_Click()
Dim searchKey As Integer ' Value to search for
Dim element As Integer ' Index of Value
lblResult.Caption = ""
searchKey = txtKey.Text
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index:
" & element
Else
lblResult.Caption = "Value was not found.“
End If
End Sub
Private Sub lstData_Click()
Dim x As Integer
Call Randomize
Call lstData.Clear
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd())
Call lstData.AddItem(mArray(x))
Next x
End Sub
Function LinearSearch(a() As
Integer, key As Integer) As
Integer
Dim x As Integer
For x = LBound(a) To UBound(a)
If a(x) = key Then
LinearSearch = x ' Return index
Exit Function
End If
Next x
LinearSearch = -1
found
End Function
' Value not
Department of Information Technology
Nguyễn Cao Trí – [email protected]
75
Binary Search
Binary search algorithms
Array need to be sorted in advance
Binary Search (incremental array)
1.
2.
3.
4.
5.
6.
7.
8.
Set startindex= lbound (myarray)
Set endindex = ubound (myarray)
Get miditem = (startindex + endindex ) /2
If searchkey = myarray(miditem) then FOUND
Elseif searchkey >myarray(miditem) then
startitem = miditem +1 and goto step 3
else enditem = miditem -1 and goto step 3
If startitem>=enditem then NOT FOUND
Binary search vs. Linear Search
Department of Information Technology
Nguyễn Cao Trí – [email protected]
76
Binary Search code view
Private Sub BinarySearch()
Dim middle As Integer
Dim low As Integer, high As
Integer
Dim searchKey As Integer
low = mLowBound
high = mUpperBound
Call PrintHeader
searchKey = txtKey.Text
Do While (low <= high)
middle = (low + high) \ 2
Call PrintRow(low, middle, high)
if (searchKey = mArray(middle)) Then
Print "Found " & searchKey & " in " _
& "index " & middle
Exit Sub
ElseIf searchKey < mArray(middle) Then
high = middle - 1
Else
low = middle + 1
End If
Loop
Print searchKey & " not found."
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
77
Binary Search sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
78
Multidimensional array
Multidimensional array
Col 1
Col 2
Col 2
Row 1
Item(1,1)
Item(1,2)
Item(1,3)
Row 2
Item(2,1)
Item(2,2)
Item(2,3)
Row 3
Item(3,1)
Item(3,2)
Item(3,3)
Declare Multidimensional array
Dim myarray (firstDimenIndex , SecondDimenIndex,….) As Datatype
Dim arrayA ( 8 , 12 to 15, 1 to 10) As Integer
Dim arrayB ( 8,8,9,10,3) as integer
Access to item : arrayname(index1,index2,…)
arrayA( 5, 10, 8)
arrayB(3,2,7,0,0)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
79
Multidimensional Array - Sample
Option Base 1
Dim mArray(2, 3) As Integer
Private Sub Form_Load()
Dim x As Integer, y As Integer
Call Randomize
For x = LBound(mArray) To
UBound(mArray)
For y = LBound(mArray, 2) To
UBound(mArray, 2)
mArray(x, y) = 10 + Int(89 * Rnd())
Call lstValues.AddItem(mArray(x, y))
Next y
Next x
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
80
Control Array
What’s control array?
Creating a control array:
1.
2.
Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
Using the same name for controls
All controls in a control array have the same name and
therefore only need to write one even procedure for all
control within a control array.
Control array has lbound=0 and ubound (32767 max)
Control array count value : number of items in control
array.
Controlname.count Controlname.lbound Controlname.ubound
Access to items properties :
controlname.Item(index).propertyname
Department of Information Technology
Nguyễn Cao Trí – [email protected]
81
Control array sample
Private Sub cmdEnter_Click()
Dim message As String
mAccessCode = txtDisplay.Text
txtDisplay.Text = ""
Select Case mAccessCode
Case Is < 1000
' Panic codes
message = "Access Denied"
Case 1645 To 1689
message = "Technician Personnel"
Case 8345
message = "Custodial Services"
Case 55875
message = "Special Services"
Case 999898, 1000006 To 1000008
message = "Scientific Personnel"
Case Else
message = "Access Denied"
End Select
Call lstLogEntry.AddItem(Now & Space$(3) & message)
End Sub
Private Sub cmdButton_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & Index
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
82
Dynamic array
Dynamic array is array with dynamic size.
Dim myDynamicArray() as integer
Define array size when using in code by Redim
Redim myDynamicArray (20)
when Redim is execute, all items is reset.
Preserve keyword using to keep original value of
items when Redim array
Redim Preserve myDynamicArray (50)
Multidimensional array also can be dynamic
however the number of dimension cannot be.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
83
Dynamic array sample
Option Base 1
Dim mDynamic() As Integer
Private Sub cmdRedim_Click()
Dim arrayLength As Integer, x As Integer
Call lstValues.Clear
arrayLength = txtInput.Text
' Determine state of CheckBox
If chkPreserve.Value = vbUnchecked Then
ReDim mDynamic(arrayLength)
ElseIf chkPreserve.Value = vbChecked Then
' Allocate memory and preserve contents
ReDim Preserve mDynamic(arrayLength)
End If
Call Displayarray
cmdErase.Enabled = True
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
84
Dynamic array sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
85
Variable – Length arguments: ParamArray
Option Explicit
Private Sub Form_Load()
Call AnyNumberArguments
Call AnyNumberArguments(1)
Call AnyNumberArguments(2, 3)
Call AnyNumberArguments(4, 5, 6)
Call AnyNumberArguments(7, 8, 9, 10, 11, 12)
End Sub
Private Sub AnyNumberArguments(ParamArray
x() As Variant)
Dim y As Integer
Print "Procedure AnyNumberArguments
received "
For y = LBound(x) To UBound(x)
Print x(y) & Space$(4);
Next y
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
86
String , Date & Time
Character & String data structure
String processing capabilities
Date & Time processing
Ho Chi Minh City University of Technology - Department of Information Technology
Character
Character is stored in computer as a number from
0 to 255.
Example: A is stored as 65
1 is stored as 49
ANSI character set (American National Standard Institute)
including 256 characters from 0 to 255 (one byte in memory)
ASSCII character set (American Standard Code for Information
Interchange) includes first 128 characters from ANSI (from 0 to 127).
Character data type include A,B,C,…, 0,1,2,…,
as well as others characters like *, &, +, /, *, etc.
Character are comparable by its numeric value in
memory.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
88
String data type
A string is a series of characters treated as a
single unit.
A string may include any character in ANSI
character set. (value from 0 to 255)
String in Visual basic has data type named string
String is written as list of characters within a
double quotation. "This is a string !"
Declared a string variable/constant in VB:
Dim StringVariable As String
Dim StringVariable As String * 20
Variable length - Default
Fix length to 20
Department of Information Technology
Nguyễn Cao Trí – [email protected]
89
String data type
Variable length string are composed up to
2,147,483,648 characters.
Fix length String are composed up to 65,568
characters
Strings are comparable by its characters numeric
values in order.
Example : "ABCDEF" is less than "ABCd" because D < d
If an Fix-length String is assign a shorter string,
the rest will take space characters.
For larger String assigned to fix-length string, it ‘s
automatically truncated to fix size of string.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
90
String compare example
Function StrComp(FirstStr, SecondStr, Option type)
Result
-1 FirstStr < SecondStr
1 FirstStr > SecondStr
0 FirstStr = SecondStr
Option Type
vbBinaryCompare
vbTextCompare
vbDatabaseCompare
vbUseCompareOption
Option Compare Type
Binary Text Database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
91
String compare example
Private Sub cmdCompare_Click()
If txtInput1.Text > txtInput2.Text Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text
Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& "equal to " & txtInput2.Text)
End If
End Sub
Private Sub cmdStrComp_Click()
Dim result As Integer
result = StrComp(txtInput1.Text,
txtInput2.Text)
If result = -1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is less than " & txtInput2.Text)
ElseIf result = 1 Then
Call lstOutput.AddItem(txtInput1.Text
& " is greater than " & txtInput2.Text)
Else
Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
92
String concatenation with & and +
Larger string can be conducted by combining small strings
together. This process is called string concatenation by
using & and/or + operators.
Example:
S1=“Hello “
S2 = “friends”
S 3 = S1 + S2 => S3 = “Hello friends”
S4 = S1 & S2 => S4 = “Hello friends”
If all operands are string, the + and & are similar
If an operand are other data type the + operator may have
problem.
Example: s1 = “Hello” + 22 => Error since VB try to change “Hello”
to number and add to 22 => type mismatch
Department of Information Technology
Nguyễn Cao Trí – [email protected]
93
Operator Like
Operator Like can using to compare 2 patterns of
characters or strings. Return value is True/False
Example: “ABCDEFGH” like “ABCD” => false
Pattern matching can be used:
* used to represent any character(s)
“ABCDEFG” like “ABC*” => true
? used to replace any single character.
“ABCDEFG” like “ABC??FG” => true
# used to replace any single numeric character
“ABCD5FG” like “ABCD#FG” => true
[ ], [! ] used to replace a single character with a set of
characters
“ABCD5FG” like “A[A-C]CD[ !3-7]FG” => false
Department of Information Technology
Nguyễn Cao Trí – [email protected]
94
Like Operator example
Private Sub cmdTest_Click()
Dim b As Boolean
b = txtString.Text Like txtPattern.Text
lstOutput.AddItem (txtString.Text & " Like " & txtPattern.Text & " is " & b)
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
95
Other String SUBs/Functions
Function Mid$ (string, position, amount)
Return a character/string with amount of characters which copied from
string at position.
If remaining is fewer than amount the remained of string is return.
Mid$ also can used to replace a part of string with a substring.
S = “Visual Basic 6.0”
Mid$(S,2,3) = “XXX” => S = “VXXXal Basic 6.0”
Function Len (string) Return length of string.
Function Left$ (string, amount) Return amount leftmost characters
Function Right$ (string, amount) Return amount rightmost characters
Function InsStr (StartPos, String,SubString) Return the position
where the substring exist from startpos of string or return 0 if not exist.
Function InsStrRev (String , SubString , Endpos) Return the
position where the substring exist from endpos of string or return 0 if not
exist.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
96
Other String SUBs/Functions (cont.)
Functions LTrim$(String) , RTrim$(String) and Trim$(String) return a
string which have LEFT , RIGHT or BOTH space characters removed
Function Space$ (amount) return a string with amount space
characters.
Function String$( amount, character) return a string with amount of
characters
Function Replace(String, OldChrs, Newchrs, start, amount,
compareoption) return a string with all sub string OldChrs has been
replace with substringNewchrs. Replacement’s done from start point
of string with amount of time and compareoption used to fine the
Oldchrs sub string.
Function StrReverse (string) return a reversed string of string
Function Ucase$ (string) , Lcase$(string) Uppercase and lowercase a
string
WHAT ‘s ELSE? - See language reference
Department of Information Technology
Nguyễn Cao Trí – [email protected]
97
Conversion Functions
ASC (character) and Chr$(number)
Functions Isnumeric(string) , Val (string) and Str$(number)
CBool(string)
CByte(string)
CCur(string)
CDate(string)
CDbl(string)
CDec(string)
CInt(string)
CLng(string)
CSng(string)
CVar(string)
Other functions Format string, currency,.. See your text book
Department of Information Technology
Nguyễn Cao Trí – [email protected]
98
Date & Time processing
Function Now gets the current date and time.
Function date gets the current date.
Date related functions:
Time related functions:
Weekday, WeekDayName, Month, Year
IsDate : check if sting can be convert to date format
DateSerial , DatePart, DateAdd, Dateiff
Time, Hour, Minute, Second
Timer , TimeSerial
Date and time format
FormatDateTime & Format$
Department of Information Technology
Nguyễn Cao Trí – [email protected]
99
Sample of using Date/Time functions
Private Sub Form_Load()
Call lstOutput.AddItem("Current date and time: " & Now)
Call lstOutput.AddItem("Date: " & Date)
Call lstOutput.AddItem("Day: " & Day(Date))
Call lstOutput.AddItem("Weekday: " & Weekday(Date))
Call lstOutput.AddItem("WeekdayName: " & WeekdayName(Weekday(Date)))
Call lstOutput.AddItem("WeekdayName abbrieviated: " & WeekdayName(Weekday(Date), True))
Call lstOutput.AddItem("Month: " & Month(Date))
Call lstOutput.AddItem("MonthName: " & MonthName(Month(Date)))
Call lstOutput.AddItem("MonthName abbrieviated: " & MonthName(Month(Date), True))
Call lstOutput.AddItem("Year: " & Year(Date))
Call lstOutput.AddItem(#3/2/1976#) ' Date literal
End Sub
Private Sub Form_Load()
Call lstOutput.AddItem("Year: " & DatePart("yyyy", Now))
Call lstOutput.AddItem("Quarter: " & DatePart("q", Now))
Call lstOutput.AddItem("Month: " & DatePart("m", Now))
Call lstOutput.AddItem("Day of year: " & DatePart("y", Now))
Call lstOutput.AddItem("Day: " & DatePart("d", Now))
Call lstOutput.AddItem("Weekday: " & DatePart("w", Now))
Call lstOutput.AddItem("Week: " & DatePart("ww", Now))
Call lstOutput.AddItem("Hour: " & DatePart("h", Now))
Call lstOutput.AddItem("Minute: " & DatePart("n", Now))
Call lstOutput.AddItem("Second: " & DatePart("s", Now))
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
100
Graphic
Coordination system in computer graphic
Drawing on window with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Coordinate system
User define
coordinate system
(0,0)
x
(0,0) x
y
(x,y)
y
(x,y)
Origin coordinate system
•The unit that the coordinate is measured in called a scale.
•Visual basic support difference scales in it system.
•Scale mode can be define by ScaleMode of properties.
•User-define coordinate system allow user to change the origin.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
102
Scale system in Visual basic
Visual basic support 8 (eight) scale systems
Scale
Constant
Value
Description
User defines
vbUser
0
Scale defined by programmer.
Tswips
vbTwips
1
Default for forms and most controls. 1440 twips
per inch. 567 twips per cm. 20 twips per point
Points
vbPoints
2
Commonly used for fonts. 72 points per inch.
Pixels
vbPixels
3
Commontly used with images. Represent a
smallest unit of resolution on a screen.
Characters
vbCharacters
4
120 twips horizontally, 240 twips vertically (12
points)
Inches
vbinches
5
Physical inch.
Millimeters
vbMillimeter
6
Physical Millimeters.
Centimeters
vbCentimeter
7
Physical centimeter.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
103
Changing scale systems
Calling scale method to change the coordinate
and scale system.
Scale (left , top) – (right , low)
Scale (-500, 250) – (500, -250)
The ScaleMode propertie will change to vbUser after call
Scale.
Scale can also be set by setting ScaleTop, ScaleLeft,
ScaleWidth and ScaleHeight properties.
ScaleTop = 250
ScaleLeft = = -500
ScaleWidth = 500
ScaleHeight = -250
ScaleX , ScaleY are used to convert between scales.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
104
Drawing Methods
Print method used to print a text on screen at (CurrentX, CurrentY)
Line method draw lines on a form or control. Can also draw
rectangles.
Line (x1,y1) – (x2,y2)
Line (x1,y1) – (x2,y2) , VbColor, B/BF (not-fill/filled)
Circle method draw circles on a form or control. Can also draw
ellipses or ARC.
Circle (x1,y1) , radius
‘ Circle
Circle (x1,y1) , radius, vbColor, startangle , endangle ‘ Sector
Circle (x1,y1) , radius, vbColor, -startangle , -endangle ‘ Arc
Circle (x1,y1) , radius, vbColor, startangle , endangle , ratio ‘ Ellipse
Pset method set a point’s color , draw a pixel on form.
Pset (x1,x1) , vbColor
Department of Information Technology
Nguyễn Cao Trí – [email protected]
105
Draw Method
Department of Information Technology
Nguyễn Cao Trí – [email protected]
106
Draw Method Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
107
Drawing method : Circle
Private Sub cmdCircle_Click()
Dim x As Single, y As Single
Dim r As Single
Call Randomize
' Randomly pick values to draw at
x = Rnd() * Width
y = Rnd() * Height
r = Rnd() * Height / 10
If Opt1.Value = True Then Circle (x, y), r 'Cirle
If Opt2.Value = True Then Circle (x, y), r, vbRed, 0, 3.14 / 1.5 'Sector
If Opt3.Value = True Then Circle (x, y), r, vbGreen, -3.14 / 2, -3.14 'Arc
If Opt4.Value = True Then Circle (x, y), r, vbGreen, , , 1.5 'Ellipse
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
108
Draw Method : Line
Private Sub cmdLine2_Click()
Dim x1 As Single, y1 As Single
Dim x2 As Single, y2 As Single
Call Randomize
' Randomly pick values to draw at
x1 = Rnd() * Width
y1 = Rnd() * Height
x2 = Rnd() * Width
y2 = Rnd() * Height
If chkfilled.Value = vbChecked Then
Line (x1, y1)-(x2, y2), vbRed, BF ' Filled Rectangle
Else
Line (x1, y1)-(x2, y2), vbRed, B ' Rectangle
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
109
Draw Method: Pset
Private Sub DrawShape()
Dim x As Single, y As Single
Dim totalRadians As Single, r As Single
Dim a As Single, theta As Single
Call Randomize
Scale (3, -3)-(-3, 3)
totalRadians = 8 * Atn(1)
a = 3 * Rnd()
For theta = 0.001 To totalRadians Step
0.01
r = 2 * a / Sin(2 * theta)
x = r * Cos(theta)
' y coordinate
y = r * Sin(theta)
' x coordinate
PSet (x, y)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
110
Drawing Properties
Draw properties used to define how do items be drawn on form.
Property
AutoRedraw
Description
DrawMode
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawMode slide)
DrawStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are draw (see DrawStyle slide)
Drawwidth
An Integer value in range 1 to 32767 that specifies the
drawing width in pixels.
FillStyle
An Integer value that specifies how new points generated
from Line, Circle and Pset are drawn.(see FillStyle slide)
A Boolean value that determones whether or not copy all
graphic element drawn is store in memory
Department of Information Technology
Nguyễn Cao Trí – [email protected]
111
DrawMode Values – Fig 9.12 page 383
Constant
Value
Description
vbBlackness
1
Blackness – Drawing is done in black.
vbNotMergePen
2
Not Merge Pen – Inverse of vbMergePen (15)
vbMaskNotpen
3
Mask Not Pen – combines colors common to the inverse pens’
background color.
vbNotCopyPen
4
Not Copy Pen – Inverse of vbCopyPen (13).
vbMaskNotPen
5
Mask Not Pen – combines the color common to both the pen and the
inverse of the display.
vbInvert
6
Inverse – Inverse of the display color.
vbXorPen
7
Xor Pen – combines the colors in the pen and in the display color ,
but not in both.
vbNotMaskPen
8
Not Mask Pen – inverse of MaskPen (9)
vnMaskPen
9
Mask Pen – combine the colors common to both the pen and the
display.
vnNotXorPen
10
N ot xor Pen – inverse of vbXorPen (7)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
112
DrawMode Values – Fig 9.12 page 383 (cont.)
Constant
Value
Description
vbNop
11
No Operation – Turn off drawing.
vbMergeNotPen
12
Merge Not Pen – combines the display color and the inverse of the
pen color.
vbCopyPen
13
Copy Pen – Default. Drawing is done in the ForeColor.
vbMergePenNot
14
Merge Pen Not – Combines the pen color and the inverse of the
display color.
vbMerPen
15
Merge Pen – Combines the pen color and the display color.
vbWhiteness
16
Whiteness – Draw is done in white.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
113
DrawMode Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
114
DrawStype values - Fig 9.13 page 384
Constant
Value
Description
vbSolid
0
Solid – Default. Drawing is done as a solid.
vbDash
1
Dash – Drawing is done as a series of dashes.
vbDot
2
Dot - Drawing is done as a series of dots.
vbDashDot
3
Dash Dot - Drawing is done as a series of dash and dot
combinations.
vbDashDotDot
4
Dash Dot Dot - Drawing is done as a series of dash, dot, dot
combinations.
vbInvisible
5
Invisible - Drawing is invisible (i.e, transparent)
vbInsideSoloid
6
Inside Solid – Drawing is done inside the solid.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
115
DrawStyle Sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
116
FillStype values - Fig 9.14 page 384
Constant
Value
Description
vbFSSolid
0
Solid the fill is solid
vbFSTransparent
1
Transparent – Default. The fill is not visible.
vbFSHorizontalLine
2
Horizontal Line – The fill is a series of horizontal lines.
vbVerticalLine
3
Vertical Line – The fill is a series of vertical lines.
vbUpwardDiagonal
4
Upward Diagonal – The fill is a series of diagonal lines.
vbDownwardDiagonal
5
Downward Diagonal – The fill is a series of diagonal lines.
vbCross
6
Crossing Line – The fill is a series of crossing horizontal
and vertical lines
vbDiagonalCross
7
Diagonal Crossing Lines – The fill is a series of upward
and downward diagonal crossing lines.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
117
FillStyle sample
Department of Information Technology
Nguyễn Cao Trí – [email protected]
118
Line Control & Shape Control
Line and Shape control provide another way to drawing graphics.
Line’s Color is specified by using Line Control’s BorderColor property
Line’s Style is specifies by using Line Control’s BorderStyle property
Line’s width is specifies by using Line Control’s BorderWidth property
Department of Information Technology
Nguyễn Cao Trí – [email protected]
119
Line Control Sample
Private Sub
cmdButton_Click()
Dim v As Integer
v = txtStyle.Text
If v >= 0 And v <= 6 Then
linLine.BorderStyle = v
Else
linLine.BorderStyle = 1
txtStyle.Text = 1
End If
Department of Information Technology
Nguyễn Cao Trí – [email protected]
120
Line Control & Shape Control
Shape Control can be using to draw rectangles, ellipse, Circle,…
Some properties of Shape control:
BorderStyle ,BorderColor, borderWidth
FillStyle, BackStyle, FillColor, BackColor
BorderStyle’s value is identifies as Line’s BorderStyle’s.
FillStyle , Drawmode have value as mention before.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
121
Colors
Colors on visual basic is created from RGB values (Red, Green,
Blue). Each has value from 0 to 255.
RGB(Red,Green,Blue) return a value of a color as long data style.
pinkColor = RGB(255,175,175)
Some Visual Basic color constants
Department of Information Technology
Nguyễn Cao Trí – [email protected]
122
Colors Sample
ForeColor = RGB(Rnd() * 256, Rnd() *
256, Rnd() * 256)
a = 3 * Rnd() ' Offset used in equation
For theta = 0.001 To totalRadians Step
0.01
r = Sqr(a ^ 2 / theta)
x = r * Cos(theta) ' y coordinate
y = r * Sin(theta) ' x coordinate
x1 = -r * Cos(theta) ' y coordinate
y1 = -r * Sin(theta) ' x coordinate
PSet (x, y)
' Turn pixel on
PSet (x1, y1)
' Turn pixel on
Next theta
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
123
Image & PictureBox
Image can be displayed in form by Image control or PictureBox
control. PictureBox control give more properties and method than
image control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
124
PictureBox Sample
Private Sub Form_Load()
picPicture.Picture = LoadPicture("d:\images\ch09\cool.bmp")
End Sub
Private Sub cmdInvert_Click()
Call picPicture.PaintPicture(picPicture.Picture, 0, 0, , , , , , , vbDstInvert)
Call SavePicture(picPicture, "images\" & "cool_inverse.bmp")
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
125
Printer Object
Printer Object allow user sent text / graphic to printer. By default
printer object ‘s properties correspond to default printer in windows
setup.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
126
Printer object
Department of Information Technology
Nguyễn Cao Trí – [email protected]
127
Graphic User Interface (GUI)
Basic
control and ActiveX control
Advance GUI design
MDI & SDI interface
Ho Chi Minh City University of Technology - Department of Information Technology
Controls
User graphic
interface in VB is
designed by using
controls
Standard Control:
building with VB
ActiveX control
Developed by others
Need to add to VB by
select Projects>Components menu
Menu design
Department of Information Technology
Nguyễn Cao Trí – [email protected]
129
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
130
Standard Controls
Department of Information Technology
Nguyễn Cao Trí – [email protected]
131
Standard Controls
•Standard control is ready to use by VB
•Controls have difference Properties and Methods
•Some standard controls are not available in standard version of Visual Basic.
It’s only available in professional or enterprise versions.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
132
TextBox
Text box is used to display / input text to application.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
133
TextBox
Department of Information Technology
Nguyễn Cao Trí – [email protected]
134
MaskEdit Control (ActiveX)
Used to define how/format/structure of data that user input
to application
Using by add Microsoft MaskEdit control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
135
MaskEdit Control Properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
136
MaskEdit Mask Define
Telephone
6290
(091) 391-
Department of Information Technology
Nguyễn Cao Trí – [email protected]
137
Menu design
Menu is a common GUI
componen in most
windwos applications.
Menu in VB Applications
can be implement by
design it with Menu Edit
Tool.
Select Tools -> Edit to open Menu editor.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
138
Using Edited Menu
Private Sub cmdExit_Click()
End
End Sub
Private Sub mnuExit_Click()
Call cmdExit_Click
End Sub
How to assign function to menu Items?
Department of Information Technology
Nguyễn Cao Trí – [email protected]
139
SDI & MDI interface
Single Document Interface (SDI) : NotePad, Paint
Multiple Document Interface (MDI): Word, Excel
Department of Information Technology
Nguyễn Cao Trí – [email protected]
140
Create and manipulate MDIChild form
Private Sub MDIForm_Load()
Call Load(frmForm3) ' Load child frmForm3
Call Load(frmForm2) ' Load child frmForm2
Call Load(frmForm1) ' Load child frmForm1
End Sub
Private Sub mnuC_Click()
Call frmForm1.Show ' Show child frmForm1
End Sub
Private Sub mnuExit_Click()
Call Unload(frmForm1) ' Unload child frmForm1
Call Unload(frmForm2) ' Unload child frmForm2
Call Unload(frmForm3) ' Unload child frmForm3
End
' Terminate execution
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
141
Arrange MDIChild Windows
Private Sub mnuItem_Click(Index As Integer)
Call mdiParent.Arrange(Index) ' Arrange children
End Sub
Arranged Constant
Department of Information Technology
Nguyễn Cao Trí – [email protected]
142
Records and Files Access
DirListBox,
FileListBox & DriveListBox
Sequential File Processing
Record data structure
Random access file
Using Common Dialog control
Ho Chi Minh City University of Technology - Department of Information Technology
DirListBox , FileListBox & DriveListBox
FileListBox visually list the files in a directory
filFileListBox.Path
DirListBox visually represents the directory
structure of a drive
dirDirListBox.Path
DriveListBox visually lists the drive structure of a
system
drvDrivelistbox.Drive
FileSystemObject, File,Filder,Drive &TextStream
Objects – See pages 586 for detail method
Dim mfileSysObj As New fileSystemObject
Department of Information Technology
Nguyễn Cao Trí – [email protected]
144
Random Access file
Why do we have to access file?
Long term data storage.
Exchange data between users.
Sequences access vs. Random access
Record as user-defined datatype
Private Type ClientRecord
AccountNumber As Integer
Fullname As String * 30
Balance As Currency
End Type
Dim CurrentItem, AccountTable(99) As ClientRecord
Department of Information Technology
Nguyễn Cao Trí – [email protected]
145
Manipulating Fields of Record Type
A variables of Record datatype can be assigned
record value as normal datatype.
AccountTable(5) = CurrentItem
Record datatype can not do compare. However,
its fields can.
Fields of record can be used as a variable of its
datatype. Filed indicated by
RecordName.FieldName
AccountTable(1).FullName = “Bill Clinton”
AccountTable(2).FullName = “Monica”
Record of record: field is a record
Department of Information Technology
Nguyễn Cao Trí – [email protected]
146
Creating a Random Access file
Sub cmdInitialize_Click()
Dim recordLength As Long, x As Integer
Dim udtBlankClient As ClientRecord ' user defined
type
Dim filename As String
' Determine number of bytes in a ClientRecord object
recordLength = LenB(udtBlankClient)
dlgOpen.ShowOpen
filename = dlgOpen.filename
For x = 1 To 100
Put #1, x, udtBlankClient ' Write empty
records
Next
Close #1 ' Close file
cmdInitialize.Enabled = False
MsgBox ("File initialized. Click Exit to
terminate.")
Else
MsgBox ("You must specify a file name")
End If
End Sub
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength
Department of Information Technology
Nguyễn Cao Trí – [email protected]
147
File Open
dlgOpen.ShowOpen
File open dialog
Department of Information Technology
Nguyễn Cao Trí – [email protected]
148
Writing Data to File
dlgOpen.ShowOpen
filename = dlgOpen.filename
Common Dialog
If dlgOpen.FileTitle <> "" Then
Open filename For Random Access Write As #1 Len = recordLength
cmdOpenFile.Enabled = False
cmdEnter.Enabled = True
cmdDone.Enabled = True
Else
MsgBox ("You must specify
a file name")
End If
' Write record to file
Put #1, mUdtClient.accountNumber, mUdtClient
Department of Information Technology
Nguyễn Cao Trí – [email protected]
149
Random and Sequentially Reading data from file
Open file for reading
dlgOpen.ShowOpen
filename = dlgOpen.filename
If dlgOpen.FileTitle <> "" Then
' Open file for writing
Open filename For Random Access Read As #1 Len = recordLength
cmdOpenFile.Enabled = False ' Disable button
Random File READ
Get #1, ItemIndex, Variable
Manipulating thought items
Seek openedfile, index
(index started from 1)
Sequentially File Read
Do
Get #1, , mUdtClient
Loop Until EOF(1) Or mUdtClient.accountNumber <> 0
Department of Information Technology
Nguyễn Cao Trí – [email protected]
150
Database applications
Database management system (DBMS)
Structured query Language (SQL)
Using database with VB
Ho Chi Minh City University of Technology - Department of Information Technology
Database Management System (DBMS)
What is database system?
Why does database used?
Data stored
Data management
Data query
Data relationship maintenance
File vs. Database: Stored data, query, structured data
Data management
Relationship database
Database Management System (DBMS)
Visual basic, relationship database and SQL
Department of Information Technology
Nguyễn Cao Trí – [email protected]
152
Benefit of using database and DBMS
Redundancy can be reduced.
Inconsistency can be avoided.
The data can be shared.
Standard can be enforced.
Security restrictions can be applied.
Integrity can be maintained.
Conflicting requirement can be balanced.
Exchangeable between applications
Upgradeable
Distributed database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
153
Relational Database model
Records and Data Tables
Relational database
Logical representation of the data that allow relationship between
data to be considered.
Composes of tables and their relationship all in once.
Advantage of relational database
Department of Information Technology
Nguyễn Cao Trí – [email protected]
154
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
155
Microsoft ADO Data Control & DataGrid Control
Department of Information Technology
Nguyễn Cao Trí – [email protected]
156
ADO Controls common properties
Department of Information Technology
Nguyễn Cao Trí – [email protected]
157
Structured Query Language (SQL)
SQL is a standard language for query, management
difference database systems.
Some of SQL language keywords
Department of Information Technology
Nguyễn Cao Trí – [email protected]
158
SQL Command
SELECT query: Select data from table(s)
SELECT * From Tablename
Select Au_ID, Author From Authortable
WHERE Clause : Locate record(s) in a database that satisfy
certain Selection criteria
SELECT * From TableName WHERE Criteria
Select * From Authortable WHERE YearBorn >=1990
Select * From Authortable Where Like ‘d[a-f]*’
Note: if fields name has blank please using [ ] to specify filed name.
LIKE operator also can be using as well as >, <, <=, >=, <>, =.
ORDER BY Clause: Arrange the result of query
Select * From tablename Order Fieldname ASC
Select * From tablename Order Fieldname DESC
Select * From AuthorTable Order by Author ASC
Department of Information Technology
Nguyễn Cao Trí – [email protected]
159
SQL Command
INNER JOIN : merge data from multiple tables
Select * From Table1 Inner Join Tabbe2 On Table1.field = Table2.field
SELECT Authors, ISBN FROM Authors INNER JOIN TitleAuthor ON Authors.Au_ID
= TitleAuthor.Au_ID ORDER BY Author ASC
Using Data Environment Designer
Add More ActiveX Designers -> Data environmont .
The Data Environment Designer appears
See document on Using Data Environment to connect to database (Page 797
TextBook)
Department of Information Technology
Nguyễn Cao Trí – [email protected]
160
Slide 25
Foundation of Computer Programming
Visual Basic 6.0
Programming
Instructor: Mr. Nguyen Cao Tri
[email protected]
http://www.dit.hcmut.edu.vn/~caotri
Documents: Course syllabus, lecture’s slide, samples can be found at
http://www.dit.hcmut.edu.vn/~caotri/VB6
Ho Chi Minh City University of Technology - Department of Information Technology
Course Information
Course objectives:
Understand basic theories on Computer software
programming
Understand Microsoft Visual Basic 6.0 syntax and its
major features
Design and develop GUI Windows applications
Develop critical thinking of software programming
Text book/reading material:
Visual Basic 6.0 how to program ,Deitel & Deitel
Cyber classroom CD :Visual Basic 6.0 how to program
Internet Web site access
Department of Information Technology
Nguyễn Cao Trí – [email protected]
2
Introduction
Computing concepts
Programming concepts
Flowchart
Ho Chi Minh City University of Technology - Department of Information Technology
Computing Concepts
Computer
CPU
Processor
I/O
devices
I/O Devices
Storage system: Primary & Secondary
Storage
System
Operating system
User interface: command line , GUI
Programming concepts:
What’s Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms
Department of Information Technology
Nguyễn Cao Trí – [email protected]
4
Programming languages & IDE
Programming languages
Compiler
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.
Interpreter
Compiler
Integrated Development Environment (IDE)
Project manager, Code editor, debug, compiler
Department of Information Technology
Nguyễn Cao Trí – [email protected]
5
Object Oriented Programming (OOP)
What’s Object?
Object properties
Object method
What’s Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic
Object Name (ID)
Properties
Methods
Object 1
Messages
Object 1
Object 1
Department of Information Technology
Nguyễn Cao Trí – [email protected]
6
Algorithms & Flowchart
What’s algorithms
How to present an algorithms?
Natural language, Programming languages
Others?
Flowchart
Characteristic: picture base, chart base
Capability
Advantage:
Simple
Easy to understand
Powerful
Better view and control of Flowchart
Department of Information Technology
Nguyễn Cao Trí – [email protected]
7
Flowchart components
• Start or Begin of algorithms. One START point only.
Start
• Process Flow
• Input / Output data
• Process description / data calculation
No
Condition
• Process Direction Control
Yes
Evaluation Item
• Other Process direction Control
Value 1
Stop
Value i
Others
• Stop or End of algorithms. One/Multi STOP point.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
8
Flowchart Example
Algorithms
ax + b=0 equation solving.
Start
Read a, b
a=0 ?
No
X=-b/a
Yes
b=0 ?
Yes
No
No Solution
Any number
is solution
Stop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
9
Control Structures in programming languages
If
If
else Statement 2;
Case
value 1 : Statement 1;
………..
value n : Statement n;
else
: Statement 0
end;
While
Repeat Statement until
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;
Department of Information Technology
Nguyễn Cao Trí – [email protected]
10
Other terms in computer programming
Data & Data type
Basic data type
integer, long, character, byte, ….
Real (double, float)
Others: string
Structured data type: array, string, record,..
Variable, Constant
Reserve words, keywords
Error : Syntax error, Semantic error, Run time error
Debug : trace, break point, test case
Packet & installation tools
Department of Information Technology
Nguyễn Cao Trí – [email protected]
11
What’s Visual Basic (VB)
Microsoft Windows Programming language
Microsoft IDE for Visual studio developer
Visual Basic versions
Version history
Standard , Professional & Enterprise
What can programmers do with VB?
Windows GUI applications
Database applications
Computer Graphic applications
Internet / WEB applications
………
Department of Information Technology
Nguyễn Cao Trí – [email protected]
12
Visual Basic programming steps
User interface design.
Forms design
Objects/Components properties define
Resource edit : icon, button image,..
Code Writing form “even base” concept.
Compile/Build program
Debug source code
Packet application
Deploy application.
Maintenance
Department of Information Technology
Nguyễn Cao Trí – [email protected]
13
Microsoft Visual Studio IDE
Integrated Development Environment
Project
Tools Box
Form layout
Properties
Menu Bar and Tool Bar
Simple Program develop
Ho Chi Minh City University of Technology - Department of Information Technology
IDE Overview
Menu Bar
Tool Bar
Project
Window
Properties
Window
Department of Information Technology
Nguyễn Cao Trí – [email protected]
15
Project Windows Standard EXE application
Title Bar
Project View
Tool Box
Properties
Form
Department of Information Technology
Nguyễn Cao Trí – [email protected]
16
Other IDE Components
Tool Box
Content all objects/components for FORM design.
Properties Windows
Control all properties of Form/Objects/Components
Display, font, format, enable,…
Project Windows
Project folder view
Form view
Code view
Department of Information Technology
Nguyễn Cao Trí – [email protected]
17
Simple Welcome Program
Program description
How to do that with Visual Basic 6.0
The program will show/hide the text “Welcome to
Visual Basic 6.0” when button Show/Hide is clicked
The exit button used to exit the program. It is available
after first click of Show button only.
Design form with Label object name Label1 and caption “Welcome
to Visual Basic 6.0” Set it visible properties to false.
Add button cmdShowHide & Button cmdExit to form.
Click on each button for writing code to it base on “Click” even
Click Play button on IDE to run program.
See sample below
Department of Information Technology
Nguyễn Cao Trí – [email protected]
18
Simple application FORM design
form1
Label1
Visible = false
Caption = “welcome to Visual Basic
6.0”
cmdExit
Enable = false
cmdShowHide
Caption =“&Show
Department of Information Technology
Nguyễn Cao Trí – [email protected]
19
Simple application Code write
Department of Information Technology
Nguyễn Cao Trí – [email protected]
20
Simple Application Run Time
First run: Only Show button available
Click Hide button: Hide Text
Click Show button: Exit enable, show Text,
Show -> Hide
Click Exit button: Exit Program
Department of Information Technology
Nguyễn Cao Trí – [email protected]
21
Review & Home Work
Review from page 25 -> 47
Drawing the Flowchart for Solving the equation
ax2 +bx + c =0
Redo the simple program
Using Visual Basic 6.0 IDE to build the form
design from page 48->49
Submit to instructor by email.
Pre-View chapters 3 and 4 for next lecture.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
22
Introduction to
Visual Basic programming
Get familiar with Visual Basic Programming
Get familiar with fundamental data types
Using arithmetic operators
Writing simple program in Visual Basic
Ho Chi Minh City University of Technology - Department of Information Technology
Visual Programming & Even Programming
Visual tool of Visual basic for user interface
design (GUI)
Tool Box components
From
Components
Component evens
Even procedure
Some basic components:
Label
Text box
…….
Button (CmdButton)
Frame, Selected box, List box
Department of Information Technology
Nguyễn Cao Trí – [email protected]
24
Visual Basic Tools Box
Icon
ActiveX Control
Horizontal scrollbar
Not a control; enables the mouse pointer
DriveListBox
Label
DirListBox
TextBox
FileListBox
CommandButton
Shape
Timer
Line
PictureBox
Data
Frame
OLE
CheckBox
Animation
OptionButton
UpDown
ComboBox
MonthView
ListBox
DateTimePicker
Vertical scrollbar
FlatScrollBar
Department of Information Technology
Nguyễn Cao Trí – [email protected]
25
Even drive programming
What’s Even?
Component
evens
Even Procedure
The sub procedure will
be done when an
even happened to
component
Each component has its
own evens.
Department of Information Technology
Nguyễn Cao Trí – [email protected]
26
Writing first program with Visual Basic
Print Line of Text on form
Button Exit : exit program on click
Button print: On click, print a line of text “Hello, Welcome to Visual
Basic” on form.
•CODE
Private Sub Command1_Click()
Print " Hello! Welcome to Visual
Basic"
End Sub
Private Sub Command2_Click()
End
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
27
Other Application
Accumulate ADD
Program allow user to enter an
integer number and click add
button. The numbers will be
accumulate and display on
form.
Dim sum As Integer
Private Sub cmdClear_Click()
sum = 0
txtInput.Text = " "
txtAdd.Text = 0
End Sub
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdAdd_Click()
sum = sum + txtInput.Text
txtAdd.text = sum
txtInput.Text = ""
End Sub
Private Sub Form_Load()
cmdClear_Click()
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
28
Syntax and statement
Data type
Variable declaration
DIM variablename As datatype
Ex:
Dim Sum As Integer
Dim Total As Integer
Keywords and reserved words
Statement
Statement end with “end of line”
Assign statement
Variable = Assigned value
Department of Information Technology
Nguyễn Cao Trí – [email protected]
29
Arithmetic
Visual Basic
Operation
Arithmetic
operator
Algebraic
expression
Visual basic
expression
Addition
Subtraction
Multiplication
Division (float)
Division (Integer)
Exponentiation
Negation
Modulus
+
*
/
\
^
Mod
x+y
x–y
ab
v/u
None
Pq
-e
Q mod R
x+y
x–y
a*b
v/u
v\u
p^q
-e
Q mod R
Department of Information Technology
Nguyễn Cao Trí – [email protected]
30
Operators Precedence
Operator
Operation
()
Parentheses
^
Exponentiation
-
Negation
* and /
\
Multiplication and
floating point
division
Integer Division
Mod
Modulus
+ or -
Addition and
Subtraction
Order of evaluation
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs at he same level nested, they are
evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right
Evaluation first. If there are several, they are evaluated
left to right.
Evaluation fourth. If there are several, they are
evaluated left to right.
Evaluation
Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Evaluation Firths. If there are several, they are
evaluated left to right
Department of Information Technology
Nguyễn Cao Trí – [email protected]
31
Comparison Operators
Standard
Algebraic
equality
operator
(relational
operator)
Visual Basic
comparison
operator
Example of
Visual Basic
condition
=
>
<
=
<>
>
<
<=
d=g
S <> R
y>i
P
>=
M >=s
Meaning of Visual Basic
condition
D is equal to g
S is not equal to R
Y is greater than i
P is less than M
C is greater than or equal
to E
M is less than or equal to S
Department of Information Technology
Nguyễn Cao Trí – [email protected]
32
Example of comparison operator
Write a windows program
which allow user input 2
numbers A and B and then
compare and show the
result.
Private Sub cmdExit_Click()
End
End Sub
Private Sub cmdClear_Click()
txtInput1.Text = ""
txtInput2.Text = "“
Label3.Caption = “Result”
End Sub
Private Sub cmdCompare_Click()
Dim input1, input2 As Integer
input1 = txtInput1.Text
input2 = txtInput2.Text
If input1 = input2 Then
Label3.Caption = "First number equal second number"
Else
If input1 < input2 Then
Label3.Caption = "First number less than second
number"
Else
Label3.Caption = "First number greater than second
number"
End If
End If
End Sub
Department of Information Technology
Nguyễn Cao Trí – [email protected]
33
Visual Basic
Control structures
Understanding
control structures of VB
Flowchart and control structures
Using control structure by samples
Ho Chi Minh City University of Technology - Department of Information Technology
If/Then structure
Syntax
if
statements
end if
Condition
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
end if
Yes
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
35
If/Then/Else structure
Syntax
if
statements
else
statements
end if
Condition
No
Example
If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
Label1.Visible = true
else
cmdShowHide.Caption = “&Show”
Label1.Visible = false
end if
Yes
Statements
Statements
Department of Information Technology
Nguyễn Cao Trí – [email protected]
36
While/Wend structure
Syntax
While
statements
Wend
Condition
Yes
No
Statements
Example
Dim product As integer
product = 1
While product <= 1000
product = product * 2
print product
Wend
What’s on form
4 8 16 32 64 128 256 512 1024
Beware of infinite loop
Department of Information Technology
Nguyễn Cao Trí – [email protected]
37
Do while/Loop structure
Syntax
Do while