0% found this document useful (0 votes)
257 views160 pages

Visual Basic 6

This document provides an overview of a course on the foundations of computer programming using Visual Basic 6.0. It outlines the course objectives of understanding basic programming theories, Visual Basic syntax and features, and developing GUI applications. It also lists the required textbook and materials. The document then covers various topics to be taught in the course, including computing concepts, programming concepts, flowcharts, object-oriented programming, algorithms, and an introduction to Visual Basic programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PPS, PDF, TXT or read online on Scribd
Download as pps, pdf, or txt
0% found this document useful (0 votes)
257 views160 pages

Visual Basic 6

This document provides an overview of a course on the foundations of computer programming using Visual Basic 6.0. It outlines the course objectives of understanding basic programming theories, Visual Basic syntax and features, and developing GUI applications. It also lists the required textbook and materials. The document then covers various topics to be taught in the course, including computing concepts, programming concepts, flowcharts, object-oriented programming, algorithms, and an introduction to Visual Basic programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PPS, PDF, TXT or read online on Scribd
Download as pps, pdf, or txt
Download as pps, pdf, or txt
You are on page 1/ 160

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 Storage
 I/O Devices devices System

 Storage system: Primary & Secondary


 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
 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


Nguyễn Cao Trí – [email protected] 5
Object Oriented Programming (OOP)

 What’s Object? Object Name (ID)


 Object properties
Properties
 Object method
 What’s Class?
Methods
 Message/Even
 Object vs. Structure
 How can an OOP Object 1 Object 1
Messages
program works?
 Object and Visual Object 1
Basic
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 • Start or Begin of algorithms. One START point only.

• Process Flow

• Input / Output data

• Process description / data calculation

No
Condition • Process Direction Control
Yes

Evaluation Item
• Other Process direction Control
Value 1 Value i Others

Stop • Stop or End of algorithms. One/Multi STOP point.

Department of Information Technology


Nguyễn Cao Trí – [email protected] 8
Flowchart Example
Start Algorithms
ax + b=0 equation solving.
Read a, b

Yes Yes
a=0 ? b=0 ?
No No

X=-b/a Any number


No Solution
is solution

Stop

Department of Information Technology


Nguyễn Cao Trí – [email protected] 9
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


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
 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


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 Show button: Exit enable, show Text,
Show -> Hide

Click Hide button: Hide Text 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 Button (CmdButton)
Text box 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
Dim sum As Integer
 Accumulate ADD
Program allow user to enter an Private Sub cmdClear_Click()
sum = 0
integer number and click add txtInput.Text = " "
button. The numbers will be txtAdd.Text = 0
End Sub
accumulate and display on
form. 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 Arithmetic Algebraic Visual basic
Operation operator expression expression

Addition + x+y x+y


Subtraction - x–y x–y
Multiplication * ab a*b
Division (float) / v/u v/u
Division (Integer) \ None v\u
Exponentiation ^ Pq p^q
Negation - -e -e
Modulus Mod Q mod R Q mod R

Department of Information Technology


Nguyễn Cao Trí – [email protected] 30
Operators Precedence
Operator Operation Order of evaluation
() Parentheses  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
^ Exponentiation
evaluated left to right
- Negation  Evaluation first. If there are several, they are evaluated
left to right.
* and / Multiplication and Evaluation fourth. If there are several, they are
floating point evaluated left to right.
division
Integer Division Evaluation Firths. If there are several, they are
\
evaluated left to right
Modulus Evaluation Firths. If there are several, they are
Mod evaluated left to right
Evaluation Firths. If there are several, they are
+ or - Addition and
evaluated left to right
Subtraction

Department of Information Technology


Nguyễn Cao Trí – [email protected] 31
Comparison Operators
Standard Visual Basic Example of Meaning of Visual Basic
Algebraic comparison Visual Basic condition
equality operator condition
operator
(relational
operator)
= = d=g D is equal to g
 <> S <> R S is not equal to R
> > y>i Y is greater than i
< < P <M P is less than M
 <= C <= E C is greater than or equal
to E
 >= M >=s 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 Private Sub cmdClear_Click()
txtInput1.Text = ""
which allow user input 2 txtInput2.Text = "“
numbers A and B and then Label3.Caption = “Result”
End Sub
compare and show the
result. 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
Private Sub cmdExit_Click() End If
End End Sub
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  Example
if <condition> then If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
statements
Label1.Visible = true
end if
end if

Yes
Condition

Statements

Department of Information Technology


Nguyễn Cao Trí – [email protected] 35
If/Then/Else structure

 Syntax  Example
if <condition> then If cmdShowHide.Caption = “&Show” then
cmdShowHide.Caption = “&Hide”
statements
Label1.Visible = true
else
else
statements cmdShowHide.Caption = “&Show”
end if Label1.Visible = false
end if
No
Condition
Yes

Statements Statements

Department of Information Technology


Nguyễn Cao Trí – [email protected] 36
While/Wend structure

 Syntax  Example
While <condition> Dim product As integer
product = 1
statements
Wend
While product <= 1000
product = product * 2
print product
Wend
Yes
Condition Statements
What’s on form
No 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  Example
Do while <condition> Dim product As integer
statements product = 1
Loop
Do while product <= 1000
product = product * 2
print product
While/Wend Loop
||
What’s on form
Do while/Loop 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  Example
Do until <condition> Dim product As integer
product = 1
statements
Loop
Do until product >1000
product = product * 2
print product
Statements Loop
Condition
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
Counter = StartValue
a= a+2
Next j Counter = Counter + Stepsize

statements

** Stepsize = 1 is default Counter > endValue


No
value Yes

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
Statements Do
Do
Print counter & Space$(2); Loop While
counter = counter + 1 Yes
Loop Until counter >= 10 Condition

No

 Result
Statements
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10 Do
1 2 3 4 5 6 7 8 9 10 No
Loop Until Condition

Yes

Department of Information Technology


Nguyễn Cao Trí – [email protected] 44
Exit Do / Exit For
counter = 1  For x=1 to 10
Do if x=5 then
Print counter & Space$(2);
exit for
counter = counter + 1
if n = 5 then end if
Exit Do print x
Loop Until counter >= 10 next x

Result: Result:
12345 12345

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
Private Sub callbyVal(ByVal x As Integer)
a = 30 x=x^2
Print "Value of a before call callbyVal " & a Print "Value of x (has been tranfer as a) within
callbyVal a procedure " & x
Print "Value of a after call callbyVal " & a End Sub
Print
End Sub Private Sub callbyref(x As Integer)
x=x^2
Private Sub Command2_Click()
Dim a As Integer Print "Value of x (has been tranfer as a) within
a = 30
procedure " & x
Print "Value of a before call callbyRef " & a End Sub
callbyref a Public Sub ByValandByRef(ByVal x As Integer, y
Print "Value of a after call callbyRef " & a As Integer)
Print x=x^2
End Sub y=y^2
Print "Value of x ,y (know as a,b) within sub " & x
Private Sub Command3_Click() &" "&y
Dim a, b As Integer End Sub
a = 30
b = 20
Print "Value of a,b before ByvalandByref called " & a & " " & b Private Sub Command4_Click()
Print "call ByValandByref and tranfer A as byVal and b as Byref" End
ByValandByRef a, b End Sub
Print "Value of a,b after ByvalandByref called " & a & " " & b
Print
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
 Using Rnd function .
 Rnd return a random number between 0 and 1 (but not 1)
 Scope of variable and const in Sub and Function
 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 : n! = n * (n-1)!
0! =1
 Iteration : 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 Lbound =0 Ubound = Number of Items -1
Example : 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
Private Sub ModifyArray(a() As Integer)
Dim mArray(-5 To 5) As Integer Dim x As Integer
For x = LBound(a) To UBound(a)
Private Sub cmdArray_Click() a(x) = a(x) * 2
Dim x As Integer Next x
Call Initialize End Sub
Call ModifyArray(mArray()) Private Sub ModifyElement(element As Integer)
Call PrintModified element= element * 5
End Sub End Sub

Private Sub cmdElement_Click() Private Sub Initialize()


Dim x As Integer Dim x As Integer
Call Initialize lstOriginal.Clear
For x = LBound(mArray) To UBound(mArray) lstModified.Clear
Call ModifyElement(mArray(x)) For x = LBound(mArray) To UBound(mArray)
Next x mArray(x) = x
Call PrintModified lstOriginal.AddItem mArray(x)
End Sub Next x
End Sub
Private Sub cmdExit_Click() Private Sub PrintModified()
End Dim x As Integer
End Sub 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. Finding the biggest item, put it at end of array
2. Assume that array have one item less
3. Repeat step 1 until the assumed array has only 1
items
4. 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 ' Module modBubble.bas
Option Explicit
Private Sub cmdGenerate_Click()
Dim x As Integer Public Sub BubbleSort(theArray() As Integer)
Call lstOriginal.Clear Dim pass As Integer, compare As Integer
Erase mArray Dim hold As Integer
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(100 * Rnd()) For pass = 1 To (UBound(theArray) - 1)
Call lstOriginal.AddItem(mArray(x))
Next x For compare = 1 To (UBound(theArray) - 1)
Call lstSorted.Clear ' Clear ListBox
cmdSort.Enabled = True If theArray(compare) > theArray(compare + 1) Then
cmdSort2.Enabled = True hold = theArray(compare)
End Sub theArray(compare) = theArray(compare + 1)
Private Sub cmdSort_Click() theArray(compare + 1) = hold
Dim x As Integer End If
Call lstSorted.Clear ' Clear ListBox
Call BubbleSort(mArray) ' Sort the array Next compare
For x = 1 To UBound(mArray)
Call lstSorted.AddItem(mArray(x)) Next pass
Next x
cmdSort.Enabled = False End Sub
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() Function LinearSearch(a() As
Dim searchKey As Integer ' Value to search for
Integer, key As Integer) As
Dim element As Integer ' Index of Value
lblResult.Caption = "" Integer
searchKey = txtKey.Text Dim x As Integer
element = LinearSearch(mArray(), searchKey)
If element <> -1 Then
lblResult.Caption = "Value was found at index: For x = LBound(a) To UBound(a)
" & element
Else
lblResult.Caption = "Value was not found.“ If a(x) = key Then
End If LinearSearch = x ' Return index
End Sub
Exit Function
Private Sub lstData_Click() End If
Dim x As Integer
Call Randomize
Call lstData.Clear Next x
lblResult.Caption = ""
For x = LBound(mArray) To UBound(mArray)
mArray(x) = 1 + Int(10000 * Rnd()) LinearSearch = -1 ' Value not
Call lstData.AddItem(mArray(x)) found
Next x End Function
End Sub
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. Set startindex= lbound (myarray)
2. Set endindex = ubound (myarray)
3. Get miditem = (startindex + endindex ) /2
4. If searchkey = myarray(miditem) then FOUND
5. Elseif searchkey >myarray(miditem) then
6. startitem = miditem +1 and goto step 3
7. else enditem = miditem -1 and goto step 3
8. 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() Do While (low <= high)
Dim middle As Integer middle = (low + high) \ 2
Dim low As Integer, high As Call PrintRow(low, middle, high)
Integer if (searchKey = mArray(middle)) Then
Dim searchKey As Integer Print "Found " & searchKey & " in " _
& "index " & middle
low = mLowBound Exit Sub
high = mUpperBound ElseIf searchKey < mArray(middle) Then
Call PrintHeader high = middle - 1
searchKey = txtKey.Text 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. Select a control -> copy, past it to the same form as many control as you
need, they will be a control array
2. 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 Variable length - Default
Dim StringVariable As String * 20 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() Private Sub cmdStrComp_Click()
Dim result As Integer
If txtInput1.Text > txtInput2.Text Then result = StrComp(txtInput1.Text,
Call lstOutput.AddItem(txtInput1.Text txtInput2.Text)
& " is greater than " & txtInput2.Text)
ElseIf txtInput1.Text < txtInput2.Text If result = -1 Then
Then Call lstOutput.AddItem(txtInput1.Text
Call lstOutput.AddItem(txtInput1.Text & " is less than " & txtInput2.Text)
& " is less than " & txtInput2.Text) ElseIf result = 1 Then
Else Call lstOutput.AddItem(txtInput1.Text
Call lstOutput.AddItem(txtInput1.Text & " is greater than " & txtInput2.Text)
& "equal to " & txtInput2.Text) Else
End If Call lstOutput.AddItem(txtInput1.Text
& " is equal to" & txtInput2.Text)
End Sub 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:
 Weekday, WeekDayName, Month, Year
 IsDate : check if sting can be convert to date format
 DateSerial , DatePart, DateAdd, Dateiff
 Time related functions:
 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 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


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)

Basiccontrol 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 (091) 391-


6290
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 -> <Menu
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() For x = 1 To 100
Dim recordLength As Long, x As Integer Put #1, x, udtBlankClient ' Write empty
records
Dim udtBlankClient As ClientRecord ' user defined Next
type
Dim filename As String Close #1 ' Close file

' Determine number of bytes in a ClientRecord object cmdInitialize.Enabled = False


recordLength = LenB(udtBlankClient) MsgBox ("File initialized. Click Exit to
terminate.")
Else
dlgOpen.ShowOpen MsgBox ("You must specify a file name")
filename = dlgOpen.filename 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 Common Dialog
filename = dlgOpen.filename

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?


 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
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

You might also like