You are on page 1of 160

Foundation of Computer Programming

Visual Basic 6.0


Programming
Instructor: Mr. Nguyen Cao Tri
caotri@dit.hcmut.edu.vn
http://www.dit.hcmut.edu.vn/~caotri

Documents: Course syllabus, lectures 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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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:
Whats Program
Programming languages: machine code, high level languages
Developing environmental
Algorithms

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

Programming languages & IDE

Programming languages
GO TO Programming : basic, assembly
Structured Programming: Pascal, C,..
Object Programming: Java, C++
Visual approach for GUI programming.

Compiler
Interpreter
Compiler

Integrated Development Environment (IDE)

Project manager, Code editor, debug, compiler

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

Object Oriented Programming (OOP)

Whats Object?
Object properties
Object method
Whats Class?
Message/Even
Object vs. Structure
How can an OOP
program works?
Object and Visual
Basic

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

Object Name (ID)


Properties

Methods

Object 1

Messages

Object 1

Object 1

Algorithms & Flowchart

Whats 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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

Flowchart Example
Algorithms
ax + b=0 equation solving.

Start
Read a, b
a=0 ?

Yes

No

X=-b/a

b=0 ?

Yes

No

No Solution

Any number
is solution

Stop

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

Control Structures in programming languages

If <condition> then Statement;


If <condition> then Statement 1
else Statement 2;
Case <Value> of
value 1 : Statement 1;
..
value n : Statement n;
else
: Statement 0
end;
While <condition> do Statement;
Repeat Statement until <condition>;
For counter=start value to end value do Statement;
For counter=start value downto end value do Statement;

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

11

Whats 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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

15

Project Windows Standard EXE application


Title Bar

Project View

Tool Box
Properties
Form

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

17

Simple Welcome Program

Program description
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.

How to do that with Visual Basic 6.0

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

19

Simple application Code write

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

20

Simple Application Run Time

First run: Only Show button available

Click Hide button: Hide Text


Department of Information Technology
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

Click Show button: Exit enable, show Text,


Show -> Hide

Click Exit button: Exit Program


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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
.

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

Button (CmdButton)
Frame, Selected box, List box

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

25

Even drive programming

Whats 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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
xy
ab
v/u
None
Pq
-e
Q mod R

x+y
xy
a*b
v/u
v\u
p^q
-e
Q mod R

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

30

Operators Precedence
Operator

Operation

()

Parentheses

Exponentiation

Negation

* and /

Multiplication and
floating point
division
Integer Division

Mod

Modulus

+ or -

Addition and
Subtraction

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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

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
C <= E

>=

M >=s

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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

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
Department of Information Technology
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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

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 <condition> then
statements
end if

Example

If cmdShowHide.Caption = &Show then


cmdShowHide.Caption = &Hide
Label1.Visible = true
end if

Yes

Condition

Statements

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

35

If/Then/Else structure

Syntax

if <condition> 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

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

Statements

36

While/Wend structure
Syntax
While <condition>
statements
Wend

Condition

Yes

Example

Dim product As integer


product = 1
While product <= 1000
product = product * 2
print product
Wend

Statements

Whats on form
4 8 16 32 64 128 256 512 1024

No

Beware of infinite loop


Department of Information Technology
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

37

Do while/Loop structure
Syntax
Do while <condition>
statements
Loop

While/Wend

Example

Dim product As integer


product = 1
Do while product <= 1000
product = product * 2
print product
Loop

||
Do while/Loop

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

Whats on form
4 8 16 32 64 128 256 512 1024

38

Do until/Loop structure
Syntax
Do until <condition>
statements
Loop

Statements

Condition

Example

Dim product As integer


product = 1
Do until product >1000
product = product * 2
print product
Loop

No

Whats on form
4 8 16 32 64 128 256 512 1024

Yes

Beware of infinite loop


Department of Information Technology
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

Counter > endValue


Yes

No

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

46

Visual Basic Data type


Data type

Bytes

Range

Boolean

True or False

Byte

0 to 255

Currency

-922337203685477.5808 to 922337203685477.5807

Date

1 Jan 100 to 31 Dec 9999 / 0:00:00 to 23:59:59 (see chapter 8)

Double

-1.79769313486232E308 to -4.94065645841247E-324 (Negative)


1.79769313486232E308 to 4.94065645841247E-324 (Positive)

Integer

-32767 to 32768

Long

-2147483648 to 2147483648

Object

Any Object type (See Chapter 16)

Single

-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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

47

LAB Works

All Samples from text book


Exercises at end of chapters
Assignment Calculator application
Your own applications (option)

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

48

SUB & Function procedure


Procedure in VB
Sub/Function
Recursive

Ho Chi Minh City University of Technology - Department of Information Technology

Module programming

Whats 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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

50

SUB procedure

Create new procedure:


In code windows, select menu
Tools-> Add Procedure

Public Sub
MyProcedure()
Your process codes
here
End Sub
Department of Information Technology
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

53

Call By Value & Call by reference

Whats call by Value?


Whats 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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
Department of Information Technology
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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

55

Sample of Call by value and Call by Reference

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

60

Code modules

Whats code modules


Create code module

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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

Whats an array structure?


What are they used for?
12 24 32

87 16 34

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 :

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

Arrayname(index)
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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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

69

Passing array sample

Passing full array


Department of Information Technology
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

Passing Item by item

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

71

Bubble Sort in Visual basic

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
Department of Information Technology
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

' 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

73

Linear Search

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
Department of Information Technology
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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

77

Binary Search sample

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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)

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

arrayB(3,2,7,0,0)
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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

80

Control Array

Whats 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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

84

Dynamic array sample

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

Variable length - Default


Fix length to 20

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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. Replacements 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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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

(x,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
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

102

Scale system in Visual basic


Visual basic support 8 (eight) scale systems
Scale

Constant

Value

Description

User defines

vbUser

Scale defined by programmer.

Tswips

vbTwips

Default for forms and most controls. 1440 twips


per inch. 567 twips per cm. 20 twips per point

Points

vbPoints

Commonly used for fonts. 72 points per inch.

Pixels

vbPixels

Commontly used with images. Represent a


smallest unit of resolution on a screen.

Characters

vbCharacters

120 twips horizontally, 240 twips vertically (12


points)

Inches

vbinches

Physical inch.

Millimeters

vbMillimeter

Physical Millimeters.

Centimeters

vbCentimeter

Physical centimeter.

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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 points color , draw a pixel on form.


Pset (x1,x1) , vbColor

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

105

Draw Method

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

106

Draw Method Sample

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

110

Drawing Properties
Draw properties used to define how do items be drawn on form.

Property

Description

AutoRedraw

A Boolean value that determones whether or not copy all


graphic element drawn is store in memory

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)

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

111

DrawMode Values Fig 9.12 page 383


Constant

Value

Description

vbBlackness

Blackness Drawing is done in black.

vbNotMergePen

Not Merge Pen Inverse of vbMergePen (15)

vbMaskNotpen

Mask Not Pen combines colors common to the inverse pens


background color.

vbNotCopyPen

Not Copy Pen Inverse of vbCopyPen (13).

vbMaskNotPen

Mask Not Pen combines the color common to both the pen and the
inverse of the display.

vbInvert

Inverse Inverse of the display color.

vbXorPen

Xor Pen combines the colors in the pen and in the display color ,
but not in both.

vbNotMaskPen

Not Mask Pen inverse of MaskPen (9)

vnMaskPen

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

113

DrawMode Sample

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

114

DrawStype values - Fig 9.13 page 384


Constant

Value

Description

vbSolid

Solid Default. Drawing is done as a solid.

vbDash

Dash Drawing is done as a series of dashes.

vbDot

Dot - Drawing is done as a series of dots.

vbDashDot

Dash Dot - Drawing is done as a series of dash and dot


combinations.

vbDashDotDot

Dash Dot Dot - Drawing is done as a series of dash, dot, dot


combinations.

vbInvisible

Invisible - Drawing is invisible (i.e, transparent)

vbInsideSoloid

Inside Solid Drawing is done inside the solid.

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

115

DrawStyle Sample

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

116

FillStype values - Fig 9.14 page 384


Constant

Value

vbFSSolid

Solid the fill is solid

vbFSTransparent

Transparent Default. The fill is not visible.

vbFSHorizontalLine

Horizontal Line The fill is a series of horizontal lines.

vbVerticalLine

Vertical Line The fill is a series of vertical lines.

vbUpwardDiagonal

Upward Diagonal The fill is a series of diagonal lines.

vbDownwardDiagonal

Downward Diagonal The fill is a series of diagonal lines.

vbCross

Crossing Line The fill is a series of crossing horizontal


and vertical lines

vbDiagonalCross

Diagonal Crossing Lines The fill is a series of upward


and downward diagonal crossing lines.

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

Description

117

FillStyle sample

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

118

Line Control & Shape Control

Line and Shape control provide another way to drawing graphics.


Lines Color is specified by using Line Controls BorderColor property
Lines Style is specifies by using Line Controls BorderStyle property
Lines width is specifies by using Line Controls BorderWidth property

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
BorderStyles value is identifies as Lines BorderStyles.
FillStyle , Drawmode have value as mention before.

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

126

Printer object

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

129

Standard Controls

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

130

Standard Controls

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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.
Its only available in professional or enterprise versions.

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

132

TextBox

Text box is used to display / input text to application.

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

133

TextBox

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

135

MaskEdit Control Properties

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

136

MaskEdit Mask Define

Telephone

6290

(091) 391-

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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 -> <Menu
Edit to open Menu editor.

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

139

SDI & MDI interface

Single Document Interface (SDI) : NotePad, Paint


Multiple Document Interface (MDI): Word, Excel

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
If dlgOpen.FileTitle <> "" Then
' Open clients.rnd for writing
Open filename For Random Access Write As #1
-- Len = recordLength

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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

147

File Open

dlgOpen.ShowOpen

File open dialog

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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
Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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?


Data stored
Data management
Data query
Data relationship maintenance

Why does database used?


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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

154

Microsoft ADO Data Control & DataGrid Control

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

155

Microsoft ADO Data Control & DataGrid Control

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

156

ADO Controls common properties

Department of Information Technology


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

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


Nguyn Cao Tr caotri@dit.hcmut.edu.vn

160

You might also like