0% found this document useful (0 votes)
413 views772 pages

Learning Visual Basic & Oracle

Uploaded by

mann
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
413 views772 pages

Learning Visual Basic & Oracle

Uploaded by

mann
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 772

Learning

Visual Basic
&
Oracle
VISUAL BASIC
Topics to be covered
 Introduction to OOPs

 Features of VB

 The IDE Environment and the various Windows


OBJECT ORIENTED
PROGRAMMING CONCEPTS
 Object oriented programming - A type of programming in
which programmers define not only the data type of a
data structure, but also the types of operations (functions) that
can be applied to the data structure.
 Object - A software bundle of related variables and methods.
 Messages - Software objects interact and communicate with
each other using messages.
 Class - A class is a blueprint or prototype that defines the
variables and the methods common to all objects of a certain
kind.
 Inheritance - A class inherits state and behavior from its
superclass. Inheritance provides a powerful and natural
mechanism for organizing and structuring software programs.
Object-Oriented Programming
(OOP)
 Object -- anything real or abstract,
about which you store both data and
operations that manipulate the data
 Class -- an implementation that can be
used to create multiple objects with the
same attributes and behavior
 Object is and Instance of a Class
Object-Oriented Terms
 Attribute -- identifying characteristics of
individual objects, such as name or color
 Operation -- an activity that reads or
manipulates the data of an object; called
service in OOD, in OOP called a method
 Message -- has two parts: name of object to
which message is sent, name of operation that
will be performed. In OOP called event
Major Constructs of OOP
 Encapsulation
 Inheritance
 Polymorphism
Encapsulation
 Capability of an object to have data
(properties) and functionality (methods)
available to the user without the user
having to understand the
implementation within the object
 Also called information hiding
 Process of hiding the implementation
details of an object from its user
Inheritance
 A descendent class (subclass) that
differs from its superclass in only one
way contains just the code or data
necessary to explain the difference
 Also known as subclassing
Polymorphism
 Allows an instruction to be given to an
object in a generalized rather than
specific detailed command
 Same command will get different but
predictable results depending on object
receiving command
 Specific actions, internal to object differ,
results are the same
Benefits of OOP
 Reusability -- classes designed to be reused in
many systems or create modified classes using
inheritance

 Stability -- classes designed for repeated reuse,


become stable over time

 Easier Design -- object is a black box

 Faster Design -- can be created from existing


components
What is Visual Basic
 A Programming tool
 What could be created in minutes with Visual Basic
could take days in other languages such: as "C" or
"Pascal".
 Availability of sets of tools to aid in building exciting
applications.
 Controls help to create many applications which use
certain parts of windows. Example, a button. First
create the control ,then write the code which would
be executed once the control button is pressed.
Contd….
 Even though people tend to say Visual Basic's
compiler is far behind the compilers of Pascal
and C, it has earned itself the status of a
professional programming language, and has
almost freed BASIC of the reputation of a
children's language.
 Visual Basic as a Graphics User
Interface(GUI). Because as you draw, you
write for the program.
Graphical User Interface (GUI)
Design
 Should be under user’s control
user should be able to customize
 Form should follow function
 Use concepts and metaphors familiar to user;
parallel real-world experience
 Visually and functionally consistent
 Immediate feedback
 Attempt to prevent user mistakes
User Interfaces & Applications
 User Interface -- way in which you give
instructions to a computer and receive
feedback

 Graphical User Interface (GUI) -- allows use


of both text and graphical images

 Application software -- computer programs


that perform a specific function
Development Environment
 Integrated Development Environment (IDE)

 Single document interface (SDI) --


independent windows on the desktop

 Multiple document interface (MDI) --


windows within windows; contained within
single parent window
Features of Visual Basic

 A complete graphical  Ability to develop


development programs that can be
environment. used as a front end
 Allows users with little application to a database
programming experience system
to quickly develop useful  Serving as the user
Microsoft Windows interface which collects
applications which have user input and displays
the ability to use OLE formatted output in a
( Object Linking and more appealing and useful
Embedding ) objects, such form than many SQL
as an Excel spreadsheet. versions are capable of.
Features of VB
 Easy to create nice  Automatic
looking, graphical generation of much
programs with little of the program code
coding unlike many by the Visual Basic
other languages that program.
may take hundreds
of lines of
programmer keyed
code.
How to start in VB?
& How to create an application!!
Four Steps in Creating VB
Applications
1. Create the Interface using forms and controls

2. Set the Properties in the Properties window

3. Write the Code in the code window

4. Run the form/application to see results


Design Time vs. Run Time
 Design time -- time during which you build an
application

 Run time -- time during which you use an


application for its intended purpose

 Title bar will say [design] during design time


and [run] during run time
STEP- 1
Creating Projects and Forms
 Project (.vbp)
 starts with one form

 may contain several forms

 Form (.frm)
 becomes the application window during

run time
Creating a new project
Create a new project for this application:
Select the File | New | Project menu
entry.
Choose Windows Application from the
New Project dialog displayed.
Type where you want your project to be
stored in the Name and Location fields.
Click the OK button.
The Form In VB
 The main object in
Visual Basic is called
a form. When you
open a new project,
you will start with a
clear form.
Controls in VB
 Can be added to the form.
 Are things like text boxes, check boxes
and command buttons.
 Added to form by choosing them from
the Visual Basic "toolbox" with the
mouse and inserting them in the form.
Toolbox
 Window shown
down the left-
hand side of the
IDE
 Lists all the
controls that you
can add to the
form.
STEP- 2
Setting Properties in
Properties Window
 Once forms/controls are
created, you can change
the properties
( appearance, structure
etc. ) related to those
objects in that particular
objects properties
window.
 Choose the property you
want to change from the
list and change its
corresponding setting.
Project Explorer
 Window on the
right hand side of
the Visual Basic
window
 Lists all the items
in the project
 Lets you choose a
form to modify, or
edit its code.
STEP- 3
Writing Code

 Write the code on appropriate events of


appropriate controls on the form.

 When the form is run, this code gets executed


to display the desired results.
The Code Window
Writing Code
 Events -- messages sent to an object when the application
runs
 can be initiated by user or by application

 trigger procedures

 Procedures -- groups of code statements

 Code Statements -- instructions to computer, written at


design time, execute at run time

 Event procedures in VB written in blocks of code called


subroutines
Function, Methods & Comments
 Function -- code that transforms one or more values into
a new value
 Val function -- takes whatever value is given and

converts it to a number

 Methods -- code statements that can be applied to an


object to change its attributes or behavior
 SetFocus method -- causes focus to be changed to a

specific control on a form

 Comment -- explanatory text within a procedure


 begins with an apostrophe (‘) or keyword Rem
Events
 Add events to controls.
 Are responses to actions performed on
controls.
 Code must be written to create an
event.
 Done in VB’s code window.
Writing an event procedure
The running application displays the text “hello world”
when the button is clicked

Double click on the button to create the even procedure and


add one line:
Private Sub Button1_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
Button1.Click

TextBox1.Text = "hello world"


End Sub
STEP- 4
 Run the application /form just created by
pressing F5 key and see the results.
At runtime, the form displays “Hello
world” when the button is clicked.
Areas of Application

 Education  Commerce
 Research  Marketing and Sales
 Medicine  Accounting
 Business  Consulting
 Law
 Science
Summary
•Object -- anything real or abstract, about which you
store both data and operations that manipulate the
data.
•Class -- an implementation that can be used to create
multiple objects with the same attributes and
behavior.
•Object is an Instance of a Class.
•The major constructs of OOP are Encapsulation,
Polymorphism and Inheritance.
Summary cont…

 Encapsulation is the process of hiding the


implementation details of an object from its user.
 Inheritance is the descendent class (subclass)
that differs from its superclass in only one way
that it contains just the code or data necessary to
explain the difference.
 Polymorphism allows an instruction to be given
to an object in a generalized rather than as a
specific detailed command.
Summary cont…

 VB is a GUI.
 The Graphical User Interface (GUI) allows use of
both text and graphical images.
 VB provides Integrated Development Environment
(IDE).
 It is also known as design environment.
 IDE has no. of components viz. Toolbox, Project
Explorer window, Properties window,Form Layout
window, Form designer and Toolbar.
Summary cont…

Features of VB:

 A complete graphical development environment.

 Allows users with little programming experience to


quickly develop useful applications

 Automatic generation of much of the program code by


the Visual Basic program.
Visual Basic
Topics to be covered
 Introduction to variables in VB

 Their Scope
 Their Datatypes

 Basic Controls in VB

 The Label control


 The Textbox control
 The Command button
Variable
 Memory location whose value can change as the
program is running.
 Used to hold temporary information
 Used to control the type of data used in calculations
 Can store only one piece of data at any time
 Data is processed faster
Data Types
 Byte  Long
 Boolean  Object
 Currency  Single
 Date  String
 Double  Variant
 Integer
Use the Appropriate Data
Type
 Integer or Long - Used to store whole numbers
 Single, Double, Currency - Used to store numbers
with a decimal fraction
 String - Used to store strings
 Boolean - Used to store Boolean values (True and
False)
 Date - Used to store date and time information
 Object - Used to store a reference to an object
 Byte - Used to store binary data
 Variant - Flexible, but not efficient
Variable Names
 Should be meaningful

 First three characters should represent


the data type

 Remainder of name should represent


the variable’s purpose
Three-character Ids
 Byte byt  Long lng
 Boolean bln  Object obj
 Currency cur  Single sng
 Date/Time dtm  String str
 Double dbl  Variant vnt
 Integer int
Rules for Naming Variables
 Name must begin with a letter.
 Name can contain only letters,
numbers, and the underscore. No
punctuation characters or spaces are
allowed.
 Name cannot exceeds 255 characters.
 Name cannot be a reserved word.
Creating (declaring) a Variable

 Dim variablename [As datatype]

 Public variablename [As datatype]


Assigning Values to Variables
 Assignment statement
 variablename = value
 Examples:
 sngHours = 38.5
 curBonus = curSales * .1
 strName = “Susan”
Constants
 Literal constant  Symbolic constant
an item of data a memory location
whose value whose contents
cannot change cannot be
while the program changed while the
is running program is
running
 Examples:  Examples:
7 conPi
“Janet” conRate
Scope of a Variable
 Indicates which
procedures can use
the variable
 Determined by
where the Dim or
Public statement is
entered.
 Can be either global,
form-level, or local.
Local Variables
 Created with the Dim statement.
 The Dim statement is entered in an
object’s event procedure.
 Only the procedure in which it is
declared can use the variable.
 Removed from memory when the
procedure ends.
Form-level Variables
 Created with the Dim statement.
 The Dim statement is entered in a
form’s General declarations section.
 Can be used by any of the procedures
in the form.
 Removed from memory when the
application ends.
Global Variables
 Created with the Public statement.
 The Public statement is entered in a code
module’s General declarations section.
 Used in multi-form projects and can be used
by any of the procedures in any of the
project’s forms.
 Removed from memory when the application
ends.
Option Explicit Statement
 Doesn’t allow you to create variables
“on the fly.”
 Enter in every form’s, and every code
module’s, General declarations section.
 Use Tools, Options, Environment tab,
Require Variable Declaration to have
Visual Basic include Option Explicit in
every new form and module.
Creating a Symbolic Constant
 A memory location whose value cannot
change during run time.
 Syntax: [Public] Const constname [As
datatype] = expression
 Examples:
 Const conPi As Single = 3.141593
 Public Const conMaxAge as Integer = 65
Scope of a Symbolic Constant
 Indicates which procedures can use the
symbolic constant.
 Global: Public Const statement in a code
module’s General declarations section.
 Form-level: Const statement in the form’s
General declarations section.
 Local: Const statement in an event
procedure.
Controls
 Something you place on a form.
 When you see a box to enter text,
or have a drop-down box of
choices, or a button to click, these
are all controls.
How to start a new project
 In Visual Basic, the applications
that you develop are called projects.
 Choose the New command in the
File menu.
 For most projects, you’ll use the
Standard EXE option to start a
project that can be used to create an
executable file, or EXE, that can be
run from any machine that uses
Windows 95, Windows 98, or
Windows NT.
 When you select this option, Visual
Basic starts a new project and
displays a new form for it.
 You can use the Existing and
Recent tabs of the New Project
dialog box to open existing files.
TextBox Control
Enables user to type text from the keyboard and store it in your program.

Property Changes…
Name
d use it in a program TextBox Name
Text By default text1 and value that is
written in textbox

Multiline True/False to store more than one line


of text
Maxlength Maximum no. of characters that can be
enetered
Height Sets height of an object
Textbox Control….
Methods Purpose

Setfocus Moves the focus to specified control or


form

Click Occurs when user presses and then


releases a mouse button over an object

Gotfocus Occurs when an object receives the


focus

Lostfocus When an object loses the focus


Label Control
Enables user to display text and message output.

Property Changes…
Name
d use it in a program Label Name
Caption By default label1 and value that is
displayed on screen.

Alignment To align the caption to left, right or


center.
Height Sets height of an object
Command Button
To run commands

Properties Purpose
Default Boolean value if true sets that button to
be default on form.

Cancel button When Esc key is pressed, code of button


whose cancel property is true gets
executed.
Caption String to be displayed on button

Name Name of the button used in code to


identify it.
Command Button Control….
Methods Purpose

Setfocus Moves the focus to specified control or


form
Click Occurs when user presses and then
releases a mouse button.
Gotfocus Occurs when an object receives the
focus
Lostfocus When an object loses the focus

Refresh Forces a complete repaint of the control.


Examples

Enter text

Clear Insert Date

Exit
Code
 Clear Button
 Text1.text=“”
 Date Button
 Text1.text=date
 Exit button
 Unload me
Summary

 There are 14 data type variables available in VB.

 A variable name always begins with a letter.

 It can be max. of 255 chars.

 It is declared with Dim statement.

 Constant variable’s value cannot be changed and


is declared using ‘const’ keyword.
Summary cont…

 Scope of a variable can be either Private or Form-


wide or Public.

 Private variables are limited to procedures in


which declared.

 Form-wide variables are available to all


procedures within same form.

 Public variables are available to all forms in an


application.
Summary cont…

 The 3 basic controls used in VB applications are


Label, Textbox, Command buttons.

 A Label is used for display purpose ie. to display a


name etc. at runtime.

 A Textbox is used to hold a string entered at


runtime.

 A Command button is used to execute code.


Summary cont…

 The most common/default event of command


button is the Click event.

 The default property of Textbox control is the


text property which holds the string entered in
the textbox at runtime or design time.

 The default property of a Label is caption.


Exercises:

1. Create a form and Textbox. On the press of tab i.e


on Lostfocus of Text1 display whether user has
entered a positive or negative number.
2. Make a form containing two text boxes and
following command buttons.
 On the click of Command1, copy the text of text1
to text2.
 Command2 displays the caption of the Form as the
caption of the button clicked
 Command3 Clears the text of text1 box
Exercises cont…
 Command4 Clears the text of text2 box
 Command5 Clears all. i.e. all textboxes are empty
 Command6 ends the application.

3. Create the form to add/subtract/multiply/divide/ the


two number and show result in text3. Exit button is
used to terminate the program.
Exercises cont…
Number1
3. Number1
Number 2
Text1

Result
Text2

Number 2

Text3
Result

Add SubtractAdd MultiplySubtractAdd Divide

Exit
Visual Basic
Topics to be covered

 Decision Constructs in VB and their use

 Looping Statements in VB and their use


The If..Then statement

This is a decision based statement. It conditionally


executes a group of statements, depending on the value of
an expression.
If condition Then
statement
statement
…..
End If
The If condition takes the form of a comparison between
two values, for example a test for equality or to see if one
value is greater or less than another.
If contd…
Example:
dim a as integer, b as integer
‘where a & b are ages of Sonia and Deepa resp.
a=22
b=25
if a < b then
msgbox(“Sonia is younger”)
Else
msgbox(“Deepa is younger”)
End if
The BMI application
The BMI Application
The BMI is calculated by dividing the weight
in kilos by the square of the height in metres.
A BMI of between 20 and 25 is ideal, less than
this indicates underweight and different
degrees of overweight.

If intBmi < 20 Then


strM = strM & "underweight"
End If
If intBmi >= 20 And intBmi <= 25 Then
strM = strM & "just right"
End If
BMI Application contd…
If intBmi > 25 And intBmi <= 30 Then
strM = strM & "plump"
End If
If intBmi > 30 Then
strM = strM & "overweight"
End If
The If..Then..Else statement
If condition1 Then •You can add as
statement many Else clauses
statement
as you wish
…..
ElseIf condition2 Then •A maximum of one
statement of them is executed.
statement
….. •If none of the If
Else conditions are met,
statement none of the
statement statements are
….. executed.
End If
Improving the BMI application

If intBmi < 20 Then


strM = strM & "underweight"
ElseIf intBmi <= 25 Then
strM = strM & "just right"
ElseIf intBmi <= 30 Then
strM = strM & "plump"
Else
strM = strM & "overweight"
End If
The Select Case statement
The Select Case statement is a useful alternative to using
If..Then..Else statements, it is often easier to read. The
basic syntax of this statement is:
Select Case test expression The test expression must be
Case expression list1 one of the following:
statements
A literal or expression which
Case expression list2 evaluates to one of the
statements following types: Boolean,
…… Byte, Char, Date, Double,
Case Else Decimal, Integer, Long,
statements Object, Short, Single, or
End Select String.
A Third BMI application

A conditional range using the keyword Is.


The use of the keyword Is shown below.
Select Case intBmi
Case Is < 20
strM = strM & "underweight"
Case Is <= 25
strM = strM & "just right"
Case Is <= 30
strM = strM & "plump"
Case Else
strM = strM & "overweight"
End Select
A range using the keyword ‘To’ can also be used.
Case 20 To 25
You can also specify more than one value, for example:
Case 20,21,22,23,24
Looping Constructs

For..Next statement.
For…Each statement.
While...Wend Statement.
Do while..Loop.
Do until ..Loop.

With….End With.
Looping
Looping constructs: these allow you
to repeat a block of code many times,
perhaps changing the value of a
variable each time. There are four
types of construct:
For…Next
For Each…Next
While
Do…Loop
The For…Next statement
The general form of the For..Next loop is:
For counter = start To end Step value
statements ' as many statements as you wish
Exit For ' this optional statement exits the
‘ loop
statements ' as many statements as you wish
Next ' increase the counter
‘ and go to start of loop
Eg. To add all the numbers from 0 to 100 (say)
Dim intTotal As Integer, c As Integer
intTotal = 0
For c=0 To 100
intTotal = intTotal + c
Next c
Eg 2: To add all the even numbers from 0
to 100:
Dim intTotal As Integer, c As Integer
intTotal = 0
For c=0 To 100 Step 2
intTotal = intTotal + c
Next c
debug.print c
The While statement
The While statement, this tests one or more conditions and
executes a series of statements if they are met.
While conditions
statements ' as many as you wish
Exit While
statements
End While
The Exit While statement leaves the loop.
Example: a credit card bill of £10,000 – how long before it
reaches £1,000,000 at 29% interest?
How long to reach a million?

Dim dblDebt As Double


Dim intYears As Integer = 0
dbldebt = CDbl(TxtLoanAmount.Text)
While dblDebt < 1000000
dblDebt = dblDebt * 1.29
intYears += 1
End While
LblTime.Tex ="The debt will reach £1,000,000
in "_
& CStr(intYears) & " years"
The Do While..Loop statement
The Do..Loop statement is functionally very
similar to the While statement.
There are two forms of this statement, the first tests
one or more conditions at the start of the loop:
Do While conditions
statements ' as many as you wish
Exit Do
Statements
Loop
The code below could be used to replace the While
loop in the previous example.
dblDebt = CDbl(TxtLoanAmount.Text)
Do While dblDebt < 1000000
dblDebt = dblDebt * 1.29
intYears += 1
Loop
lblTime.Text="The debt will reach £1,000,000 in
"_
& CStr(intYears) & " years"
The Do..Loop While statement

The alternative form tests at the end:


Do
statements ' as many as you wish
Exit Do
Statements
Loop While conditions
The Exit Do statement exits the loop.
dblDebt = CDbl(TxtLoanAmount.Text)
Do While dblDebt < 1000000
dblDebt = dblDebt * 1.29
intYears += 1
Loop
lblTime.Text="The debt will reach £1,000,000
in “_
& CStr(intYears) & " years"
Functionally the same, however this is not always
the case.
If the test condition is at the end of the loop, the
loop will always execute at least one.
With Statement
 executes a series of statements on a single object or
control
 Syntax:
With object
[statements]
End With
 Example:
With Label1
.FontName = CommonDialog1.FontName
.FontItalic = CommonDialog1.Italic
.FontBold = CommonDialog1.FontBold
.FontSize = CommonDialog1.FontSize
End With
Summary

 The major decision constructs in VB are:


 If…Else..End If
 Select Case….End Case

 These contructs help the user take a decision based


on a condition and accordingly execute a specific
code.

 The Looping statements available in VB are:


 For…Next
 For….Each Next
 Do While….loop and Do Until…loop
 Do…loop while and Do…loop until
 While…Wend
 With….End With

 These statements repeat a group of code


statements a specified number of times
Exercises:
Name

RNo

M1 Compute

M2

Total Exit

Grade
Exercises cont…
1. In the above form,
 Keep textboxes of Total and Grade disabled
 On the Lostfocus of M2 display the total marks (M1
+ M2) and also display grade as
if (M1 + M2) >=80 A
(M1 + M2) >=60 B
(M1+M2) >= 50 C
(M1+M2) >= 40 D
else Fail

2. Give three chances to the user to enter the correct


password and display the relevant message.
Exercises cont…
3.

Principal

Compute
Time

Rate
Exit

Interest
Exercises cont…
Keeping rate disabled, on the got focus of Rate
display rate as 10% and at lost focus of rate
compute interest as P * R * T
100
Exercises cont…
4. Text1 Text2

Setpassword off
Exit

Keeping text2 disabled. Do following:-


What-so-ever is typed in the text1 should be displayed in text2
side-by-side.
Now when the caption of command button is set password off,
then text1 and text2 will display the same text. Every time when
the button is clicked caption changes to set password off if it is
on and On if it is Off. When it is on text2 should display the text
in some password character
Visual Basic
Topics to be covered

 Declaration and use of Arrays

 One-dimensional
 Two-dimensional

 Control Arrays
Arrays
A one-dimensional array is a list of items of the same type.
A list of exam marks
A list of names and addresses
A class list.
Arrays can have more than one dimension, for example a
timetable could be stored as a two–dimensional array. Up to
sixty dimensions are allowed.
Why use arrays?
Consider a list of 25,000 students at DMU. they can all be listed
in a single array, rather than thinking of 25,000 different variable
names.
Declaring Arrays
Before an array can be used it must be declared using
the Dim statement.
Dim name (subscripts) [As type]
For example:
Dim strNameList(5) As String
This defines a one–dimensional array with six
elements: strNameList(0) to strNameList(5)
The first index of an array is 0 by default.
Eg. strNameList(0) = "Rohan"
Two-dimensional Arrays
2-dim arrays are declared as:
dim arr(2,3) as integer
where ‘2’ denotes the no. of rows in the array
and ‘3’ denotes the no. of columns.
The first few elements of this array would be:
arr(0,0), arr(0,1),arr(0,2),arr(1,0),arr(1,1) etc.
Total no. of elements in this array would be
2*3=6.
Arrays contd…
The starting index of any array can be changed
to any other value by declaring the array as:
Dim arr(1 to 5) as integer
or Dim arr(2 to 10) as integer etc.
Now the first element of the array would be:
arr(1) or arr(2)
And the last element would be:
arr(5) or arr(10)
Arrays contd…..
Similarly a 2-dim array can start with an index
value of 1 or any other by declaring as:
Dim arr(1 to 3, 2 to 4) as integer
where the first row index starts from 1 and
the first col. index starts from 2.
So, the first element of this array would be:
arr(1,2)=28
Example:
‘To calculate the sum of the elements of an
array

Dim x(1 to 3) as integer


Dim s as integer
Dim I as integer
x(1)=10
x(2)=20
x(3)=30
For I=1 to 3
s=s+x(I)
Next I
Debug.print s
Changing Array dimensions
You can declare an array without specifying its size,
for example:
' declare an array Dim intRange( ) As Integer
The size can be specified with a ReDim statement
later on.
ReDim intRange(300)
why bother?
You may not know the size of the array where you
declare it. If it is too big memory is wasted.
Using ReDim and Preserve
You can change the size of an existing array with the
ReDim statement.
When you do so all the information in the array is
lost unless the Preserve keyword is used, for
example:
'declare an integer array
Dim Range( ) As Integer

ReDim intRange (20) ' declare its size

'change its size retaining all data.
ReDim Preserve intRange (30)
If you wish to free all the memory an array uses:
Erase intArray
Control Arrays
 a group of controls of the same type
 share a common control name
 share a common set of event procedures
 each control in an array has a unique index number,
starting with 0
 All must have the same Name property setting
 other properties apply to each individual control
Example1:
Object Name Property Name Value
Form Name Form1
 
Caption RCC=> Employees Database
     

Label1 Index 0 (Control Array)


 
Caption Employee Code
Label1 Caption Employee’s Name
  Index 1
Label1 Caption Department Code
 
Index 2
Label1 Caption Designation code
 
Index 3
Label1 Caption Salary
 
Index 4
Label1 Caption Data of Joining
 
Index 5
     
Example 2:
Text1 (it is a control array of 8 elements where
only index property of each text box is changing
starting from 0 to 7, they are used to display the
values of different fields in the table
SUM AND AVERAGE OF TEST SCORES
USING CONTROL ARRAYS:

 Here is another example of a control array. This will


be if you wanted to figure the sum and average of test
scores.

 'Calculating Sum and Average


Private Sub cmdCalculate_Click()
For X = 0 to 9
Sum = Sum + val(txtTest(X))
Next X
Average = Sum / 10
End Sub
  'Clearing text boxes and totals
Private Sub cmdClear_Click()
For Z = 0 to 9
TxtTest(Z) = "“
Next
ZLblSum = "“
LblAvg = "“
Sum = 0
Average = 0
End Sub
Summary

 Arrays are a contigous allocation of storage space for


elements of same type.
 Arrays can be one-dimensional or multi-dimensional.
 Using arrays saves the user from declaring large
number of variables.
 Control arrays are a group of controls of the same type
having a common name and common event procedures.
 They help in making the programming easy for the
user.
Exercises:

1. Get a number from the user and display its


multiplication table in the immediate window.

2.  Write a function which takes an array of


numbers and returns the biggest.

3. Write a function which returns the average of an


array of numbers.
Visual Basic
Topics to be covered

 VB in-built functions (string,numeric,date) and


their use
IN-BUILT FUNCTIONS
 Visual basic has a rich library of functions. Listed
below are some commonly used function.
 
1.  Asc Function
 
Syntax
  Asc(string)
  Returns an Integer representing the character code

corresponding to the first letter in a string. The


required string argument is any valid string
expression. If the string contains no characters, a
run-time error occurs.
 
The range for returns is 0 – 255 on non-DBCS systems,
but -32768 – 32767 on DBCS systems.
 
e.g.
 
MyNumber = Asc("A") ' Returns 65.
MyNumber = Asc("a") ' Returns 97.
MyNumber = Asc("Apple") ' Returns 65.
2. Chr Function
 
 Returns a String containing the character associated

with the specified character code.


Syntax
Chr(charcode)
 The required charcode argument is a Long that

identifies a character.
e.g.
 MyChar = Chr(65) ' Returns A.
 MyChar = Chr(97) ' Returns a.
 MyChar = Chr(62) ' Returns >.
 MyChar = Chr(37) ' Returns %.
3. Date Function
  Returns a Variant (Date) containing the current
system date.

Syntax
Date()

  e.g. MyDate = Date ' MyDate contains the


current system date
 
4.  DateAdd Function
 Returns a Variant (Date) containing a date to which a
specified time interval has been added.

Syntax
DateAdd(interval, number, date)

 Where
interval is “m” for month, “y” for year, “D” for
days
Number is numeric value to be added in date
Date may be current date or any user defined date
5.     DateDiff function

 Returns a Variant (Long) specifying the number of


time intervals between two specified dates.

Syntax
DateDiff(interval, date1, date2)
6.     DatePart Function
 
 Returns a Variant (Integer) containing the specified part

of a given date.
Syntax
DatePart(interval, date)

Interval : String expression that is the interval of time


you want to return.
Date: Variant (Date) value that you want to evaluate.

 The interval argument has these settings:


Setting Description
 
Yyyy Year

Q Quarter

M Month

Y Day of year

D Day

W Weekday

Ww Week

H Hour

N Minute

S Second
e.g.

TheDate = InputBox("Enter a date:")


Msg = "Quarter: " & DatePart("q", TheDate)
MsgBox Msg
7.  Day Function
 
 Returns a Variant (Integer) specifying a whole number

between 1 and 31, inclusive, representing the day of the


month.
 
Syntax
Day(date)
 e.g.

Dim MyDate, MyDay


MyDte = #February 12, 1969# ' Assign a date.
MyDay = Day(MyDate) ' MyDay contains 12.
8. Dir Function
 
 Returns a String representing the name of a file,
directory, or folder that matches a specified pattern or
file attribute, or the volume label of a drive.
Syntax
 
Dir[(pathname[, attributes])]
 
 Pathname:. String expression that specifies a file name

—may include directory or folder, and drive. A zero-


length string ("") is returned if pathname is not found.
 
 Attributes : Constant or numeric expression, whose sum
specifies file attributes. If omitted, all files are returned
that match pathname.

 The attribute argument settings are:


Constant Value Description
 

vbNormal 0 Normal

vbHidden 2 Hidden

vbSystem 4 System file

vbVolume 8 Volume label; if specified, all other attributes


are ignored

vbDirectory 16 Directory or folder


 Dir supports the use of multiple-character (*) and single-character (?)
wildcards to specify multiple files.
 
9. Exp Function
 Returns a Double specifying e (the base of natural logarithms) raised

to a power.

Syntax
Exp(number)
 
10. Format Function

 Returns a Variant (String) containing an expression formatted


according to instructions contained in a format expression.

Syntax
Format(expression[, format[, firstdayofweek[,
firstweekofyear]]])
expression valid expression.
 
format(Optional) A valid named or user-defined format
expression.

Firstdayofweek (Optional). A constant that specifies the


 
first day of the week.

Firstweekofyear (Optional). A constant that specifies the


first week of the year.
Eg.

MyStr = Format(MyTime, "h:m:s") ' Returns


"17:4:23".
MyStr = Format(MyTime, "hh:mm:ss AMPM") ' Returns
"05:04:23 PM".
MyStr = Format(MyDate, "dddd, mmm d yyyy") ' Returns
"Wednesday,' Jan 27 1993".
' If format is not supplied, a string is returned.
MyStr = Format(23) ' Returns "23".
' User-defined formats.
MyStr = Format("HELLO", "<") ' Returns "hello".
MyStr = Format("This is it", ">") ' Returns "THIS IS IT".
 
11. Hour Function

 Returns a Variant (Integer) specifying a whole number


between 0 and 23, inclusive, representing the hour of the day.

Syntax
Hour(time)
 The required time argument is any Variant, numeric

expression, string expression, or any combination, that can


represent a time. If time contains Null, Null is returned.
e.g.
 MyTime = #4:35:17 PM# ' Assign a time.
 MyHour = Hour(MyTime) ' MyHour contains 16.
 
12.     IIf Function
 
 Returns one of two parts, depending on the evaluation of an expression.
Syntax
IIf(expr, truepart, falsepart)
Expr : Required. Expression you want to evaluate.
Truepart : Required. Value or expression returned if expr is True.
Falsepart : Required. Value or expression returned if expr is False.
 e.g.

CheckIt = IIf(TestMe > 1000, "Large", "Small")


If TestMe is 2000 then iif function will return large.

13.    Instr Function


Returns a Variant (Long) specifying the position of the first occurrence
of one string within another.
Syntax
InStr([start, ]string1, string2[, compare])
Start Numeric expression that sets the starting position
for each search. If omitted, search begins at the first
character position. If start contains Null, an error
occurs. The start argument is required if compare is
specified. 

String1 String expression being searched.


String2 String expression sought.
 
Compare Specifies the type of string comparison. The
compare argument can be omitted, or it can be 0, 1or 2.
Specify 0 (default) to perform a binary comparison.
Specify 1 to perform a textual, non case-sensitive
comparison. For Microsoft Access only, specify 2 to
perform a comparison based on information contained in
your database. If compare is Null, an error occurs. If
compare is omitted, the Option Compare setting
determines the type of comparison.
14.     Isarray Function
 
 Returns a Boolean value indicating whether a variable

is an array.
Syntax
IsArray(varname)
e.g.

 Dim MyArray(1 To 5) As Integer, 'Declare array


variables.
 MyCheck = IsArray(YourArray) 'Returns True.
15.      Isdate Function
 Returns a Boolean value indicating whether an

expression can be converted to a date.


Syntax
IsDate(expression)
 MyDate = "February 12, 1969": YourDate =

#2/12/69#: NoDate = "Hello"


 MyCheck = IsDate(MyDate) ' Returns True.
 MyCheck = IsDate(YourDate) ' Returns True.
 MyCheck = IsDate(NoDate) ' Returns False.
 
16.     Isempty Function
 Returns a Boolean value indicating whether a variable has

been initialized.
Syntax
IsEmpty(expression)

 The required expression argument is a Variant containing a


numeric or string expression. However, because IsEmpty is
used to determine if individual variables are initialized, the
expression argument is most often a single variable name.
e.g.
Dim MyVar, MyCheck
MyCheck = IsEmpty(MyVar) ' Returns True.
MyVar = Null ' Assigns Null.
16. Isnull Function

 Returns a Boolean value that indicates whether an


expression contains no valid data
 (Null).

Syntax
IsNull(expression)
 The required expression argument is a Variant
containing a numeric expression or string
expression.

e.g.

 Dim MyVar, MyCheck


 MyCheck = IsNull(MyVar) ' Returns False.
 MyVar = ""
 MyCheck = IsNull(MyVar) ' Returns False.
 
17.  Isnumeric Function
 
 Returns a Boolean value indicating whether an

expression can be evaluated as a number.

Syntax
IsNumeric(expression)

 The required expression argument is a Variant


containing a numeric expression or string expression.
e.g.

 MyVar = "459.95" ' Assign value.


 MyCheck = IsNumeric(MyVar) ' Returns True.
 MyVar = "45 Help" ' Assign value.
 MyCheck = IsNumeric(MyVar) ' Returns
False.
18.  Ltrim Function 

 Returns a string without leading spaces

Syntax
Ltrim(string)

e.g. dim a as string, b as string


b=” hello“
a=ltrim(a) will return “hello”
19.     Month Function
 Returns a Variant (Integer) specifying a whole number

between 1 and 12, inclusive, representing the month of


the year.

Syntax
Month(date)
 The required date argument is any Variant, numeric
expression, string expression, or any combination, that
can represent a date. If date contains Null, Null is
returned.
 MyDate = #February 12, 1969# ' Assign a date.
 MyMonth = Month(MyDate) ' MyMonth contains 2.
20. Now Function

Returns a Variant (Date) specifying the current date


and time according your computer's system date and
time.
Syntax
Now()
e.g.
 msgbox(now) will return 01/01/99 7:12:45 p.m.
21.   Rtrim Function

 Returns a string without trailing spaces

Syntax
Rtrim(string)

e.g.
dim a as string, b as string
b=”hello “
a=rtrim(a) will return “hello”
22.  Trim Function

 Returns a string without trailing spaces and leading


spaces

Syntax
trim(string)

e.g.
dim a as string, b as string
b=” hello “
a=trim(a) will return “hello”
23.    Val Function

 Returns the numbers contained in a string as a


numeric value of appropriate type.

Syntax
Val(string)

 The required string argument is any valid string


expression. The Val function stops reading the
string at the first character it can't recognize as part
of a number. Symbols and characters that are often
considered parts of numeric values, such as dollar
signs and commas, are not recognized.
24.     Weekday Function

 Returns a Variant (Integer) containing a whole number


representing the day of the week.

Syntax
Weekday(date)
e.g.
Dim MyDate, MyWeekDay
MyDate = #February 12, 1969# ' Assign a date.
MyWeekDay = Weekday(MyDate)

‘MyWeekDay contains 4 because ' MyDate represents a


Wednesday.
25.  Year Function

 Returns a Variant (Integer) containing a whole number


representing the year.
Syntax
Year(date)
 The required date argument is any Variant, numeric

expression, string expression, or any combination, that


can represent a date. If date contains Null, Null is
returned.
e.g.
 
 MyDate, MyYear
 MyDate = #February 12, 1969# ' Assign a date.
 MyYear = Year(MyDate) ' MyYear
contains 1969.
26.      Second Function
 
 Returns a Variant (Integer) specifying a whole

number between 0 and 59, inclusive, representing


the second of the minute.
 
 Syntax

  Second(time)

 The required time argument is any Variant, numeric


expression, string expression, or any combination,
that can represent a time. If time contains Null, Null
is returned.
e.g.

 Dim MyTime, MySecond


 MyTime = #4:35:17 PM# ' Assign a time.
 MySecond = Second(MyTime) ' MySecond contains
17.
27. Sqr Function

 Returns a Double specifying the square root of a


number.
 
Syntax
Sqr(number)
 
 The required number argument is a Double or any

valid numeric expression greater than or equal to


zero.
e.g.

Dim MySqr
MySqr = Sqr(4) ' Returns 2.
MySqr = Sqr(23) ' Returns 4.79583152331272.
MySqr = Sqr(0) ' Returns 0.
MySqr = Sqr(-4) ' Generates a run-time error.
28.    String Function
 Returns a Variant (String) containing a repeating

character string of the length specified.

Syntax
  String(number, character)
 
 The String function syntax has these named

arguments:
e.g
MyString = String(5, "*")' Returns "*****".
29.    Str Function
 Returns a Variant (String) representation of a number.

Syntax
Str(number)
 The required number argument is a Long containing any valid
numeric expression. When numbers are converted to strings, a
leading space is always reserved for the sign of number. If number
is positive, the returned string contains a leading space and the plus
sign is implied. Use the Format function to convert numeric values
you want formatted as dates, times, or currency or in other user-
defined formats. Unlike Str, the Format function doesn't include a
leading space for the sign of number.
 
 The Str function recognizes only the period (.) as a valid decimal
separator. When different decimal separators may be used (for
example, in international applications), use CStr to convert a
number to a string.

e.g.
 MyString = Str(459) ' Returns " 459".
 MyString = Str(-459.65) ' Returns "-459.65".
 MyString = Str(459.001) ' Returns " 459.001".
30.  Time Function

 This example uses the Time function to return the


current system time.

Syntax
Time()
e.g.
 Dim MyTime
 MyTime = Time ' Return current system time.
31. MsgBox Function 

 Displays a message in a dialog box, waits for the user to


click a button, and returns an Integer indicating which
button the user clicked.

Syntax
MsgBox(prompt[, buttons] [, title] [, helpfile,
context])

 The MsgBox function syntax has following arguments:


 Prompt(Required). String expression displayed as the
message in the dialog box. The maximum length of
prompt is approximately 1024 characters, depending on
the width of the characters used. If prompt consists of
more than one line, you can separate the lines using a
carriage return character (Chr(13)), a linefeed character
(Chr(10)), or carriage return – linefeed character
combination (Chr(13) & Chr(10)) between each line.
 Buttons(Optional) Numeric expression that is the sum
of values specifying the number and type of buttons to
display, the icon style to use, the identity of the default
button, and the modality of the message box. If omitted,
the default value for buttons is 0.

 Title(optional) String expression displayed in the title


bar of the dialog box. If you omit title, the application
name is placed in the title bar.

Helpfile(Optional) String expression that identifies the


Help file to use to provide context-sensitive Help for
the dialog box. If helpfile is provided, context must also
be provided.
 Context(Optional). Numeric expression that is the Help
context number assigned to the appropriate Help topic
by the Help author. If context is provided, helpfile must
also be provided.

 Settings
The buttons argument settings are:
VbOKOnly 0 Display OK button only.
VbOKCancel 1 Display OK and Cancel buttons.
VbAbortRetryIgnore 2 Display Abort, Retry, and Ignore buttons.
VbYesNoCancel 3 Display Yes, No, and Cancel buttons.
VbYesNo 4 Display Yes and No buttons.
vbRetryCancel 5 Display Retry and Cancel buttons.
vbCritical 16 Display Critical Message icon.
vbQuestion 32 Display Warning Query icon.
vbExclamation 48 Display Warning Message icon.
vbInformation 64 Display Information Message icon.
vbDefaultButton1 0 First button is default.
vbDefaultButton2 256 Second button is default.
vbDefaultButton3 512 Third button is default.
vbDefaultButton4 768 Fourth button is default.
vbApplicationModal 0 Application modal; the user must respond to the
message box before continuing work in the
vbSystemModal 4096 System modal; all applications are suspended
current application.
until the user responds to the message box.
Adds Help button to the message box
vbMsgBoxHelpButton 16384
VbMsgBoxSetForeground 65536 Specifies the message box window as the foreground
window
vbMsgBoxRight 524288 Text is right aligned
vbMsgBoxRtlReading 1048576 Specifies
 
 The first group of values (0–5) describes the number
and type of buttons displayed in the dialog box; the
second group (16, 32, 48, 64) describes the icon style;
the third group (0, 256, 512) determines which button is
the default; and the fourth group (0, 4096) determines
the modality of the message box. When adding numbers
to create a final value for the buttons argument, use
only one number from each group.
Return Values
 

Constant Value Description


 
VbOK 1 OK

VbCancel 2 Cancel

VbAbort 3 Abort

VbRetry 4 Retry

VbIgnore 5 Ignore

VbYes 6 Yes

VbNo 7 No
32. Inputbox Function

 Displays a prompt in a dialog box, waits for the user to


input text or click a button, and returns a String
containing the contents of the text box.

Syntax
InputBox(prompt[, title] [, default] [, xpos] [,
ypos])
Where
 Prompt(Required) String expression displayed as the

message in the dialog box. The maximum length of


prompt is approximately 1024 characters, depending on
the width of the characters used. If prompt consists of
more than one line, you can separate the lines using a
carriage return character (Chr(13)), a linefeed character
(Chr(10)), or carriage return–linefeed character
combination (Chr(13) & Chr(10)) between each line.
 Title(Optional) String expression displayed in the title

bar of the dialog box. If you omit title, the application


name is placed in the title bar.
 Default(Optional) String expression displayed in the text
box as the default response if no other input is provided.
If you omit default, the text box is displayed empty.

 Xpos(Optional) Numeric expression that specifies, in


twips, the horizontal distance of the left edge of the dialog
box from the left edge of the screen. If xpos is omitted,
the dialog box is horizontally centered.

 Ypos(Optional) Numeric expression that specifies, in


twips, the vertical distance of the upper edge of the dialog
box from the top of the screen. If ypos is omitted, the
dialog box is vertically positioned approximately one-third
of the way down the screen.
InputBox always has the buttons OK and Cancel.

Dim strPrompt As String, strTitle As String


Dim strDefault As String, strName As String
strPrompt = "Who are You?"
strTitle = "Search"
strDefault = "Me"
strName = InputBox(strPrompt, strTitle,
strDefault)
Label1.Text = strName
If the user clicks Cancel, a zero-length string is
returned.
Missing Optional Parameter in Inputbox

intRes = InputBox("File name?", "File Input", ,


xpos , ypos)

(No default value)

Must include the comma separator.


Summary

 As we have learnt today, VB provides a number of


in-built functions.
 These functions belong to three major categories
Viz. String fns., Numeric fns., Date & Time fns.
 The in-built functions provided by Visual Basic are
very useful in programming.
 They lessen the code to be written by the user.
Exercises:
1. Make the following stop watch
Text1

Text2

Text3 Compute

Start Exit Stop


Exercises cont…
2. Make form which will have two text boxes and
following command buttons and Labels to display the
result.

String s Text1 a’s


e’s
Resulting s
Text2 i’s
o’s
u’s

Reverse Strlen Exit

Count Vowels Display Vowels Palindrome


Exercises cont…

3. Accept a month from the user and display in the


message box in which quarter does it lies.
Visual Basic
Topics to be covered

 Code Modules

 User-defined Procedures

 User-defined Functions

 Passing parameters to functions and procedures


Code Modules
Any Visual Basic application is collection of modules.

 Modules
 
 A module is collection of procedures, functions and event

handlers. It has following advantages.


 It makes code easy

 Debugging is easy

 Single module can be inserted into more than one project.


 Code in Visual Basic is stored in modules. There are
three kinds of modules: form, standard, and class.

 Simple applications can consist of just a single form, and


all of the code in the application resides in that form
module. As your applications get larger and more
sophisticated, you add additional forms. Eventually you
might find that there is common code you want to
execute in several forms. You don't want to duplicate the
code in both forms, so you create a separate module
containing a procedure that implements the common
code. This separate module should be a standard
module. Over time, you can build up a library of
modules containing shared procedures.
 Each standard, class, and form module can contain:
  Declarations. You can place constant, type, variable,
and dynamic-link library (DLL) procedure declarations
at the module level of form, class or standard modules.
   Procedures. A Sub, Function, or Property procedure
contains pieces of code that can be executed as a unit.

Form Modules
 
 Form modules (.FRM file name extension) are the

foundation of most Visual Basic applications. They can


contain procedures that handle events, general
procedures, and form-level declarations of variables,
constants, types, and external procedures.
 If you were to look at a form module in a text editor, you
would also see descriptions of the form and its controls,
including their property settings. The code that you write
in a form module is specific to the particular application
to which the form belongs; it might also reference other
forms or objects within that application.

Standard Modules
Standard modules (.BAS file name extension) are
containers for procedures and declarations commonly
accessed by other modules within the application. They
can contain global (available to the whole application) or
module-level declarations of variables, constants, types,
external procedures, and global procedures. A standard
module can be reused in many different applications.
Class Modules
 
 Class modules (.CLS file name extension) are the

foundation of object-oriented programming in Visual


Basic. You can write code in class modules to create
new objects. These new objects can include your own
customized properties and methods. Actually, forms are
just class modules that can have controls placed on them
and can display form windows.
Consider the following example of Form Module.
 Code
  Option Explicit
Dim EmployeeNumber As Integer
Dim EmployeeName As String
Private Sub Command1_Click()
EmployeeNumber = InputBox("Enter Number")
EmployeeName = InputBox("Enter Name")
EmployeeBasic = InputBox("Enter Basic")
MsgBox (EmployeeName & " has " &
Trim(Str(EmployeeNumber)) & " employee number.")
End Sub
The following screen will appear.
Consider the example of calculation of simple
interest.The parameters are passed to standard
module and value is returned from standard module
to the calling module

The following code is used in Standard form (with


extension BAS)

Option Explicit
Public Function CalculateInterest(p As Integer, r As
Integer, t As Integer)
Dim si As Double
si = p * r * t / 100
Debug.Print si
CalculateInterest = si
End Function
 
The following code is used in form module (.FRM)
 
Private Sub Command1_Click()
Unload Me
End Sub
Private Sub Command2_Click()

Dim x As Double
Dim p As Integer, r As Integer, t As Integer
p = InputBox("Enter amount")
r = InputBox("Enter rate of interest")
t = InputBox("Enter time ")
x = Module1.CalculateInterest(p, r, t)
Debug.Print x

End Sub
The following screen will appear.
• Procedures

• Passing Parameters
General Procedures
 General Procedures -- include subroutines
(a.k.a. sub procedures) and functions
 Function procedures
 return a value
 can be used in expressions
 Sub procedures can be called, or activated,
by using the procedure name followed by
arguments list
Calling General Procedures
 Insert a line of code with general procedure name
and arguments being passed to initiate a general
procedure
 general procedures have none or more

arguments
 multiple variables, arguments, are separated by

commas within the calling statement


 After general procedure is completed, program
control returns to code statement following one
that called general procedure
Introduction
Event handlers are procedures – a
collection of re-useable code
We can create other procedures – they
may be called from more than one place,
which reduces the need to duplicate code.
Faster and fewer errors.
A function is very similar to a procedure
except that it returns a value.
The Sub statement

Procedures start with the Sub statement


Finish with the End Sub statement
The Sub statement is one of the most complex in
Visual Basic with an extensive range of options –
but we only use small subset:
[access type]Sub name [(argumentList)]
statements
[Exit Sub]
statements
End Sub
The Exit Sub statement is a way of exiting the
procedure before the end of the procedure is
reached as indicated by the End Sub statement.
Eg. Public Sub Biggest(a As Integer, b As Integer, _
c As Integer) As Integer
Dim big as integer
Big = a
If b > Big Then
Big = b
End If

If c > Big Then


Big = c
End If
End Sub

This procedure can be called as follows in two ways:


Call Biggest(2333,87,878)
or Biggest 2333, 87, 878
Functions
Similar to a procedure – but a value is returned.
[access type]Function name [(argumentList)] As[return type]
statements
[Exit Function]
statements
End Function

The Exit Function statement is a way of exiting the procedure


before the end of the procedure is reached as indicated
by the End Function statement.
Eg. Public Function Biggest(a As Integer, b As
Integer, c As Integer) As Integer
Biggest = a
If b > Biggest Then
Biggest = b
End If
If c > Biggest Then
Biggest = c
End If
End Function

The value returned is the value of the variable which


has the function name, in this case Biggest.
This function can be called as follows:
Dim Result As Integer
Result = Biggest(2333, 87, 878)
Parameter Passing
Information can be passed to a procedure or a
function either by reference or by value.

The default is pass by value.

Pass by value

In pass by value, a copy of the value is made. The


original is not used.

Pass by value is like making a copy of a file and


giving it to someone else – if they change it your copy
remains unchanged.
Pass by reference
In pass by reference the address of the original value
is used.
Pass by reference is like giving someone the location
of your original file – if they change it the original
changes.
When a parameter is passed to a procedure by
reference the address of that data is passed.
This has some interesting repercussions on the scope
of variables.

Normally a variable defined in a procedure can only


be changed in that procedure, BUT if you pass it by
reference it can also be changed in the new procedure.
The Power procedure
Let us see how this works in practice by using a small
procedure which uses pass by reference.

Public Sub Power(ByRef intValue As Integer, ByVal


intPow As Integer)
' raise intValue to the power intPow and return the result
in intValue
Dim c As Integer
Dim intResult As Integer
If intPow = 0 Then
intValue = 1
' anything to the power 0 is one, if intPow is 1 no action
required
Else If intPow > 1 Then
intResult = intValue
For c = 1 To intPow – 1
intResult = intResult * intValue
Next c
intValue = intResult
End If
End Sub
Calling the Power procedure

It can be called by the statement:

Call Power(intA, intB)

What happens if the ByRef is changed to


ByVal?

intA is unchanged.

If possible avoid call by reference.


Why?

• The scope is increased


• Harder to find where problems occur
• If two values have to be returned – redesign the code.
Summary
 There are three types of code modules in VB
 Form modules(available to one form only)

 Standard modules(available to all forms of one

project)
 Class modules(related to classes. Used to create

objects)

 User can define his own Procedures or Functions in


VB.

 A user-defined fn. or procedure is nothing but a group


of code statements carrying out a particular task
Summary cont…

 A user-defined function always returns a value while a


procedure may or may not return a value.

 Parameters can be passed to a fn. or procedure either


by value or by reference.

 Changes carried out to a variable passed by reference


to a fn/procedure changes its original value whereas
changes made to a variable passed by value does not
affect its original value.
Exercises:

1. Write a user-defined function to calculate factorial of


a number. The number should be accepted from the
user at runtime.
2. Write a user-defined procedure to accept a string
from the user and display it’s reverse.
3. Write a user-defined procedure to accept a string
from the user and display a message whether it is
palindrome or not.
Visual Basic

LECTURE-7
Topics to be covered

 VB controls:

 Frames
 Option Buttons
 Checkboxes
 Timer control

 Their properties, methods, events and use


Frames
 It’s a container control.

 Used to group other controls (viz. option


buttons,checkboxes etc.) on the form, both visually and
functionally.

 Controls can be moved around on a frame but not


outside the frame.
Option Buttons And Check Boxes
 Allows you to display multiple choices from
which the user can choose only one. An
OptionButton control displays an option that can
be turned on or off. Usually, OptionButton
controls are used in an option group to display
options from which the user selects only one. You
group OptionButton controls by drawing them
inside a container such as a Frame control, a
PictureBox control, or a form. All OptionButton
controls within the same container act as a single
group. Only one can be selected from group.
 CheckBox and OptionButton controls function similarly
but with an important difference: Any number of
CheckBox controls on a form can be selected at the same
time. In contrast, only one OptionButton in a group can
be selected at any given time.
OPTION BUTTONS

 The VALUE property of the option button is set


TRUE if you want it to be selected, otherwise,
FALSE.
 Set the option buttons CAPTION property to the
text you want to appear next to the option button.
 When assigning an option button, a variable name
always starts out with the prefix, opt
 If you want an event to occur when you click on an
opt button, you can double-click on the opt button to
place code behind the opt button.
Example:

‘ Setting fonts of the text

If option1.value=True then
text1.font=“Arial”
Elseif option2.value=True then
text1.font=“Algerian”
Elseif option3.value=True then
text1.font=“Impact”
End If
CHECK BOXES
 More than one check box can be selected at a time.
 The VALUE property of the option button is set
to CHECKED if you want it to be selected,
otherwise, set it to UNCHECKED.
 A second option is to set the VALUE property on
check boxes to a 0, 1 or 2.
0 - UnChecked
1 - Checked
2 - Grayed
 Set the CAPTION property to the text you would
like to appear next to the check box
 When assigning a variable name, always start out with
prefix chk

 If you want an event to occur when you click on a chk


box, double-click the button to place code behind.
Example:

‘Setting font style of the text

If (check1.value=True and check2.value=True) then


Text1.fontbold=True
Text1.fontitalic=True
Elseif (check1.value=True and check2.value=False) then
Text1.fontbold=True
Text1.fontitalic=False
Elseif (check1.value=False and check2.value=True) then
Text1.fontbold=False
Text1.fontitalic=True
Else
Text1.fontbold=False
Text1.fontitalic=False
End If
Properties
Properties Description Value Setting
 
Determines the name used in code to    
Name
identify the object
3D or flat 0 Flat
Appearance
1 3D
Alignment Sets the alignment of an object 0 Left alignment
1 Right alignment
Sets the back color of label   Select color form pull down
BackColor
menu
Caption String to be displayed on button.    

Enabled Determines whether to respond user’s True Enabled


action or not. False Disabled
Font Font, style setting of the button.   On clicking this property, a
dialogue box will appear.
Sets the fore color of label   Select from pull down menu
ForeColor
Sets the graphics to be displayed, if   Select from dialogue box.
Picture
style is set to 1 0 Standard
Style Determines the appearance of
control, whether standard or graphics 1 Graphics
TabIndex Sets the tab order of the object    

Visible Whether a button is visible or hidden True Visible


False Hidden
Value Determines the state of check box True Checked
False Unchecked
Methods Method Description
   

Refresh Forces a complete repaint of the control

SetFocus Moves the focus to the specified control or form. The object
must be a Form object, MDIForm object, or control that can
receive the focus. After invoking the SetFocus method, any
user input is directed to the specified form or control. You can
only move the focus to a visible form or control
Events
Events Description
 

Click Occurs when the user presses and then releases a mouse button over an object. It
can also occur when the value of a control is changed. For a Form object, this
event occurs when the user clicks either a blank area or a disabled control. User
has to write the code in code view.
GotFocus Occurs when an object receives the focus, either by user action, such as tabbing
to or clicking the object, or by changing the focus in code using the SetFocus
method. A form receives the focus only when all visible controls are disabled. If
click and GotFocus both events are written, on clicking button, only gotfocus
event will be executed and also focusing using tab, gotfocus event will be
executed.
LostFocus Occurs when an object loses the focus, either by user action, such as tabbing to
or clicking another object, or by changing the focus in code using the SetFocus
method.
Properties Description Value Setting
Properties  

Name Determines the name used in code to    


identify the object

Enabled Whether user’s actions can be True Enabled


responded or not

Interval Number of milliseconds between calls    


to timer control’s time event

Description
Events Event
 

Timer Occurs when a preset interval for a Timer control has elapsed. The
interval's frequency is stored in the control's Interval property, which
specifies the length of time in milliseconds.
The Timer Control
The Timer control allows you to trigger an event
at regular intervals
The Timer control starts when the Enabled
property is True.
The Interval property sets the time between
events in milliseconds (1000 to the second).
The Timer control is invisible at runtime.
Size of the Timer control is fixed.
The Timer control has no method.
Timer Control Application
Timer Control
Private Sub Timer1_Timer()
txtCounter.Text = CInt(txtCounter.Text) + 1
lblTime.Text = Now

Dim strPic(2) As String


strPic(0) = "a"
strPic(1) = "b"
strPic(2) = "c"
Dim intC As Integer = CInt(txtCounter.Text) Mod 3
picBike1.picture = Loadpicture(“c:\images\a1.jpg”)

End Sub
Timer Control
Private Sub btnStart_Click()

txtCounter.Text = 0
If txtInterval.Text > 0 Then
Timer1.Interval = CDbl(txtInterval.Text) * 1000
End If
Timer1.Enabled = True
End Sub

Private Sub btnStop_Click()


Timer1.Enabled = False

End Sub
Summary
 Option Buttons allow the user to choose any one option
out of a group of buttons.

 To keep more than one group of option buttons on the


form, each group must be placed in a separate frame.

 Check Boxes allow the user to choose more than one


options out of the group.

 The Timer control allows the user to carry out a


specific action repeatedly after every set interval of
time.
Exercises
1. My font form using control arrays and functions
or procedures.
Text1

Reset
Font Name
O Courier
O Sansserif
Change text
O Vineta BT
O Proxy I

Red O
Green O
Font style

Bold Color
Itallics
Size
Regular
O 10
O 20
O 30
Exercises cont…

2. Make an application using appropriate controls to


create Traffic Light system.
Exercises cont…
3. Pizza Order
1)
Pizza Size Topping

Mushroom Onion O Large Cheese


O Medium
O Small
Salami Cheese
Single Veg.

Chicken Onion Cheese


Single non-Veg.

Order Type

O Eat-in Check Order


O Take out or Pack

Cancel Order Bill


Exercises cont…
2)On the click of check order a msgbox should appear
displaying different option. Selected from above.
Also asking the user for surety.
On the click of yes display another form form2 of type.
Is the order all right

Yes No

Pizza Ordered
Pizza names

Size

Topping

Amount
Sales tax OK
STAX
Back
Total Amount
Exercises cont…
4. Calender

Time August

Running Time 6
Using
timer control
Visual Basic

LECTURE-8
Topics to be covered
 VB controls

 File controls
 Scroll bars
 PictureBox
 ImageBox
File System Controls
 The file system controls enable you to add file
system navigation functionality to your
application. The following are the file system
controls:

·        DriveListBox
·        DirListBox
·        FileListBox
DriveListBox Control
 The DriveListBox control is a drop-down list box used to
present a list of available computer drives. No code is
required to get the list or to determine which drives are
on the computer. The DriveListBox control gets the drive
information for you from the operating system.

  DirListBox Control
 The DirListBox control works a lot like the DriveListBox
control. The DirListBox control displays a list of the
current directories and subdirectories for the current
drive.
FileList Box Control
 
 Files are displayed using the File List Box control. The
File List Box control displays all the files in the current
drive and folder. The File List Box control has
properties that enable you to set up search criteria to
limit or expand the filenames displayed in the list box.
The pattern property provides a filter to set up file-
specific search criteria. For instance, if you want to see
all the files in a folder, use the default *.* setting of the
property. Suppose you want to see only files with an
EXE extension. The following code limits the files
displayed, in the list box to only those files with an
EXE extension:
File1.Pattern = *.EXE
 To connect the File controls,appropriate values must be
assigned to them.
 To force the DirListbox to display the folders of the
selected drive in the DriveListbox, the following code
must be written in the Drivelistbox’s change event.

Private Sub Drive1_change()


Dir1.Path=Drive1.Drive
End Sub

 Similarly,everytime the current selection in the Dirlistbox


control changes,the Filelistbox’s Path property must be
set to point to the new path of the Dirlistbox control.
Private Sub Dir1_Change()
File1.Path=Dir1.Path
End Sub

 The Path property sets or returns the current path for


the file listbox, but not for the operating system.
 The Drive property of DriveListbox contains the
currently selected drive name.

 The Path property of DirListbox contains the


currently selected directory name

 The Filename property of FileListbox contains the


currently selected filename.
Hscroll Bar
 It’s the Horizontal scrollbar.

 Provides a graphical tool for quickly navigating


through a long list of items or a large amount of
information, for indicating the current position on
a scale, or as an input device or indicator of speed
or quantity.
Properties
Properties Description Value Setting
 

Name Determines the name used in code to    


identify the object
Enabled Whether user’s actions can be True Enabled
responded or not
False Disabled

LargeChange Sets the amount of change to value Any  


property of scroll bar when user
clicks the scroll bar area
Max Set maximum value to value   Default is 32767
properties
Min Set minimum value to value   Default is 0
properties
MousePointer Type of the mouse pointer displayed   Select from pulldown
when user clicks the scroll bar area menu. Default is 0

Visible Whether control can be visible or True Visible


not.
    False Invisible
Events

Events Description
 

Change Moves the scroll box portion of the scroll bar. Occurs when the user scrolls or
when you change the Value property setting through code.

Click Occurs when the user presses and then releases a mouse button over an object.
It can also occur when the value of a control is changed. For a Form object,
this event occurs when the user clicks either a blank area or a disabled control.
User has to write the code in code view.

GotFocus Occurs when an object receives the focus, either by user action, such as
tabbing to or clicking the object, or by changing the focus in code using the
SetFocus method. A form receives the focus only when all visible controls are
disabled. If click and GotFocus both events are written, on clicking button,
only gotfocus event will be executed and also focusing using tab, gotfocus
event will be executed.
LostFocus Occurs when an object loses the focus, either by user action, such as tabbing
to or clicking another object, or by changing the focus in code using the
SetFocus method.

Scroll Occurs when the scroll box on a ScrollBar control, or an object which
contains a scrollbar, is repositioned or scrolled horizontally or vertically.
Methods
 
Method Description

Refresh Forces a complete repaint of the control

SetFocus Moves the focus to the specified control or form. The object must be
a Form object, MDIForm object, or control that can receive the
focus.After invoking the SetFocus method, any user input is directed
to the specified form or control. You can only move the focus to a
visible form or control
Vscroll Bar
 It’s the Vertical Scroll Bar

 Provides a graphical tool for quickly navigating


through a long list of items or a large amount of
information, for indicating the current position on
a scale, or as an input device or indicator of speed
or quantity.
Properties
 
Properties Description Value Setting
 

Name Determines the name used in code    


to identify the object

Enabled Whether user’s actions can be True Enabled


responded or not
False Disabled

Sets the amount of change to value Any  


LargeChange
property of scroll bar when user
clicks the scroll bar area

Set maximum value to value   Default is 32767


Max
properties
Set minimum value to value   Default is 0
Min
properties
Type of the mouse pointer displayed   Select from pulldown
MousePointer
when user clicks the scroll bar area menu. Default is 0

Visible Whether control can be visible or True Visible


not.
False Invisible
Methods

Method Description
 

Refresh Forces a complete repaint of the control

SetFocus Moves the focus to the specified control or form. The object must
be a Form object, MDIForm object, or control that can receive the
focus. After invoking the SetFocus method, any user input is
directed to the specified form or control. You can only move the
focus to a visible form or control
Events
 
Events Description
 

Change Moves the scroll box portion of the scroll bar. Occurs when the user
scrolls or when you change the Value property setting through code.

Click Occurs when the user presses and then releases a mouse button over an
object. It can also occur when the value of a control is changed. For a Form
object, this event occurs when the user clicks either a blank area or a disabled
control. User has to write the code in code view.

GotFocus Occurs when an object receives the focus, either by user action, such as
tabbing to or clicking the object, or by changing the focus in code using the
SetFocus method. A form receives the focus only when all visible controls
are disabled. If click and GotFocus both events are written, on clicking
button, only Gotfocus event will be executed and also focusing using tab,
gotfocus event will be executed.
LostFocus Occurs when an object loses the focus, either by user action, such as tabbing
to or clicking another object, or by changing the focus in code using the
SetFocus method.
Scroll Occurs when the scroll box on a ScrollBar control, or an object which
contains a scrollbar, is repositioned or scrolled horizontally or vertically.
Image Control
 The Image control to is used to display a graphic.
An Image control can display a graphic from a
bitmap, icon, or metafile, as well as enhanced
metafile, JPEG, or GIF files.
 The Image control uses fewer system resources
and repaints faster than a PictureBox control, but
it supports only a subset of the PictureBox
properties, events, and methods.
 Use the Stretch property to determine whether the
graphic is scaled to fit the control or vice versa.
Although you can place an Image control within a
container, an Image control can't act as a
container.
Properties
Properties Description Value Settings
 
Determines the name used in code    
Name
to identify the object
Appearance 3D or flat 0 Flat
1 3D
BorderStyle Sets the border style of the object 0 None
1 Single
Sets the field from where the   Select from pull down menu
DataField
displayed string will be taken
Determines the datasource   Select from pull down menu
DataSource

Enabled Determines whether button can True Enabled


respond to user generated events
False Disabled
Sets the graphics to be displayed on   Select from dialogue box
Picture
the control
Stretch Sets a value that determine whether True Allowed
a graphics resizes to fit size of an
False Not allowed
image control
Visible Sets a value that determine whether True Allowed
the object can be made visible or
False Not allowed
hidden
Methods
Method Description
 

Move Move a control. The Syntax object. Move left, top, width,
height

Refresh Forces a complete repaint of the control


Events

Events Description

Click Occurs when the user presses and then releases a mouse
button over an object. It can also occur when the value of
a control is changed. For a Form object, this event occurs
when the user clicks either a blank area or a disabled
control. User has to write the code in code view.
Image Control contd…
Loading a Graphic Into the Image Control

 Pictures can be loaded into the image control at design time


by selecting the Picture property from the control's
Properties window, or at run time by using the Picture
property and the LoadPicture method

Image1.Picture=LoadPicture("c:\Windows\Winlogo.bm
p")
 When a picture is loaded into the image control, the control
automatically resizes to fit the picture — regardless of how
small or large the image control was drawn on the form.
 To clear the graphic from the image control, use
the LoadPicture method without specifying a file
name. For example:
Image1.Picture = LoadPicture

 This will clear the image control even if a graphic


was loaded into the Picture property at design
time.
PictureBox Control
 The picture box control is used to display
graphics, to act as a container for other controls,
and to display output from graphics methods or
text using the Print method.

 The picture box control is similar to the image


control in that each can be used to display
graphics in your application — each supports the
same graphic formats. The picture box control,
however, contains functionality which the image
control does not, for example: the ability to act as
a container for other controls and support for
graphics methods.
Supported Graphic Formats

 The picture box control can display picture files in any


of the following formats: bitmap, icon, metafile,
enhanced metafile, or as JPEG or GIF files.
PictureBox Control contd…

Using the Clipboard

 You can also add a graphic to a picture box control


at design time by pasting it from another
application. For example, you may want to add a
bitmap image that was created in Windows Paint.
Simply copy the image to the clipboard, select the
picture box control, and either use the keyboard
shortcut CTRL+V or the Paste command from the
Edit menu.
Sizing a Picture

 By default, graphics are loaded into a picture box at


their original size, meaning that if the graphic is larger
than the control, the image will be clipped — the picture
box control does not provide scroll bars. To make a
picture box control automatically resize to display an
entire graphic, set its AutoSize property to True. The
control will then size to the graphic — growing or
shrinking.
PictureBox Control contd…
 Unlike the image control, the picture box
control cannot stretch the image to fit the
size of the control.

Using the Picture Box Control as a


Container
 You can use the picture box control as a

container for other controls. For example,


since the picture box can be placed inside the
internal area of a MDI form, it is often used
to manually create a toolbar or status bar.
Graphics Methods
 Picture boxes, like forms, can be used to receive the
output of graphics methods such as Circle, Line, and
Point. For example, you can use the Circle method to
draw a circle in a picture box by setting the control's
AutoRedraw property to True.

Picture1.AutoRedraw = True
Picture1.Circle (1200, 1000), 750
 Setting AutoRedraw to True allows the output from
these methods to be drawn to the control and
automatically redrawn when the picture box control is
resized or redisplayed after being hidden by another
object.
Using the Print Method
 You can use the picture box control to output text
by using the Print method and setting the
AutoRedraw property to True. For example:
Picture1.Print "A text string"

 When using the Print method you can also modify


the font style and size or use the CurrentX,
CurrentY, Height, and Width properties to align
text within a picture box.
 The primary use for the picture box control is to display
a picture to the user. The actual picture that is displayed
is determined by the Picture property. The Picture
property contains the file name (and optional path) for
the picture file that you wish to display.
 Form objects also have a Picture property that can be set
to display a picture directly on the form's background.
 To display or replace a picture at run time, you can use
the LoadPicture function to set the Picture property. You
supply the name (and optional path) for the picture and
the LoadPicture function handles the details of loading
and displaying it:

picMain.Picture=LoadPicture("VANGOGH.BMP")
 The picture box control has an AutoSize property that,
when set to True, causes the picture box to resize
automatically to match the dimensions of its contents.
Take extra care in designing your form if you plan on
using a picture box with the AutoSize enabled. The
picture will resize without regard to other controls on
the form, possibly causing unexpected results, such as
covering up other controls. It's a good idea to test this by
loading each of the pictures at design time.
Using the Picture Box as a Container

 The picture box control can also be used as a container


for other controls. Like the frame control, you can draw
other controls on top of the picture box. The contained
controls move with the picture box and their Top and
Left properties will be relative to the picture box rather
than the form.

 A common use for the picture box container is as a


toolbar or status bar. You can place image controls on it
to act as buttons, or add labels to display status messages.
By setting the Align property to Top, Bottom, Left, or
Right, the picture box will "stick" to the edge of the form.
Loading a Graphic Into the PictureBox
Control 
 Pictures can be loaded into the picture control at design time
by selecting the Picture property from the control's
Properties window, or at run time by using the Picture
property and the LoadPicture method.

Picture1.Picture=LoadPicture("c:\Windows\Winlog.bmp")

 To clear the graphic from the picture control, use the


LoadPicture method without specifying a file name. For
example:
Picture1.Picture = LoadPicture
This will clear the image control even if a graphic was
loaded into the Picture property at design time.
When to Use an Image Control
Instead of Picture Box Control
 The image control uses fewer system resources and
repaints faster than a picture box control, but it supports
only a subset of the picture box control's properties,
events, and methods. Both controls support the same
picture formats. However, you can stretch pictures in an
image control to fit the control's size. You cannot do this
with the picture box control.
Summary
 The File controls are used to traverse the host computer’s
file system and locate any folders or files on the hard disk.

 The 3 file controls ie. Drivelistbox, Dirlistbox and


Filelistbox are independent of each other but rarely used
separately.

 There are 2 types of scroll bars available in VB viz.


Horizontal scrollbar and Vertical scrollbar.

 They are used to reposition the view in a long document or


in a large picture.
Summary cont…

 The Picturebox control is a container control.

 It is used to display pictures/icons on the form.

 The image control is not a container control.

 This is also used to display images on the form.

 Both the controls Picture property is used to load the


picture/image.
Exercises:

1. Write the code to display the contents of Filelistbox.

2. Create a form. Place three vertical scrollbars on it and


one picturebox.Also place a command button. Write
code such that on click of the command button the
background color of the picturebox should change
according to the settings of the 3 scrollbars(each
scrollbar is used to change the amount of red, green
and blue color resp.).
Visual Basic

LECTURE-9
Topics to be covered

 VB controls

 ListBoxes
 Comboboxes

Their properties, methods, events and use


Listbox Control
 Used to display a list of items from which the user
can choose one.
 The list can be scrolled if it has more items than
can be displayed at one time.
 If no item is selected, the ListIndex property value
is -1.
 The first item in the list is ListIndex 0, and the
value of the ListCount property is always one
more than the largest ListIndex value.
Properties Description Value Setting
 
Name Determines the name used in code    
to identify the object
Items Allows entry of list items    

Column Whether a listbox scrolls vertically 0 Vertically scroll


in a single column or horizontally
in snaking column
    Other Horizontal

Multiselect Allows multiple selection of list 0 Allows only single selection


items 1 Simple multiple selection
2 Extended multiple selection

Sorted Whether items are to be sorted True sorted


alphabetically or not
False Not sorted

Style Whether checkboxes are displayed 0 Standard


inside list control
1 Checkbox

Text Sets the text contained in the    


contol.
Method Description

AddItem Adds an item to control. The syntax is object.AddItem item, index

where object(Required). An object expression that evaluates to an


object in the Applies To list. Item(Required). string expression
specifying the item to add to the object. Index(Optional) Integer
specifying the position within the object where the new item or row is
placed. Use 0 for first row.
Clear Clears the contents of a ListBox, ComboBox,

RemoveItem Removes an item from a ListBox or ComboBox control. The syntax is


object. RemoveItem index
Where object(Required). An object expression that evaluates to an
object in the Applies To list. Index(Required). Integer representing
the position within the object of the item or row to remove. Use 0 for
first row.
SetFocus Moves the focus to the specified control or form. The object must be
a Form object, MDIForm object, or control that can receive the
focus. After invoking the SetFocus method, any user input is
directed to the specified form or control. You can only move the
focus to a visible form or control
Events Description
 

Click Occurs when the user presses and then releases a mouse button over an
object. It can also occur when the value of a control is changed. For a Form
object, this event occurs when the user clicks either a blank area or a disabled
control. User has to write the code in code view.

GotFoucs Occurs when an object receives the focus, either by user action, such as
tabbing to or clicking the object, or by changing the focus in code using the
SetFocus method. A form receives the focus only when all visible controls
are disabled. If click and GotFocus both events are written, on clicking
button, only gotfocus event will be executed and also focusing using tab,
gotfocus event will be executed.
ItemCheck Occurs when a ListBox control Style property is set to 1 (checkboxes) and an
item’s checkbox in the ListBox control is selected or cleared.

LostFocus Occurs when an object loses the focus, either by user action, such as tabbing
to or clicking another object, or by changing the focus in code using the
SetFocus method.

Scroll Occurs when the scroll box on a ScrollBar control, or an object which
contains a scrollbar, is repositioned or scrolled horizontally or vertically.
The ListBox Control Application

You can select one or more of the sports: as you do so,


the sports you have selected are displayed in the
TextBox control at the bottom of the form.
You can add a new sport to the list by typing it into the
TextBox on the right of the form and clicking the Add a
new sport button.
You can delete one or more selected sports by clicking
on the Delete selected sports button.
Creating the application
Design time changes:

•To allow more than one item to be selected, change


the SelectionMode property from One to
MultiExtended, which allows all entries between a
selected item and another item to be selected when
the Shift key pressed.

•If set to MultiSimple, allows a number of items to


be selected by clicking on each of them in turn.
• Set the Text properties of the two TextBox controls to
"", so that no text is displayed when the application
starts.

• The Items property allows items to be added to at


design time.

• Can use the Add method of the property Items at run-


time.
Application cont…(The Form load Event)
Private Sub frmSelectSport_Load()
lstSports.Additem "Soccer"
lstSports.Additem "Swimming"
lstSports.Additem "Ice Hockey"
lstSports.Additem "Climbing"
lstSports.Additem "Hiking"
lstSports.Additem "Hang Gliding"
lstSports.Additem "Volleyball"
lstSports.Additem "Sleeping"
End Sub
The first item can be accessed by reference to
lstSports.Items(0).
Application cont…(Adding new Sports)

Private Sub btnAdd_Click()


lstSports.Additem txtNewSport.Text
txtNewSport.Text = ""

End Sub
Displaying selected items
•Each selected entry in the ListBox is stored in the
Selected() array. The number of selected items in a
ListBox is given by the ListCount property
(lstSports.listCount)

•The first selected item is stored in Selected(0).


For example the first selected item can be copied to a
String:

Dim strSport as String


strSport = lstSports.Selected(0)

When the Sports button is clicked, every selected item


is added to the selected sports displayed in the
txtChosen TextBox at the bottom of the form.
Displaying selected items (Continued)
Private Sub lstSports_SelectedIndexChanged()

Dim c As Short
txtChosen.Text = ""
For c = 0 To lstSports.SelCount - 1
txtChosen.Text = txtChosen.Text & " " & _
lstSports.Selected (c) & " "
Next c

End Sub

Note the For …. Next loop used to work through the


items.
Listbox Application cont…(Deleting Sports)
The Removeitem method is used, this requires each of
the selected items to be passed to it.

Private Sub btnDelete_Click()


Dim c As Short
For c = lstSports.SelCount - 1 To 0 Step -1
lstSports.Removeitem lstSports.Selected(c)
Next c
txtChosen.Text = ""

End Sub
(Note the use of Step -1, we have to work from the
back of the items to be deleted.)
The Combobox Control
 
Allows you to draw a combination list box and
text box. The user can either choose an item from
the list or enter a value in the text box.
Major Properties
 
Properties Description Value Setting
 

Name Determines the name used in code to    


identify the object
Sorted Whether items are to be sorted True sorted
alphabetically or not
False Not sorted

Style Determines the type and behavior of 0 (Default) Dropdown Combo.


control. Includes a drop-down list and
a text box. The user can select
from the list or type in the text
box.
1 Simple Combo. Includes a text
box and a list, which doesn't
drop down. The user can
select from the list or type in
the text box.
2 Dropdown List. This style
allows selection only from
the drop-down list.
Text Sets the text contained in the control.    
Methods
Method Description
 
AddItem Adds an item to control. The syntax is

object.AddItem item, index

where object(Required). An object expression that evaluates to an object


Item(Required). string expression specifying the item to add to the object.
Index(Optional) Integer specifying the position within the object where the new
item or row is placed. Use 0 for first row.
Clear Clears the contents of a ListBox, ComboBox,

RemoveItem Removes an item from a ListBox or ComboBox control. The syntax is

object.RemoveItem index

Where object(Required). An object expression that evaluates to an object.


Index(Required). Integer representing the position within the object of the item
or row to remove. Use 0 for first row.
SetFocus Moves the focus to the specified control or form. The object must be a Form
object, MDIForm object, or control that can receive the focus. After invoking
the SetFocus method, any user input is directed to the specified form or
control. You can only move the focus to a visible form or control
Events
Events Description
 

Change For ComboBox — changes the text in the text box portion of the control.
Occurs only if the Style property is set to 0 (Dropdown Combo) or 1 (Simple
Combo) and the user changes the text or you change the Text property setting
through code.

Click Occurs when the user presses and then releases a mouse button over an
object. It can also occur when the value of a control is changed. For a Form
object, this event occurs when the user clicks either a blank area or a disabled
control. User has to write the code in code view.

DropDown Occurs when the list portion of a ComboBox control is about to drop down;
this event doesn't occur if a ComboBox control's Style property is set to 1
(Simple Combo).

GotFoucs Occurs when an object receives the focus, either by user action, such as
tabbing to or clicking the object, or by changing the focus in code using the
SetFocus method. A form receives the focus only when all visible controls
are disabled. If click and GotFocus both events are written, on clicking
button, only gotfocus event will be executed and also focusing using tab,
gotfocus event will be executed.
GotFocus Occurs when an object receives the focus, either by user action, such as
tabbing to or clicking the object, or by changing the focus in code using
the SetFocus method. A form receives the focus only when all visible
controls are disabled. If click and GotFocus both events are written, on
clicking button, only gotfocus event will be executed and also focusing
using tab, gotfocus event will be executed.

LostFocus Occurs when an object loses the focus, either by user action, such as
tabbing to or clicking another object, or by changing the focus in code
using the SetFocus method.

Scroll Occurs when the scroll box on a ScrollBar control, or an object which
contains a scrollbar, is repositioned or scrolled horizontally or vertically.
The ComboBox control

There are 3 types of combo box:

Simple. This version comprises a TextBox and a list


which is always displayed. You can select an item or type
your own text.
Dropdown. This version has a TextBox and a list which
drops down below it. You can select an item from the
list or type your own text in the text box.

DropDownList. This is the same as a DropDown


ComboBox except that while you can select an item
from the list you cannot type your own text.
ComboBox Application

Design–time properties:
•The ComboBox DropDownStyle property is
changed to DropdownList.

•The SizeMode property of the PictureBox control


is changed to Stretch, so that the picture resizes
itself to fit the control.
ComboBox Application (Continued)
You can add the options displayed in the ComboBox at
design-time by using the Items property, we will do it at
run-time.

Private Sub frmMotorCycles_Load()


Dim c As Short
strFiles(0) = "View1"
strFiles(1) = "View2"
strFiles(2) = "View3"
For c = 0 To 2

cboViews.Additem strFiles(c)
Next
cboViews.SelectedIndex = 1

End Sub
ComboBox Application (Continued)
•An array of strings is defined called strFiles. Each
element contains the name of a view.
•The name of the file containing the picture of that view is
stored in a file of the same name.
•The SelectedIndex property which indicates the selected
item is assigned the value 1.
•This statement causes a SelectedIndexChanged event to
occur.

Private Sub cboViews_SelectedIndexChanged()


picCycle.Picture =Loadpicture(“c:\images\a2.jpg”)
lblView.Text = cboViews.SelectedItem
End Sub
Summary

 A Listbox is used to display a set of items.

 User can select one or more items from the listbox.

 User cannot enter new value in the listbox at runtime.

 A combobox is an expandable listbox.

 It is a combination of listbox and textbox.


Summary cont…
• There are 3 types of combobox- Simple combo,
Dropdown combo and Dropdown list.
• It occupies less space on the screen as compared
to listbox.
• User can select only one value in a combobox.
• User can enter new value also at runtime instead
of choosing from the list.
Exercises

1. Write a program to add items to a list using list


box from a text box and from textbox to list.
Exercises cont…
2. Write a program like

List 1
Master List 2
List

<<

>>
Exercises cont…
 Command 1 Should add selected item from the master
list to list2. This should also be possible by double click
of that item.

Command 2 from List2 to list 1 however should not


get repeated.

 Command 3 Adds all the item from list2 to list1.

Command 4 Add all items from list1 to list2 and no


repetition is allowed.
Exercises cont…
3. Using list boxes, comboboxes and picture box if
the selected file is picture file. Make Form Open
drive Project. Text1
C:\

File
Names
List1

Read only

Hidden System

Status bar
Exercises cont…

On the double click of list1 Activate picture box if


select file is a picture file
File name should appear else in the status bar

Picture box contain J Label


Else Active text box to display text of the file.
Visual Basic

LECTURE-10
Topics to be covered

 VB controls
 Common Dialog Controls and their use
CommonDialog Control
 generalized sequence of run-time steps
 code statement applies the appropriate Show

method to CommonDialog control


CommonDialog1.ShowFont
 user changes values of its properties

CommonDialog1.FontSize = 12
 code statements use the new property values to

change appearance or behavior of application


Label1.FontSize = CommonDialog1.FontSize
-This control is invisible at runtime and
cannot be resized.
Standard Common Dialogs
Four common dialogs are there:

•Color Dialog.

•Font Dialog.

•Open Dialog.

•Save Dialog
The ColorDialog control

To display all the custom colours the CdlccFullOpen


flag is set. Set the CdlccHelpbutton flag to display a
Help button on the dialog (pressing creates a
dlgColour.HelpRequest)
e.g.
dlgColour.flags=cdlccHelpbutton or cdlccfullopen
dlgColour.Showcolor
Me.BackColor = dlgColour.Color
The FontDialog Control

•Set the Cdlcfeffects flag to allow the font colours etc.


to be changed.
•Also set Cdlcfscreenfonts or Cdlcfprinterfonts or
Cdlcfboth flag to open the font dialog box.
e.g.
dlgFont. Flags=cdlcfboth or cdlcfeffects
dlgFont.Showfont
txtChameleon.Fontbold = dlgFont.Fontbold
txtChameleon.ForeColor = dlgFont.Color
The OpenDialog control

The InitDirectory property determines


which directory is displayed when the
dialog is first displayed.
The OpenDialog control contd…
The Filter property ensures that only files with a
specified extension are displayed.

"text | *.file extension | text | *.file extension"


•You can have as many text | *.file extension pairs as you
wish.
dlgOpenFile.Filter = "bmp files (*.bmp)|*.bmp|jpg
_files(*.jpg)|*.jpg| gif files(*.gif)|*.gif|All files (*.*)|*.*"
The OpenDialog control contd…

The Filename property returns the name of the chosen


file:

picHoliday.Image Image.FromFile(dlgOpenFile.FileName)

The FromFile method is passed a string. And returns an


Image object, which is displayed in the PictureBox.
If the Cancel button on the dialog is pressed no file is
selected:an ArgumentException is created - use a Try
Catch clause

Try
picHoliday.Image = Image.FromFile(dlgOpenFile.FileName)
Catch exnNoPicture As System.ArgumentException
End Try
The OpenDialog control contd…
Property/Flag Description
FileName Returns the name of the single
file selected.
FileTitle Returns the name of selected file
without path information.
cdlofNallowMultiSel Sets or returns whether selection
ect of more than one file is allowed.
cdlofNReadOnly Sets or returns whether read-only
files are displayed.
Defaultext Sets the default extension of the
dialog box.
The SaveAsDialog control

•The SaveAsDialog is similar in appearance and


properties to the OpenDialog.
•The Overwrite property returns or sets a value to
indicate if a warning dialog is displayed if an existing
file is to be over-written.
Summary
 All Windows applications use some standard dialog
boxes for common operations,such as selecting a font
or opening a file.
 The Common Dialog control provides some of these
built-in windows dialog boxes for use in a VB
application.
 It cannot be resized although it can be moved around
the form.
 The Common Dialog control is not visible at runtime.
 This control has no events.
Visual Basic

LECTURE-11 & 12
Topics to be covered

 Creating Menus
 The RichtextBox control
 Text manipulation properties
Creating Menu using Menu Editor
 

You can use the Menu Editor to create new menus and
menu bars, add new commands to existing menus,
replace existing menu commands with your own
commands, and change and delete existing menus and
menu bars.
 
 
To display the Menu Editor
 
From the Tools menu, choose Menu Editor.
–  or  –
Click the Menu Editor button on the toolbar.

This opens the Menu Editor, shown in following figure .


While most menu control properties can be set using the
Menu Editor, all menu properties are available in the
Properties window. The two most important properties for
menu controls are:
 
•· Name This is the name you use to reference the menu
control from code.
 
•·Caption This is the text that appears on the control.
• The menu control list box (the lower portion of the
Menu Editor) lists all the menu controls for the current
form.

• When you type a menu item in the Caption text box,


that item also appears in the menu control list box.

• Selecting an existing menu control from the list box


allows you to edit the properties for that control.
Creating Menu
 
Select the form.
• From the Tools menu, choose Menu Editor.
   
•In the Caption text box, type the text for the first menu title that you
want to appear on the menu bar.

•Also, place an ampersand (&) before the letter you want to be the
access key for that menu item.

•This letter will automatically be underlined in the menu.

•The menu title text is displayed in the menu control list box.
           
• In the Name text box, type the name that you will use
to refer to the menu control in code.

• Click the left arrow or right arrow buttons to change the


indentation level of the control.

• Set other properties for the control, if you choose. You


can do this in the Menu Editor or later, in the Properties
window. Choose Next to create another menu control.
• Choose OK to close the Menu Editor when you
have created all the menu controls for that form.

• The menu titles you create are displayed on the


form.

• At design time, click a menu title to drop down its


corresponding menu items.
Separating Menu Items
 
A separator bar is displayed as a horizontal line between
items on a menu. On a menu with many items, you can use a
separator bar to divide items into logical groups. To create a
separator bar in the Menu Editor, consider the following
steps.
 
If you are adding a separator bar to an existing menu,
 Choose Insert to insert a menu control between the
menu items you want to separate.

   If necessary, click the right arrow button to indent the


new menu item to the same level as the menu items it
will separate.
 Type a hyphen (-) in the Caption text box.

    Set the Name property.


    Choose OK to close the Menu Editor
Assigning Access Keys and
Shortcut Keys
 
You can improve keyboard access to menu commands by
defining access keys and shortcut keys.
 

Access Keys
 
Access keys allow the user to open a menu by pressing the
ALT key and typing a designated letter. Once a menu is
open, the user can choose a control by pressing the letter
(the access key) assigned to it.
To assign an access key to a menu control in the Menu
Editor
 
  Select the menu item to which you want to assign an
access key.
 In the Caption box, type an ampersand (&)
immediately in front of the letter you want to be the
access key.
Shortcut Keys
 
Shortcut keys run a menu item immediately when
pressed. Frequently used menu items may be assigned a
keyboard shortcut, which provides a single-step method of
keyboard access, rather than a three-step method of
pressing ALT, a menu title access character, and then a
menu item access character.

Shortcut key assignments include function key and


control key combinations, such as CTRL+F1 or CTRL+A.
To assign a shortcut key to a menu item
 
•  Open the Menu Editor.
•  Select the menu item.
• Select a function key or key combination in the
Shortcut combobox.
The RichTextBox Control

An extended version of the TextBox control:


unlike the TextBox it can display text in a
variety of fonts and sizes in the same
control.You can save the formatting features.
Introduction

 There are many things the can be done with a rich text control.
You can create a word processor that has multiple features
including put bullets, automatic save & load, and being able to
superscript & subscript. All of these and more will be shown
in here.

 Because most visual basic programmers already know the


main functions of the regular textbox, I'll skip that part of the
rich textbox control.  The main function I use the rich textbox
is to save and load files.  The rich textbox makes very simple
to create save and load files. There are three parts to a rich
textbox, the textbox, the file path, and the file type.  You don’t
need to specify the file type if the file path already contains it.
Saving a file:

Object.Save (FilePath, FileType)

Loading a file:

Object.Load (FilePath, FileType)

 As you can see loading and saving are very similar and
very simple.  
This saves everything including text, color, and bullets.
 
Basic Formatting
 There are many different settings for the format of a rich
textbox.  The four basic ones are: SelBold, SelItalic,
SelUnderline, and SelStrikethru.  These are all
booleans(True or False).  Any text editing after these are
changed will be displayed the way selected, but the text
already there will not bet changed.

Changing these settings:

Object.SelBold = Boolean
Object.SelItalic = Boolean
Object.SelUnderline = Boolean
Object.SelStrikethru = Boolean
RichTextBox1.SelUnderline = True
'Any text after this property is turned on will be
underlined

Next you will learn how to change the font size and
font name. Changing the font size and name is very
simple.  You just need to know the name of the font
you want.  Also the font name doesn't have to be case
sensitive.
Changing the font name
Object.SelFontName = FontName

If the font name is a variable, then you don't requir


quotes, else you must put quotes around it

RichTextBox1.SelFontName = "Times New Roman"


'Or
Dim Font As String
Font = "Times New Roman"
RichTextBox1.SelFont = Font
 The font size is even simpler

Object.SelFontSize = Integer

RichTextBox1.SelFontSize = 12
'The following text will be size 12

The number for a font size doesn't need to be in quotes,


but a variable could represent a number.
Inserting text
 Inserting text with the rich textbox control is made very
simple.  
 It has three parts: SelStart, SelLength, and SelText.
  The SelStart is where the text is going to be inserted (in
letters), and can't be longer than the the text.  
 SelLength is the total number of letter that will be
deleted after SelStart.  
 SelText is the text that is going to replace the SelLength.
 If SelLength is zero the SelText will just be inserted
where SelStart is.
Object.SelStart = Integer
Object.SelLenth = Integer
Object.SelText = Text

'RichTextBox1 displays "Good "


RichTextBox1.SelStart = 5
RichTextBox1.SelText = "Evening"
'RichTextBox1 now displays "Good Evening
 If you want to replace text I suggest you do the Replace
function.  The following is how to make a replace
function.

Object = Replace(String, Find, ReplaceWith, _


Start, NumerToCorrect)

Dim Temp As String


'I prefure to use a variable
Temp = RichTextBox1.Text
'RichTextBox1 displays "aaAaAAaa"
Temp = Replace(Temp, "a", "B", 2, 3)
RichTextBox1.Text = Temp
'RichTextBox1 now displays "aBABAABa"
 It replaced 3 "a" with "B" starting from the second letter
of Temp and then set the text back to Temp.  

 That is how the replace function works.  You can skip


the number of times to replace, and it will replace every
existence after the start.  If you skip the start, it will start
searching from the beginning.
Indents & Aligning
 There are 3 different indents: SelHangingIndent, Indent,
RightIndent.  
 The SelHangingIndent is how much of an indent there is on
the lines after the first.
 Indent is how much space there is before the first line of a
paragraph.  Right Indent is the indent of the right side.  
 These are all adjusted with a number that using the same scale
at the width, height, top, and left (not pixels.)

Object.SelHangingIndent = Number
Object.SelIndent = Number
Object.SelRightIndent = Number
'RichTextBox1 displays:
'Hi,
'Bye
RichTextBox1.SelHangingIndent = 100
RichTextBox1.SelIndent = 200
'RichTextBox1 now displays:
'      Hi,
'   Bye
 The right indent just stops the text from the right side, but
I didn't want to get too complicated.  Setting the
alignment for a single line is just like setting the
alignment for a whole textbox.

Object.SelAlignment = Number

The alignment numbers are the same for a regular


textbox: 0 - Left Alignment, 1 - Right Alignment, 2 -
Center Alignment.

'RichTextBox1 display:
'Hello
RichTextBox1.SelAlignment = 2
'RichTextBox1 now display:
'                 Hello
Colors, bullets & superscript

 First there's coloring.  You set this by changing the


SelColor to the color of your choice.  You can use any
color (vbcolor, RGB, QBColors).

Object.SelColor = color

RichTextBox1.SelColor = vbGreen
'Now anything typed will be green
 Now protecting.  Protecting disabled editing from the
selected text

Object.SelProtected

RichTextBox1.SelProtected = True
 Any text that was selected during this method is now
protected.
Bullets are creating by setting the SelBullet property to
true.  This creates bullets where new lines are put, and
the line the cursor was just at.

Object.SelBullets = True
 'RichTextBox displays:
'We are know for:
'Creating programs
RichTextBox.SelBullets = True
'RichTexBox now displays
'We are know for:
'·Creating programs
 With the bullets you can indent them using
BulletIndent

Object.BulletIndent = Integer

'Using the one before


'RichTextBox1 displays:
'We are know for:
'·Creating programs
RichTextBox1.BulletIndent = 200
'RichTextBox1 no displays:
'We are know for:
'·       Creating programs
 Next is how to superscript or subscript. To make
superscript or subscript you have to use the
SelCharOffSet and SelFontSize at the same time.  The
SelCharOffSet just changes the position of the text.  

Using the SelCharOffSet property:

Object.SelCharOffSet property

 
SuperScript:
Dim VariableName As Integer
Object.SelFontSize = Integer / 3 * 2
Object.SelCharOffSet = Temp * 5

That is how you can make a subscript or superscript


font.
 To subscript, you just need to change the SelFontSize.
 If you want to superscript, you must change the font
size and the SelCharOffSet.
Hello

SubScript:
Dim VariableName As Integer
Integer = Object.SelFontSize
Object.SelFontSize = Integer / 3 * 2
'This makes the size 2/3 of the original
Text Manipulation Properties

 The textbox control provides 3 properties for manipulating


the text.

Seltext Property:
It returns the selected text.
Eg.
Text1.seltext = ucase(text1.seltext)

Selstart Property:
It returns the position of the first character of the selected
text.
Sellength Property:

It returns the length of the selected text.

Eg.
Dim x as string
x = “Visual basic”
text1.sellength = len(x)
Summary

 User can create his own menus in VB with the help


of Menu Editor.

 Menus can be attached only to forms.

 Each menu command has 2 mandatory properties viz.


caption and name.

 The Richtextbox control provides all the fuctionality


of a textbox control.
Summary cont…

 In addition, it allows to mix different fonts,sizes and


attributes.

 It can be used to create a notepad type application.

 Text can be manipulated in a Richtextbox or normal


textbox control by using it’s text manipulation
properties viz. seltext, sellength, selstart.
Visual Basic

LECTURE-13
Topics to be covered

 The MDI Form and its use


MDI forms
MDI or Multiple Document Interface forms
consist of child forms contained within a parent
form.

At run-time:
All child forms are displayed within the MDI form,
but they can be moved and sized within this area as
normal.
Both child and parent forms can be minimized.
When a parent form is minimized, it and all the child
forms it contains are represented by a single icon.
MDI Form cont….
 An MDI (multiple-document interface) form is a
window that acts as the background of an application
and is the container for forms that have their MDIChild
property set to True.
 
 You can create an MDIForm object by choosing MDI
Form from the Insert menu. An application can have
only one MDIForm object but many MDI child forms.
If an MDI child form has menus, the child form's menu
bar automatically replaces the MDIForm object's menu
bar when the MDI child form is active. A minimized
MDI child form is displayed as an icon within the
MDIForm.
 An MDIForm object can contain only Menu and
PictureBox controls and custom controls that have
an Align property. To place other controls on an
MDIForm, you can draw a picture box on the form,
and then draw other controls inside the picture box.
You can use the Print method to display text in a
picture box on an MDIForm, but you can't use this
method to display text on the MDIForm itself. An
MDIForm object can't be modal.

 MDI child forms are designed independently of the


MDIForm, but are always contained within the
MDIForm at run time. You can access the collection
of controls on an MDIForm using the Controls
collection.
Properties
  Properties Description
 
ActiveControl Returns the control that has the focus. When a form is referenced, as in
ChildForm.ActiveControl, ActiveControl specifies the control that
would have the focus if the referenced form were active .

ActiveForm Returns the form that is the active window. If an MDIForm object is
active or is referenced, it specifies the active MDI child form.

BackColor Sets the background color of an object.


 

ForeColor Sets the foreground color used to display text and


graphics in an object.
Caption Determines the text displayed in the MDIForm object's
title bar.
Count Returns the number of objects in a collection.

Enabled Returns or sets a value that determines whether a form


or control can respond to user-generated events.
Method

Method Description
 

Hide Hides an MDIForm or Form object but doesn't


unload it.
Move Moves an MDIForm

Setfocus Moves the focus to the specified control or form.

Displays an MDIForm or Form object The syntax is object.Show style,


Show ownerform.where style Optional. Integer that determines if the form is
modal or modeless. If style is 0, the form is modeless; if style is 1, the
form is modal. Ownerform Optional. A string expression that
specifies the component which "owns" the form being shown. For
standard Visual Basic forms, use the keyword Me.
Events
Events Description
 

Active Occurs when an object becomes the active window.

Deactivate occurs when an object is no longer the active window.

Click Occurs when the user presses and then releases a mouse
button over an object. It can also occur when the value
of a control is changed.
Initialise Occurs when an application creates an instance of
MDIForm.
Load Occurs when a form is loaded. For a startup form,
occurs when an application starts as the result of a Load
statement or as the result of a reference to an unloaded
form's properties or controls.
Unload Occurs when a form is about to be removed from the
screen. When that form is reloaded, the contents of all
its controls are reinitialized. This event is triggered by a
user closing the form using the Close command on the
Control menu or an Unload statement.
Creating an MDI application
To create an MDI application:

•Start a Windows project by selecting the File | New


menu option and choosing Standard EXE from the
types of project available.

•Then goto Project menu and choose Add MDI form


option.

•Change the Text property of the form to Parent Form


and the name property to frmParent.
• Now goto Project menu and choose Add Form to
create a child form.

• Set the child form’s MdiChild property to True.

• Name this form frmChild.

• The next stage is to add the menu system.


Creating the Menu in an MDI Form
Add a MainMenu control.

Note that the line


between the New
child and Close was
inserted by adding a
single dash as one of
the menu items, this is
converted to an
unbroken line.
Creating a Notepad Application
The Notepad (using Richtextbox
control)
Code of MDIForm1
(General Declarations )
Dim formno As Integer
 
Private Sub MDIForm_Load()
txtchanged = False
MDIForm1.Caption = "My Notepad"
End Sub
 
Private Sub mnueditcopy_Click()
Clipboard.SetText MDIForm1.ActiveForm.rtf.SelText
End Sub
 
Private Sub mnueditcut_Click()
Clipboard.SetText MDIForm1.ActiveForm.rtf.SelText
MDIForm1.ActiveForm.rtf.SelText = ""
End Sub

Private Sub mnueditdelete_Click()


MDIForm1.ActiveForm.rtf.SelText = ""
End Sub
 
Private Sub mnueditpaste_Click()
MDIForm1.ActiveForm.rtf.SelText =
Clipboard.GetText()
End Sub
Private Sub mnueditselectall_Click()
MDIForm1.ActiveForm.rtf.SelStart = 0
MDIForm1.ActiveForm.rtf.SelLength =
Len(MDIForm1.ActiveForm.rtf)
End Sub

Private Sub mnuedittimedate_Click()


MDIForm1.ActiveForm.rtf.SelText = Date & " " & Time
End Sub
 
Private Sub mnufileclose_Click()
Unload MDIForm1.ActiveForm
End Sub
 
Private Sub mnufileexit_Click()
Unload Me
End Sub
Private Sub mnufileopen_Click()
cmd1.ShowOpen
Dim newform As New Form1
formno = formno + 1
newform.Caption = cmd1.filename
newform.Show
MDIForm1.ActiveForm.rtf.LoadFile cmd1.filename
End Sub
 
Private Sub mnufilesaveascii_Click()
Call mysave("rtftext")
End Sub
 
 
Private Sub mnufilesavertf_Click()
Call mysave("rtfrtf")
End Sub
Private Sub mnuformatfonts_Click()
If MDIForm1.ActiveForm.ActiveControl.SelLength <= 0 Then
MsgBox ("U must select some text ")
Exit Sub
End If
cmd1.Flags = cdlCFScreenFonts
cmd1.ShowFont
With MDIForm1.ActiveForm.ActiveControl
.SelFontName = cmd1.FontName
.SelBold = cmd1.FontBold
.SelItalic = cmd1.FontItalic
.SelFontSize = cmd1.FontSize
End With
End Sub
Code of Module 1 ( My Notepad )
 
Public Sub mysave(Saveas As String)
MDIForm1.cmd1.ShowSave
If Saveas = "rtfrtf" Then
MDIForm1.ActiveForm.rtf.SaveFile
MDIForm1.cmd1.filename, rtfRTF
Else
MDIForm1.ActiveForm.rtf.SaveFile
MDIForm1.cmd1.filename, rtfText
End If
MDIForm1.ActiveForm.Caption =
MDIForm1.cmd1.filename
End Sub
Menu event procedures
The File | New child menu item:

Private Sub MnuNewChild_Click()


Dim newChildForm As New frmChild( )
formno = formno + 1
newChildForm.Caption = "Untitled " &
Trim(Str(formno))
newChildForm.Show( )
End Sub

Creates a new instance of the child form frmChild.


The parent is the current MDI parent form.
The child form is displayed by the Show method.
The File | Close menu option:
unload me
which closes the application.
Creating the Menu contd…
The Arrange heading has 3 items:

•Cascade
•Tile horizontal
•Tile vertical.

A Window heading has no items: but will


display a list of all child windows.

All menu item names should have the prefix


mnu followed by the text of the menu item, for
example mnuClose.
Menu event procedures (Cont…)
The Arrange | Cascade menu item:
Mdiform1.Arrange vbcascade

The Arrange | Tile horizontal menu option:


Mdiform1.Arrange vbtilehorizontal

The Arrange |Tile vertical menu option:


Mdiform1.Arrange vbtilevertical

The Arrange |Arrange Icons menu option:


Mdiform1.Arrange vbarrangeicons
The Windows menu option: just check the WindowList
property in menu editor. When this item is selected a
list of the current child windows is displayed.
Running the Application
Summary

 MDI stands for Multiple Document Interface.

 An MDI form is a frame inside which other windows


are displayed.

 The advantage of having an MDI application is that the


user can work on more than one document within the
same application.

 An application can contain only one MDI form.


Summary cont…

 The MDI form acts as a container for all other windows


and is called the Parent form.

 The windows in which the individual documents are


displayed are called the Child windows.

 All SDI(single document interface) forms can be


converted to child forms of MDI form.
Exercises
1. Do the above but using menus, common
dialogboxes, drivebox, filelist box Richtextbox.
Basically make a notepad. Include font also menus on
the MDI will be:
File
Open ^O
New ^N
Edit Search
Close Undo Find
Cut Replace
Save ^S Copy Find Next
Save As Paste
Delete
Exit ALT +Q Select All
Exercises cont…
Format
Font
When dealing with font only selected
Color text should be changed.
Date & Time
Windows

Windows
Arrange
Vertical
Horizontal
Visual Basic

LECTURE-14
Topics to be covered

 Working with Graphics,controls and methods


Working with Graphics
Advantages :

 The graphics methods work well in situations where


using graphical controls require too much work. For
example, creating gridlines on a graph would need an
array of line controls but only a small amount of code
using the Line method.
 Tracking the position of line controls in an array as the
form changes size is more work than simply redrawing
lines with the Line method.
 When you want a visual effect to appear briefly on a
form, such as a streak of color when you display an
About dialog, you can write a couple of lines of code for
this temporary effect instead of using another control.
 Graphics methods offer some visual effects that are not
available in the graphical controls. For example, you
can only create arcs or paint individual pixels using the
graphics methods.

 Graphics you create with these graphics methods appear


on the form in a layer of their own.

 This layer is below all other controls on a form, so using


the graphics methods can work well when you want to
create graphics that appear behind everything else in
your application.
Limitations of Graphics Methods
 Creating graphics with the graphics methods takes place
in code, which means you have to run the application to
see the effect of a graphics method.

 Graphics methods therefore don't work as well as


graphical controls for creating simple design elements
of an interface.

 Changing the appearance of graphical controls at design


time is easier than modifying and testing the code for a
graphics method.
Supported Graphic Formats
 The picture box control can display picture files in any of the
following formats: bitmap, icon, metafile, enhanced metafile, or
as JPEG or GIF files.

Graphics Methods
 Picture boxes, like forms, can be used to receive the output of
graphics methods such as Circle, Line, and Point.
 For example, you can use the Circle method to draw a circle in a
picture box by setting the control's AutoRedraw property to
True.
Picture1.AutoRedraw = True
Picture1.Circle (1200, 1000), 750

 Setting AutoRedraw to True allows the output


from these methods to be drawn to the control
and automatically redrawn when the picture box
control is resized or redisplayed after being
hidden by another object.
Using the Print Method

 You can use the picture box control to output text by


using the Print method and setting the AutoRedraw
property to True. For example:
Picture1.Print "A text string"

 When using the Print method you can also modify the
font style and size or use the CurrentX, CurrentY,
Height, and Width properties to align text within a
picture box.
 The primary use for the picture box control is to display
a picture to the user. The actual picture that is displayed
is determined by the Picture property. The Picture
property contains the file name (and optional path) for
the picture file that you wish to display.
 Form objects also have a Picture property that can be set
to display a picture directly on the form's background.

 To display or replace a picture at run time, you can use


the LoadPicture function to set the Picture property. You
supply the name (and optional path) for the picture and
the LoadPicture function handles the details of loading
and displaying it:
picMain.Picture = LoadPicture("VANGOGH.BMP")
Printing At Arbitrary Locations
 You can paint graphics at arbitrary locations on a form, on
a picture box, and to the Printer object using the
PaintPicture method. The syntax for the PaintPicture
method is:

[object.]PaintPicture pic, destX, destY[, destWidth[,


destHeight[, srcX [, srcY[, srcWidth[, srcHeight[, Op]]]]]]]
 The destination object is the form, picture box, or Printer
object where the pic picture is rendered. If object is
omitted, the current form is assumed. The pic argument
must be a Picture object, as from the Picture property of a
form or control.
 The destX and destY arguments are the horizontal and
vertical locations where the picture will be rendered in
the ScaleMode of object. The destWidth and destHeight
arguments are optional and set the width and height with
which the picture will be rendered in the destination
object.

 The srcX and srcY arguments are optional and define the
x-coordinate and y-coordinate of the upper-left corner of
a clipping region within pic.

 The optional Op argument defines a raster operation


(such as AND or XOR) that is performed on the picture
as it is being painted on the destination object.
 The PaintPicture method can be used in place of the
BitBlt Windows API function to perform a wide variety
of bit operations while moving a rectangular block of
graphics from one position to any other position.

 For example, you can use the PaintPicture method to


create multiple copies of the same bitmap, and tile them
on a form. Using this method is faster than moving
picture controls on a form. The following code tiles 100
copies of a picture control and flips every picture
horizontally by supplying a negative value for
destWidth.
For i = 0 To 10
For j = 0 To 10

Form1.paintpicture=
picF.picture,j*picF.width,I*picF.height,picF.width,-
picF.height

Next j, i
Scale Properties
 
 Defines the coordinate system for a Form, PictureBox.
Doesn't support named arguments.
Syntax
object.Scale (x1, y1) - (x2, y2)
 
 The Scale method syntax has these parts:

 
 object(Optional) : An object expression that evaluates to an

object in the Applies To list. If object is omitted, the Form


object with the focus is assumed to be object.
 
 
 x1, y1(Optional) : Single-precision values indicating the horizontal
(x-axis) and vertical (y-axis) coordinates that define the upper-left
corner of object. Parentheses must enclose the values. If omitted,
the second set of coordinates must also be omitted.

 x2, y2(Optional.) : Single-precision values indicating the


horizontal and vertical coordinates that define the lower-right
corner of object. Parentheses must enclose the values. If
omitted, the first set of coordinates must also be omitted.
 
 The Scale method enables you to reset the coordinate
system to any scale you choose. Scale affects the coordinate
system for both run-time graphics statements and the
placement of controls.
 
 If you use Scale with no arguments (both sets of
coordinates omitted), it resets the coordinate
system to twips.
 
Applies To

 Form Object, Forms Collection, PictureBox Control,


PropertyPage Object, UserControl Object
Circle
 The Circle method draws a variety of circular and
elliptical (oval) shapes. In addition, Circle draws arcs
(segments of circles) and pie-shaped wedges. You can
produce many kinds of curved lines using variations of
the Circle method.
 To draw a circle, Visual Basic needs the location of a
circle’s center and the length of its radius. The syntax for
a perfect circle is:
[object.]Circle [Step](x, y), radius[, color]
 The brackets indicate that both object and the Step
keyword are optional. If you don’t specify object, the
current form is assumed. The x and y arguments are the
coordinates of the center, and radius is the radius of the
circle. For example, this statement draws a circle with a
center at (1200, 1000) and radius of 750:

Circle (1200, 1000), 750


 The exact effect of this statement depends on the size
and coordinate system of the form. Because the size of
the form is unknown, you don’t know if the circle will be
visible. Using the drawing area’s scale properties puts
the center of the circle at the center of the form:

Circle ((ScaleWidth+ ScaleLeft) / 2, (ScaleHeight +


ScaleTop) / 2), ScaleWidth / 4

 ScaleWidth and ScaleHeight help position graphics in


the center of a form.
 The radius of the circle is always specified in terms of
horizontal units. If your coordinate system uses the
same horizontal and vertical units (which it does by
default), you can ignore this fact. However, if you use
a custom scale, horizontal and vertical units may
correspond to different distances. In the preceding
examples, the radius is specified in horizontal units,
and the actual height of the circle is guaranteed to be
equal to its actual width.
The Blanker application creates circles as part of the
Rainbow Rug demo. This demo draws a series of dashed
line circles around the center of the form. In time the
circles resemble a woven circular rug. The CircleDemo
procedure creates the circles in the Rainbow Rug demo
with the following statements:
Sub CircleDemo ()
Dim Radius
R = 255 * Rnd ' Set Red to a random value.
G = 255 * Rnd ' Set Green to a random value.
B = 255 * Rnd ' Set Blue to a random value.
XPos = ScaleWidth / 2 ' Set x-coordinate in middle of
form.
YPos = ScaleHeight / 2 ' Set y-coordinate in middle of
form.
Radius = ((YPos * 0.9) + 1) * Rnd ' Set radius between
0 & 50% of form height.
Circle (XPos, YPos), Radius, RGB(R, G, B) ' Draw the
circle using a random color.
End Sub
Drawing Arcs
  To draw arcs with the Circle method, you need to give angle
arguments in radians to define the start and the end of the
arc.
The syntax for drawing an arc is:
[object.]Circle [Step](x, y), radius, [color], start, end[, aspect]
If the start or end argument is negative, Visual Basic draws
a line connecting the center of the circle to the negative end
point. For example, the following procedure draws a pie
with a slice removed.
Private Sub Form_Click ()
Const PI = 3.14159265
Circle (3500, 1500), 1000, , –PI / 2, –PI / 3
End Sub
Line
Draws lines and rectangles on an object.
Syntax
object.Line [Step] (x1, 1) [Step] (x2, y2), [color], [B]
[F]
The Line method syntax has the following object qualifier
and parts:
object(Optional.) Object expression that evaluates to an
object in the Applies To list. If object is omitted, the
Form with the focus is assumed to be object.
Step(Optional.) Keyword specifying that the starting point
coordinates are relative to the current graphics position
given by the CurrentX and CurrentY properties.
(x1, y1) (Optional.) Single values indicating the
coordinates of the starting point for the line or rectangle.
The ScaleMode property determines the unit of measure
used. If omitted, the line begins at the position indicated
by CurrentX and CurrentY.

 Step(Optional.) Keyword specifying that the end point


coordinates are relative to the line starting point.
 (x2, y2) (Required) Single values indicating the
coordinates of the end point for the line being drawn.
 color(Optional.) Long integer value indicating the RGB
color used to draw the line. If omitted, the ForeColor
property setting is used. You can use the RGB function
or QBColor function to specify the color.
 B (Optional) If included, causes a box to be drawn
using the coordinates to specify opposite corners of the
box.
 F (Optional) If the B option is used, the F option
specifies that the box is filled with the same color used
to draw the box. You cannot use F without B. If B is
used without F, the box is filled with the current
FillColor and FillStyle. The default value for FillStyle
is transparent.
 To draw connected lines, begin a subsequent line at the
end point of the previous line.
 The width of the line drawn depends on the setting of
the DrawWidth property. The way a line or box is
drawn on the background depends on the setting of the
DrawMode and DrawStyle properties.
 When Line executes, the CurrentX and CurrentY
properties are set to the end point specified by the
arguments.
 This method cannot be used in an With…End With
block.
Curves
 This is where the math starts. The Scale method makes
graphing any mathematical function trivial.
 The only problems come in deciding the maximum and
minimum values to use for the scale statement, which often
takes calculus.
 However, as before, Visual Basic will clip any figure that is
off the axis, so no problems result from setting the wrong
scale, unless you are way out of line.
 In this case, you'll have to trap the overflow error that may
result. You could have the error trap call a Resize procedure
that would rescale the drawing area to allow the new
information to be used.
 This might require recalculating all the points already drawn,
however.
For example, here's a fragment that draws a cosine
graph
Dim I As Single, TwoPie As Single
TwoPie = 8*Atn (1)
Scale (-TwoPie, 1) - (TwoPie, -1)
For I = -TwoPie To TwoPie Step .01
PSet (I, Cos ( I ) )
Next I
Pictures Without Too Many Formulas
 Imagine that four animals start at the corners of a square. The
first animal chases the second, the second chases the third, the
third the fourth, and the fourth chases the first. The screen in
next slide shows you what you get after only four moves.
Obviously, what is happening is that each square is both
rotating and shrinking. Before you can work through the
program, you'll need one more formula: the distance formula
for points in the plane. This says that the distance between two
points, X1, Y1 and X2, Y2, in the plane is
Sqr((X2-X1)^2 + (Y2 -Y1)^2)
 where Sqr is the square root function. In Visual
Basic, you can make a function out of it:

Function Dist (X1, Y1, X2, Y2) As Single


Dim A As Single, B As Single
A = (X2 - X1) * (X2 - X1)
B = (Y2 -Y1 ) * (Y2 -Y1 )
Dist = Sqr (A + B)
End Function
 The purpose of the distance function to tell the program
when to stop - to know when the animals are "close
enough." Next, you need a Movelt procedure for the
case:

Sub Movelt (A, B, T)


A = (1 - T) * A + T * B
End Sub
Here's the form_Click ( ) procedure that does all the work:

Private Sub Form_Click ( )


Dim T As Single, X1 As Single, Y1 As Single
Dim X2 As Single, Y2 As Single, X3 As Single
Dim Y3 As Single, X4 As Single, Y4 As Single
Scale (-320, 200) - (320, -200)
T = .05 'Percentage moved if 5%
X1 = -320 : Y1 = 200
X2 = 320 : Y2 = 200
X3 = 320 : Y3 = -200
X4 = -320 : Y4 = -200
Do Until Dist (X1, Y1, X2, Y2) < 10
Line (X1, Y1) - (X2 , Y2)
Line - (X3, Y3)
Line - (X4, Y4)
Line - (X1, Y1)
MoveIt X1, X2, T
MoveIt Y1, Y2, T
MoveIt X2, X3, T
MoveIt Y2, Y3, T
MoveIt X3, X4, T
MoveIt Y3, Y4, T
MoveIt X4, X1, T
MoveIt Y4, Y1, T
Loop
End Sub
 The Do loop ends when the points get close enough - less
than ten units from each other. notice that you can't use the
Box command because the square is rotated.

 The block of repeated calls to the Movelt function finds the


new coordinates for each of the four points. By adding more
parameters, you could have made the Movelt subprogram
make the changes one point at a time instead of one
coordinate at a time.

 If you imagine the animals are moving independently along


curves, then the kinds of pictures produced can be even
more dramatic.
Summary
 Graphics can be placed on 3 controls viz. Form, Picturebox
and Imagebox.

 Scale method is used to setup a user-defined co-ordinate


system to describe the position of the individual pixels on the
screen.

 The various Graphics/drawing methods of VB are:


 Print - Displays a string

 Line – Draws lines and boxes

 Circle – Draws circles and arcs

 Point – Retrieves the color value of a point

 Pset – Sets the color of a point


Exercises:

1. Write the code to print different color lines on the


form when mouse is moved over it.

2. Create a form and write the code to produce a timer


based dancing line on the form.
Visual Basic

LECTURE-15
Topics to be covered

 Introduction to Database Programming in VB

 Creating database in MS-Access


Databases and DBMS

•A database is a collection of data.

•A DBMS is a database management system. It is


the software that allows you to manipulate that
data.

•Similarly this is a PowerPoint Presentation,


which is manipulated by MS PowerPoint.
What ifs….
DBMS allow us to extract parts of the data we
want and ask interesting questions.

For example in a medical database.

•Are there more cancers around Sellafield than in


other areas?

•Is there a link between obesity and diabetes?

•Are heavy smokers more likely to get heart


disease?
Relational DBMS
Several models for data management :
hierarchical, network and relational are
three.

The relational model is most widely used -


proposed and developed by Dr Edgar (Ted)
Codd and Chris Date.

Article by Codd in Computerworld , 14-21


October 1985. - the seven rules.
Database fundamentals
Four key components to a database:

•Tables

•Forms

•Queries

•Reports
Tables
A container for data, for example:
StudentId FamilyNa FirstNam DoB Cours
me e e
P9076768 Benelli Severeno 14 Mar G500
1984
P7892028 Read Lynne 2 Nov 1983 G510
All data in a RDBMS is in a table.

A row contains data on one student.

A column contains one item of data for every


student.
Forms
A form is a device for viewing and editing data in a
table.
Forms can be used to customise the way in which
records from tables and queries are presented on
screen.
They help provide a user-friendly interface for adding
new records or editing existing ones.

For example:
Queries
Queries are used to select records from a database.
e.g. In Access there are 3 types.
Select Queries. They are questions that you may
wish to ask about entries in fields. They choose
records from a table and store them in a new table.

Action Queries. These update values in a database


table. Can be used to change entire groups of
records. E.g. delete all records of a former
employee.
Parameter Queries. These allow the criteria for a
query to be changed each time it is used. They create
a more usable environment for the end user
Reports
Reports produce output from a table ready for the
printer
Tables - a closer look
StudentId FamilyName FirstName DoB Course
P9076768 Benelli Severeno 14 Mar 1984 G500
P7892028 Read Lynne 2 Nov 1983 G510

Column and field are often used interchangeably.


Strictly though the field is the data and the column is a
structure in the table.

Every field has a field name - shown at the top of the


columns. This must be unique within a table.
Every table must also have a meaningful name, in this
case Student.
Avoid spaces in names.
Tables - a closer look (2)
Data is stored in tables that are organised by rows and
columns.
A database must have at least one table.

Columns represent fields of information, or one


particular piece of information that can be stored for
each entity in the table.

Rows contain records. A record contains one of each


field in the database table.
Generally a table represents each major set of
information in a database.
Introduction

•What data types can be stored in a


table?

•Why do we need data types?

•What is redundant data?

•Creating a database and table in


Access.
Building a table
When you have decided what data to include in
our table you need to decide on what type each
field is:
Text : most characters on the keyboard including
numbers, usually limited to 255 characters.
Memo :large blocks of text.
Number : numbers only.
Date/Time : date, time or both.
Currency : numeric with a decimal point and a
currency symbol.
AutoNumber : A number which increments for
each record.
Yes/No : boolean information
OLE Object : e.g. an Excel spreadsheet.
Why do we need data types - 1?
Four advantages:
1. Allow more meaningful operations.
If you want to save a date, a text fields works, but you
can also store any other data e.g. 16/9/2002, 16-
September-2002, myBirthday, aarghhh.
You can also perform arithmetic operations on dates -
subtracting one from another gives the time in-
between.
What data type should be used for telephone n
numbers?
If you used numeric leading zeros would be removed,
blank spaces and brackets would not be acceptable.
Telephone numbers are text which just happen to be all
Why do we need data types - 2?
2. Exclude certain types of data.

If the data/type is used, dates such as:


31 Sep 2003 are not allowed.

Watch out for European/US data format.


9/11/2003 is the 11th September in the US and
9th November in Europe.

Non-numeric data is not allowed in numeric


fields.
Why do we need data types - 3?
3. More efficient storage of data.

You can save space by using the right data type


- and therefore speed up access.

There are many numeric types:


Byte : 0255. 1 byte.
Integer :-3276832767. 2 bytes
Long Integer : -2,147,438,6482,147,438,647.
4 bytes
Single : -3.4  1038  3.4  1038. 4 bytes
Double : -1.8  10308  1.8  10308. 8 bytes.
Why do we need data types - 4?
4. Data recovery more rapid.

If you choose to make a text field 100 characters


long every record has 100 bytes allocated. This
is too many for a family name.

Storing the number of children a person has an


integer is a waste of space.

As database become larger they become slower.


Choosing field names
Separate: title, first name and surname.
Don't use Christian name - first name is better.
Not everyone has a first name and surname, so last
name may be better than surname.

Some people are touchy about the right title being


available - Mr, Miss, Mrs, Ms, Dr, Prof. is a common
list.

Separate address into fields, typically: Address line 1,


line 2, line 3, town, post/zip code. Why?

Don't think:"what do I want to put into the database“


think: "what do I want to get out"
Redundant information
Don't store the same data twice, for example:

If you store the number of items sold and the cost of


each item, don't store the total cost of sales.

Don't store a person's age and their DoB.

Which is the better one to use?


Creating a Database and Table in Access
Select File | New blank database.

Specify where the database is to be stored

Next to create the table: Create table by entering


data.

Close the table and call the table Student.

Right Click on the table select Design view to


check the data types.
Select Data sheet view
Specify the data types
Field properties - 1
Every field has a set of properties:
Field size : For text fields the default is 50
characters. Choose the minimum required.

Format : You can use special symbols to format


Memo and Text fields using these symbols:
@ - a text character is required.
& - a text character is optional.
< - make all characters lower case
>- make all characters upper case.
For example: > would convert "abcd" to "ABCD"
and @@@ would allow any three characters to
be entered.
Field properties - 2
Input mask : define how data is stored and how much data
is entered, for example
0 - used for 09 (entry required, + and - signs not
allowed.)
9 - used for 09 or space(entry optional, + and - signs not
allowed)
# - used for 09, or space (entry optional, + and - signs
allowed.)
L - letters AZ (entry required)
? - letters AZ (entry optional)
A - letter or digit (required)
a - letter of digit (optional)
& - any character (required)
C - any character (optional)
Field properties - 3
Caption - provide a meaningful description of the field.
Default value - the value entered if none specified.
Validation rule - a check made on the entered data,
for example ">=10 And <=100" only allows values
between 10 and 100 to be entered.
Operators include:
<>0 - enter a non-zero value
>100 - enter a value greater than 100.
Like "AB???" - enter a value 5 characters long which
begins with AB.
<#1/1/03# - enter a date before 1/1/03
>=#1/1/03# And <#1/1/04# - a date in 2003.
In ("Mr", "Mrs", "Miss", "Ms", "Dr") - must be one of the
list.
Field properties - 4
Validation text : The text which is displayed when the
validation fails - rather than the standard Access
message.

For example, if the validation rule was:


In ("Mr", "Mrs", "Miss", "Ms", "Dr")
A message "Must choose Mr, Mrs, Miss, Ms or Dr"
would be a helpful message.

Required : If set to yes, the value must be entered.


Allow zero length : the zero length string "" is allowed.
Indexed : an index is used to speed up access - covered
later.
Forms
In a RDBMS all data is in tables.
A form is a view which allows you to carry out
all operations on data.
Typically it shows one record at a time.
Forms

Since it is just a view you can have as many forms as


you wish:

You can show only the fields you want.


Queries
• Operations which extract data are called queries.
• The result of a query is an answer table.
• This is a key feature of RDBMS called closure.
• The data tables of the database are called base
tables.
• As the data in the base tables changes the answer
table remains unchanged. If you run the query
again, a new answer table will be produced.

• If you change the data in an answer table the


underlying data in the base table is changed - but
this is fraught with problems:
• "incompatible with preserving the integrity of the
data"
Sorts of queries
View queries.

Update queries : change the data in a table, for


example to increase prices by 5% (but only if
the product costs more than $35.00)

Append queries : Find data in one table and add


that to another table, for example to find all
the sale people who sell more than $100,000
and to add their names to another table.

Delete queries : Find the names of sales people


who have sold less than $50,000 and delete
them from another table.
Using SQL

Structured Query Language pronounced


as Sequel or S-Q-L a data access
language or data sub-language.

Used for creating and deleting tables,


updating and editing as well as simple
queries.

Queries are the most commonly used


aspect - this comprises the Data
Manipulation Language (DML)
statements.
The SALES table
SALES
SalesNo EmployeeNo Customer Item Supplier Amount
1 1 Simpso Sofa Harriso 235.67
n n
2 1 Johnson Chair Harriso 453.78
n
3 2 Smith Stool Ford 82.78
4 2 Jones Suite Harriso 3421.0
n 0
5 3 Smith Sofa Harriso 235.67
n
6 1 Simpso Sofa Harriso 235.67
n n
SELECT and FROM
The SELECT statement extracts a collection of fields
from a table:
SELECT Item, Amount
FROM SALES;
produces:
Item Amount
Sofa 235.67
Chair 453.78
Stool 82.78
Suite 3421.00
Sofa 235.67
Sofa 235.67
Bed 453.00
DISTINCT
To remove duplicates you can use DISTINCT:

SELECT DISTINCT Item, Amount


FROM SALES;
produces
Item Amount
Sofa 235.67
Chair 453.78
Stool 82.78
Suite 3421.00
Bed 453.00
WHERE
WHERE allows you to apply a condition:

SELECT Item, Amount


FROM SALES
WHERE Item="Sofa";

Item Amount
Sofa 235.67
Sofa 235.67
Sofa 235.67
Multiple Where conditions
SELECT Item, Amount
FROM SALES
WHERE Item="Sofa" AND
Customer="Smith";
Item Amount
Sofa 235.67

The basic format of a SELECT statement is:

SELECT field names


FROM table name
WHERE conditions
Operators
There are other operators in WHERE clauses in
addition to the = operator
Symbol Meaning
< Less than
> Greater than
<> Not equal to
>= Greater than or equal to
<= Less than or equal to
IN Equal to a value in a collection
LIKE Similar to
BETWEEN…AND Within a range of specified
values
IS NULL Field does not contain a value
Logical operators

Symbol Meaning
AND Both conditions must be true.
OR Either or both expressions must be
true.
NOT Inverts the condition
AND clause
SELECT Item, Amount
FROM SALES
WHERE Item="Sofa" AND SalesNo > 5

Item Amount
Sofa 235.67
IN
SELECT Item, Amount
FROM SALES
WHERE Item IN ("Sofa", "Suite", "Bed");

Item Amount
Sofa 235.67
Suite 3421.00
Sofa 235.67
Sofa 235.67
Bed 453.00
IN and AND
SELECT Item, Amount
FROM SALES
WHERE item IN ("Sofa", "Suite", "Bed")
AND SalesNo > 6;
Item Amount
Bed 453.00
IN and OR
SELECT Item, Amount
FROM SALES
WHERE Item In ("Sofa", "Suite", "Bed")
OR SalesNo > 6;
Item Amount
Sofa 235.67
Suite 3421.00
Sofa 235.67
Sofa 235.67
Bed 453.00
ORDER BY
This clause lists in numeric or alphabetical
order.
SELECT Item, Amount, SalesNo
FROM SALES
WHERE Item = "Sofa"
ORDER BY SalesNo;
Item Amount SalesNo
Sofa 235.67 1
Sofa 235.67 5
Sofa 235.67 6

The columns are in the specified order in


increasing SalesNo order.
ASC and DESC
SELECT Item, Amount
FROM Sales Item Amount
WHERE SalesNo > 2 Bed 453.00
ORDER BY Item ASC Sofa 235.67
Sofa 235.67
Stool 82.78
Suite 3421.00

The items are listed in ascending


alphabetical order.

To reverse the order use DESC.


Advanced Queries
Consider the database:
SALES CARS
SalesN EmployeeN Customer Item Supplier Amount CarNo Make Model
o o
1 Triumph Spitfire
1 1 Simpson Sofa Harrison 235.67
2 Bentley Mk. IV
2 1 Johnson Chair Harrison 453.78
3 Triumph Stag
3 2 Smith Stool Ford 82.78
4 Ford GT 40
4 2 Jones Suite Harrison 3421.0
5 Shelby Cobra
0
6 Ford Mustang
5 3 Smith Sofa Harrison 235.67
7 Aston DB Mk III
6 1 Simpson Sofa Harrison 235.67
Martin
7 1 Jones Bed Ford 453.00
8 Jaguar D Type
EMPLOYEES
EmployeeN FirstNam LastNam DateOfBirth DateEmployed CarNo
o e e
1 Bilda Groves 12 Apr 1956 01 May 1989 2
2 John Greeves 21 Mar 01 Jan 1990
1967
3 Sally Smith 01 May 01 Apr 1992 5
1967
4 Fred Jones 03 Apr 1986 01 May 1994 3
Wild cards
SELECT *
FROM SALES
WHERE SaleNo > 1

SELECT SaleNo, EmployeeNo, Customer, Item, Supplier,


Amount
FROM SALES
WHERE SaleNo > 1
Sub Queries
SELECT Customer In Access SQL the date
FROM SALES must have a preceding and
following # i.e.
WHERE EmployeeNo IN
#5/5/1989#
(SELECT EmployeeNo
FROM EMPLOYEES EmployeeNo
WHERE dateEmployed >
2
5/5/1989); 3
The sub query is worked out first to 4
give:
Customer
SELECT Customer Smith
FROM SALES Jones
WHERE EmployeeNo IN(2, 3, 4); Smith
which gives:
Built-in functions - 1
SUM - totals
COUNT - the number of occurrences
AVG - average
MIN - minimum
MAX – maximum
SELECT SUM(Amount) FROM SALES; Expr1000
Access generates a dummy field name: 5,117.57
You can name the output field:
SELECT SUM(Amount) AS "Sum of Amount"
FROM SALES;
SELECT SUM(Amount) AS SumOfAmount
FROM SALES;
SELECT SUM(Sales.Amount) AS SumOfAmount
FROM SALES;
Built-in Functions - 2
SELECT SUM(Amount) AS SumOfAmount,
COUNT(Amount) AS CountOfAmount,
AVG(Amount) AS AvgOfAmount,
MIN(Amount) AS MinOfAmount,
MAX(Amount) AS MaxOfAmount
FROM SALES;

SumOfAmoun CountOfAmoun AvgOfAmount MinOfAmount MaxOfAmoun


t t t
5,117.57 7 731.08 82.78 3421.00
Built-in functions - 3

What's wrong with this?


SELECT Customer,
AVG(SALES.Amount) As AvgOfAmount
FROM SALES;

SELECT Customer has an output of multiple


records while AVG(SALES.Amount) has a
single record as output.
Group By
SELECT AVG(Amount) AS AvgOfAmount AvgOfAmount
FROM SALES; 731.08
Gives the average of all the Amount fields.

SELECT AVG(Amount) AS AvgOfAmount AvgOfAmount


FROM SALES 235.67
WHERE Customer = "Simpson“;
How can we do this for every customer?
Customer AvgOfAmount
SELECT Customer,
AVG(Amount) As AvgOfAmount Johnson 435.78

FROM SALES Jones 1937.00

GROUP BY Customer Simpson 235.67

ORDER BY Customer; Smith 159.23

GROUP BY splits the records into groups and then


produces a summary record for every group.
Multiple tables - 1
SELECT SALES.Customer, SELECT S.Customer, E.LastName,
EMPLOYEES.LastName, S.EmployeeNo, E.EmployeeNo
SALES.EmployeeNo, FROM SALES S, EMPLOYEES E;
EMPLOYEES.EmployeeNo (SALES AS S, EMPLOYEES AS E
FROM SALES, EMPLOYEES; is also acceptable)
Custome LastNam SALES.EmployeeNo EMPLOYEES.EmployeeNo
r e
Simpso Groves 1 1
n
Johnson Groves 1 1
Smith Groves 2 1
Jones Groves 3 1
Smith Groves 3 1
Simpso Groves 1 1
n
Jones Groves 1 1
Multiple tables - 2
SELECT S.Customer, S.Amount,
E.FirstName, E.LastName,
S.EmployeeNo,E.EmployeeNo
FROM SALES S, EMPLOYEES E
WHERE S.EmployeeNo = E.EmployeeNo

Customer Amount FirstName LastName S.EmployeeNo E.EmployeeNo


Simpson 235.67 Bilda Groves 1 1
Johnson 453.78 Bilda Groves 1 1
Smith 82.78 John Greeves 2 2
Jones 3421.00 John Greeves 2 2
Smith 235.67 Sally Smith 3 3
Simpson 235.67 Bilda Groves 1 1
Jones 453.00 Bilda Groves 1 1
Multiple tables - 3
SELECT SALES.Customer, EMPLOYEES.FirstName,
CARS.Make, CARS.Model
FROM CARS, EMPLOYEES, SALES
WHERE EMPLOYEES.EmployeeNo = SALES.EmployeeNo
AND EMPLOYEES.CarNo = CARS.CarNo
Customer FirstNam Make Model
e
Simpson Bilda Bentley Mk IV
Johnson Bilda Bentley Mk IV
Simpson Bilda Bentley Mk IV
Jones Bilda Bentley Mk IV
Smith Sally Shelby Cobra

(This gives the car driven by the salesperson who dealt with
a given customer)
A recent SQL change
SELECT SALES.Customer,
EMPLOYEES.LastName,
SALES.Amount
FROM SALES, EMPLOYEES
WHERE SALES.EmployeeNo = EMPLOYEES.EmployeeNo;

can be replaced by

SELECT SALES.Customer,
EMPLOYEES.LastName,
SALES.Amount
FROM SALES INNER JOIN EMPLOYEES
ON SALES.EmployeeNo = EMPLOYEES.EmployeeNo;

This gives the same answer.


Inner joins
"Give me a list of all the cars and the salesperson to whom
each is allocated“

SELECT CARS.Make,
CARS.Model,
EMPLOYEES.FirstName
EMPLOYEES.LastName
FROM CARS INNER JOIN EMPLOYEES
ON CARS.CarNo = EMPLOYEES.CarNo

Make Model FirstName LastName


Bentley Mk. IV Bilda Groves
Triumph Stag Fred Jones
Shelby Cobra Sally Smith

This only shows cars which have been allocated - some have not.
Outer joins - 1
Substitute LEFT JOIN for INNER JOIN
SELECT CARS.Make, CARS.Model,
EMPLOYEES.FirstName, EMPLOYEES.LastName
FROM CARS LEFT JOIN EMPLOYEES
ON CARS.CarNo = EMPLOYEES.CarNo
Make Model FirstName LastNam
e
Triumph Spitfire
Bentley Mk. IV Bilda Groves
Triumph Stag Fred Jones
Ford GT 40
Shelby Cobra Sally Smith
Ford Mustang
Aston Martin DB Mk III
Jaguar D Type
This ensures that every record from the first table appears in
the answer table.
Outer joins - 2
Substitute RIGHT JOIN for LEFT JOIN
SELECT CARS.Make,
CARS.Model,
EMPLOYEES.FirstName
EMPLOYEES.LastName
FROM CARS RIGHT JOIN EMPLOYEES
ON CARS.CarNo = EMPLOYEES.CarNo
Make Model FirstName LastName
John Greeves
Bentley Mk. IV Bilda Groves
Triumph Stag Fred Jones
Shelby Cobra Sally Smith

This ensures that every record from the second table appears in the
answer table.
Outer joins - 3

To produce all of the employees and some of the cars:


FROM EMPLOYEES LEFT JOIN CARS
and
FROM CARS RIGHT JOIN EMPLOYEES

To produce all of the cars and some of the employees:


FROM CARS LEFT JOIN EMPLOYEES
and
FROM EMPLOYEES RIGHT JOIN CARS
UNION -1
UNION returns all of the records from two queries and
displays them, minus any duplicates:

SELECT Cars.make, CARS.Model,


EMPLOYEES.FirstName, EMPLOYEES.LastName
FROM CARS RIGHT JOIN EMPLOYEES
ON CARS.CarNo = Employees.CarNo

UNION

SELECT Cars.make, CARS.Model,


EMPLOYEES.FirstName, EMPLOYEES.LastName
FROM CARS LEFT JOIN EMPLOYEES
ON CARS.CarNo = Employees.CarNo
UNION - 2

Make Model FirstName LastName


John Greeves
Aston Martin DB Mk III
Bentley Mk. IV Bilda Groves
Ford GT 40
Ford Mustang
Jaguar D Type
Shelby Cobra Sally Smith
Triumph Spitfire
Triumph Stag Fred Jones
Summary

• A database is a collection of data.

• A DBMS is a database management system. It is the


software that allows you to manipulate that data.

• Four key components to a database:

• Tables
• Forms
• Queries
• Reports
Summary cont…

 All data in a RDBMS is in a table.


 A form is a device for viewing and editing data in a
table.
 Queries are used to select records from a database.
 Reports produce output from a table ready for the
printer.
 Every field has a field name - shown at the top of the
columns. This must be unique within a table.
Summary cont…
 When you have decided what data to include in our
table you need to decide on what type each field is.

 Structured Query Language pronounced as Sequel or S-


Q-L a data access language or data sub-language.

 Used for creating and deleting tables, updating and


editing as well as simple queries.
Visual Basic

LECTURE-16
Topics to be covered

•Problems with single table


databases.

•Multiple table databases.

•Types of relationships
Single table databases

The examples we have looked at are all single


table databases.

Serious problems emerge with single table


databases in real-world systems.
An awful table
SINGLETABLE

There are some serious problems with this table -


what are they?
Redundant data

There is a lot of repeated data, for


example the supplier names Harrison
and Ford are repeated many times.

Similarly the employee details such as


date of birth, date employed, first and
last name.
Typographical errors

When typing text it is easy to make


mistakes, for example, records 4 and
6 are probably the same person.

A SQL search for her would not pick up


one of these records.

Avoid typing wherever possible.


Updating and modifying data
If there is a mistake in a person's details or if a
woman marries and changes her surname
many records may have to be updated.

This table is the only place where employee


details are stored. If a new employee joins the
company how can his details be entered onto
the system before he makes a sale?

The best solution to these problems is to use a


multiple table structure.
Multiple tables
EMPLOYEES
EmployeeNo FirstName LastName DateOfBirth DateEmploye
d
1 Manny Tomanny 12 Apr 1956 01May 1989
2 Rosanne Kolumns 21 Mar 1967 01 Jan 1990
3 Cas Kade 01 May 1967 01 Apr 1992
4 Norma Lyzation 03 Apr 1956 01 Apr 1992
ORDERS
OrderNo EmployeeNo Customer Supplier Price Item
1 1 Henderso Harrison 235.00 Desk
n
2 4 Thompso Ford 234.00 Chair
n
3 1 McColgan Harrison 415.00 Table
4 2 Wellingto Ford 350.00 Lamp
n
5 3 Henderso Ford 234.00 Chair
n
6 2 Wellingto Ford 350.00 Lamp
n
Multiple tables
Not much data is saved in this example
because the number of orders is so low.

However many orders are made the employee


details are only listed once.

The two tables are linked by the employee


number.
To find out who made order 2 get the
employee reference number from the
ORDERS table - 4 then check in the
EMPLOYEES table to find that it was Norma
Lyzation.
Redundant data
How much data is saved?

Assume:
1000 employees and 1Kbyte of data each.
100,000 sales and 2Kbytes each.

In the single sales solution the 100,000 sales records


will contain an extra 1Kbyte of date (for the employee
information).
Single table solution - space required:
100,000 * (2+1) = 300,000 Kbytes
Two table solution - space required:
1000 * 1 + 100,000 * 2 = 201,000 Kbytes
A saving of 99Mbytes.
Typographical Errors
Since an employees name is only typed
once it is more likely to be correct.
Updating and modifying data

If an employee's details change, only one


record must be updated.

If new employees join the company they


can simply be added to the EMPLOYEE
table - even before they have placed any
orders.
OO terminology
An OO approach to designing relational database
systems only works imperfectly.

A table may be considered as an class.


A record may be considered as an object.

The fields of a record may be considered as the


properties.

BUT an OO system must exhibit characteristics:


Inheritance.
Polymorphism.
Encapsulation.
Identifying tables
How do you decide what tables to create?

Provide a separate table for every "real-


world" object you want to store
information about.

Tables (Classes) could be:


Employees.
Customers.
Orders.

The tables only take information which is


unique to them.
Furniture and ice cream sales - 1
Suppose we were selling furniture, the
information on each item could be:

•Stock No.
•Purchase date
•Purchase price
•Sale date
•Sale price
•Colour

If we start selling ice cream as well as furniture


what changes do we need to make?
Furniture and ice cream sales - 2

Maybe none, if both furniture and ice cream sales


have the same fields, they are members of the
same class and can be saved in the same table.

The table is really a SALES table rather than a


more specific FURNITURE or ICECREAM
table.

Objects with the same properties are in the same


class.
Identifying objects
An order system for a small business which sells
items to customers.
Some employees are allocated rooms in the head
office.
Some buildings are rented for storage.

What objects are there?


•Customers.
•Items.
•Orders.
•Employees.
•Rooms.
•Buildings.
Multiple tables revised.
EMPLOYEES
EmployeeNo FirstName LastName DateOfBirth DateEmployed
1 Manny Tomanny 12 Apr 1956 01May 1989
2 Rosanne Kolumns 21 Mar 1967 01 Jan 1990
3 Cas Kade 01 May 1967 01 Apr 1992
4 Norma Lyzation 03 Apr 1956 01 Apr 1992

ORDERS ITEMS
Order Employee Customer Item Item Supplier Price Item
No No No No
1 1 Henderson 1 1 Harrison 235.00 Desk
2 4 Thompson 2 2 Ford 234.00 Chair
3 1 McColgan 3 3 Harrison 415.00 Table
4 2 Wellington 4 4 Ford 350.00 Lamp
5 3 Henderson 2
6 2 Wellington 4
7 2 Henderson 1
Identifying objects
An order system for a small business which sells items to
customers.
Some employees are allocated rooms in the head office.
Some buildings are rented for storage.

What objects are there?


•Customers.
•Items.
•Orders.
•Employees.
•Rooms.
•Buildings.

Each of these objects can be mapped onto a table.


Fields and tables
We have six tables: CUSTOMERS, ITEMS, ORDERS,
EMPLOYEES, ROOMS, BUILDINGS.
Where do the following items go?
Field Table
Employee DoB EMPLOYEES
Order number ORDERS
Customer name CUSTOMERS
Employee name EMPLOYEES
Item name ITEMS
Customer address CUSTOMER
Employee next of EMPLOYEE
kin
Room number ROOMS
Rent BUILDINGS
The EMPLOYEES table
EMPLOYEES
EmployeeNo FirstName LastName DateOfBirth DateEmploye
d
1 Manny Tomanny 12 Apr 01 May
1956 1989
2 Rosanne Kolumns 21 Mar 01 Jan 1990
1967
3 Cas Kade 01 May 01 Apr 1992
1967
4CUSTOMERS
Norma Lyzation 03 Apr 01 Apr 1992
CustomerNo FirstNam LastName 1956
e
1 Brian Thompson
2 Sally Henderson
3 Harry McColgan
4 Sandra Wellington
Relationships

There are four types of relationships between


tables:

• one to many

• one to one

• many to many

• none
One to many

There is a one to many relationship between


customers and orders: one customer can place
none, one or more orders.

This is very common


One to one
If every employee is allocated their own
room then there is a one to one
relationship between employees and
rooms.

No employee can be allocated more than


one room.

This is an unusual relationship and the two


tables can usually be combined into one
table.
Many to many

If a customer can be served by more than one


employee and an employee can serve more
than one customer.

This means that any number of employees can


serve any number of customers.

There is no requirement that more than one


employee serves a customer.

This is very common.


None
Some tables in a system have no relationship, for
example the BUILDING table has no relationship to
the CUSTOMER table.

In a six table system how many relationships could


there be?

5 + 4 + 3 + 2 + 1 = 15
Modelling relationships
The relationships between tables is achieved
by using:

• Primary and foreign keys

• Joins

Conventions:
Table names are in capitals and field names
are in CamelCaps. They are separated by
a dot. e.g.
CUSTOMERS.CustomerNo
Primary key
A primary key has a unique value and contain no
null values.

CUSTOMERS
CustomerN FirstName LastName
o
1 Brian Thompson
2 Sally Henderson
3 Harry McColgan
4 Sandra Wellington

The primary key is CUSTOMER.CustomerNo


Primary key 2
ORDERS
OrderNo EmployeeN CustomerN Supplier Price Item
o o
1 1 2 Harrison 235.00 Desk
2 4 1 Ford 234.00 Chair
3 1 3 Harrison 415.00 Table
4 2 4 Ford 350.00 Lamp
5 3 2 Ford 234.00 Chair
6 2 4 Ford 350.00 Lamp
7 2 2 Harrison 235.00 Desk
The primary key is ORDERS.OrderNo
What happens if a table contains 10 million
entries - does Access check all of them to make
sure that the primary key is unique?
YES!
Using multiple fields
A primary key may be a combination of more than one
field, for example FirstName and LastName.

Generally these are a bad idea and slow down the database.

Choosing a primary key:

•Access has an autonumber facility which counts the


number of the records and gives a unique value.

•Guaranteed unique values such as N.I number should be


used. (Is the post code unique?)
Foreign keys - 2

Every table must have a primary key, but may


not have a foreign key.

A table which has more than one foreign key has


more than one relationship.

A foreign key is defined when a join is made.


Foreign keys - 1
A foreign key is one which references a primary key of
another table, for example:
ORDERS
OrderNo EmployeeNo CustomerNo Supplier Price Item
1 1 2 Harrison 235.00 Desk
2 4 1 Ford 234.00 Chair
3 1 3 Harrison 415.00 Table
4 2 4 Ford 350.00 Lamp
5 3 2 Ford 234.00 Chair
6 2 4 Ford 350.00 Lamp
7 2 2 Harrison 235.00 Desk

The ORDERS.CustomerNo field is a foreign key since


CUSTOMER.CustomerNo is a primary key of another
table.
ORDERS.EmployeeNo is also a foreign key
One to many relationships
How do we decide on the relationship between
tables. Consider the relationship between
customers and orders.
One customer can place more than one order - a
one to many relationship.
The primary keys are CUSTOMER.CustomerNo
and ORDERS.OrderNo.
A table is needed to link these primary keys.

To make the one to many relationship possible the


primary key of the "one" part of the relationship
must be placed in the "many" part of the
relationship.
One to one join
EMPLOYEES EmployeeNo FirstName LastName DateOfBirth DateEmploye
d
1 Manny Tomanny 12 Apr 01 May
1956 1989
2 Rosanne Kolumns 21 Mar 01 Jan 1990
1967
ROOMS 3 Cas 01
Kade May 01 Apr 1992
EMPLOYEES.EmployeeNo
1967 is the primary
RoomNo EmployeeNo
4 key Norma Lyzation 03 Apr 01 Apr 1992
1 1 ROOMS.RoomNo is a primary
1956 key.
12 2 ROOMS.EmployeeNo is a foreign key
23 3 which is also unique.
24 4 Therefore there is a one to one relationship
between ROOMS and EMPLOYEES
Note an EmployeeNo can exist in
EMPLOYEES which does not appear in
ROOMS.
Many to many - 1
An employee may deal with more than one customer
and a customer may deal with more than one
employee.

But the interaction is always via an order.


The relationship between a customer and orders is a
one to many.

Similarly the relationship between an employee and an


order is also one to many.
This pair of one to many relationships allows a many to
many relationship to be formed between the
customer and the employee.
Many to many - 2
CUSTOMERS EMPLOYEES
Customer FirstNam LastName Employee FirstNam LastNam DateOfBirth DateEmploye
No e No e e d
1 Brian Thompson 1 Manny Tomanny 12 Apr 1956 01 May 1989
2 Sally Henderso 2 Rosanne Kolumns 21 Mar 1967 01 Jan 1990
n
3 Cas Kade 01 May 1967 01 Apr 1992
3 Harry McColgan
4 Norma Lyzation 03 Apr 1956 01 Apr 1992
4 Sandra Wellingto
ORDERS n

OrderNo EmployeeN CustomerN Supplier Price Item


o o
1 1 2 Harrison 235.00 Desk
2 4 1 Ford 234.00 Chair
3 1 3 Harrison 415.00 Table
4 2 4 Ford 350.00 Lamp
5 3 2 Ford 234.00 Chair
6 2 4 Ford 350.00 Lamp
7 2 2 Harrison 235.00 Desk
Relationships in Access
There is no special mechanism to make many to
many relationships - just two one to many
relationships
Extending the system
If we want to extend the system so that you can order
more than one of an item, for example for tables how
can this be achieved?
POOR-ORDERS-1
OrderNo EmployeeN CustomerN Item Item Item Item Item5
o o 1 2 3 4
1 1 2 1 4
2 4 1 3
3 1 3 4 3 3 3 3
4 2 4 2 1 3
5 3 2 3 2
6 2 4 2 3
7 2 2 1 2

What's wrong with this?


A lot of blank space. What happens if 6 items are ordered?
Another poor solution
POOR-ORDERS-2
OrderNo EmployeeN CustomerNo Desk Lamp Chair Table
o
1 1 2 1 1
2 4 1 1
3 1 3 4 1
4 2 4 1 1 1
5 3 2 1 1
6 2 4 1 1
7 2 2 1

What's wrong with this?

A lot of blank space.What happens if the store sells a new item?


AORDERS
multi table solution
ORDERS/ITEMS
OrderNo EmployeeNo CustomerNo
OrderNo ItemNo NumberOfItems
1 1 2
2 4 1 1 1 1

3 1 3 1 4 1

4 2 4 2 3 1

5 3 2 3 3 4

6 2 4 3 4 1

7 2 2 4 1 1
4 2 1
ITEMS
4 3 1
ItemNo Supplier Price Item
5 2 1
1 Harrison 235.0 Sofa
0 5 3 1
2 Ford 350.0 Lamp 6 2 1
0 6 4 1
3 Ford 234.0 Chair 6 1 1
0

No 4wastedHarrison 415.0 Table


space, any
0
number can be ordered, new items can be added.
Choosing a primary key
ORDER.OrderNo is a primary key.

ITEMs.ItemNo is a primary key.

BUT - there is no unique key in ORDER/ITEMS

ORDERS/ITEMS
OrderNo ItemNo NumberOfItems
1 1 1
1 4 1
2 3 1
3 3 4 However, the combination
3 4 1 of OrderNo and ItemNo in
this table does provide a
unique primary key.
Terminology

Parent, Child, Own, Owned, Superior, Subordinate, Dependency, Foreign key.


The ORDERS table is owned by the EMPLOYEES table and is therefore its child.
ORDERS is subordinate to EMPLOYEES and also subordinate to its other parent
CUSTOMERS.
CUSTOMERS owns ORDERS and is its superior.
All child tables have at least one foreign key.
ORDERS has two parent tables and therefore two foreign keys.
The foreign keys establish a dependency between the parent and the child.
The final system - 1
EMPLOYEES
EmployeeNo FirstName LastName DateOfBirth DateEmployed
1 Manny Tomanny 12 Apr 1956 01 May 1989
2 Rosanne Kolumns 21 Mar 1967 01 Jan 1990
3 Cas Kade 01 May 1967 01 Apr 1992
4 Norma Lyzation 03 Apr 1956 01 Apr 1992
5 Juan Tomani 12 Apr 1956 10 Apr 1992
6 Del Eats 01 May 1957 01 May 1994

OrderNo EmployeeN CustomerNo


ORDERS o
CUSTOMER
1 1 2
CustomerN FirstName LastName
o 2 4 1
1 Brian Thompson 3 1 3
2 Sally Henderson 4 2 4
3 Harry McColgan 5 3 2
4 Sandra Wellington 6 2 4
7 2 2
The final system - 2
ORDERS/ITEMS ITEMS
OrderNo ItemNo NumberOfItems ItemNo Supplier Price Item
1 1 1 1 Harrison 235.00 Sofa
1 4 1 2 Ford 350.00 Lamp
2 3 1
3 Ford 234.00 Chair
3 3 4
4 Harrison 415.00 Table
3 4 1
4 1 1
4 2 1 ROOMS
4 3 1 RoomNo EmployeeNo
5 2 1 1 1
5 3 1 12 2
6 2 1
23 3
6 4 1
24 4
6 1 1
Multi table queries - 1
Queries are able to extract information from more than one
table. You can also create forms using multi table data.
Create a query first:
•On the Query tab Click the New button.
•Select Design view.
•Select the tables you want to extract data from.
Multi table queries - 2
Add the fields ROOMS.RoomNo, EMPLOYEES.FirstName
and EMPLOYEE.LastName.

The query produces this


result.
Multitable queries - 3
To create a Form, select the Form tag and click on the New
button.
Choose AutoForm Columnar and select the Query just created as
the basis for the Form.

The form produced is based not on a single base table but from
the results of a query.
This is possible since output from a query is always a table.
This is called closure.
Summary
 There are many problems with single table databases.viz.
redundant data, typographical errors, problems in
updating and modifying data.
 These problems can be overcome by creating multiple
table databases.
 A multiple table database can be created by linking two
tables on a common field.
 There are four types of relationships between tables:
• one to many
• one to one
• many to many
• none
Summary cont…
• The relationships between tables is achieved by using:
• Primary and foreign keys
• Joins

• A primary key has a unique value and contain no null


values.
• A foreign key is defined when a join is made.
• A foreign key is one which references a primary key of
another table.
• Queries are able to extract information from more than one
table. You can also create forms using multi table data.
Visual Basic

LECTURE-17
Topics to be covered

 Creating and manipulating databases using Data


Control
Database Creation
 
Introduction
 
A database is collection of related files. For an
applications, a database is always required. Visual Basic
also supports databases. In a database, we can have as
many table as we need. The relationships among various
tables can be established. These databases can be accessed
in two ways:
 
 Using Data Control. Data control provides limited features.
 Using Data Access Object. DAO provides a wide range of
programming features.
Following steps describe the method to create database.
 Select ADD-INS option from main menu.

 Select Visual Data Manager. A dialogue box titled with

VIS-DATA will appear.


 If existing database is to be open, select OPEN

DATABASE from file option, otherwise for creation of


new database select NEW DATABASE from file.
 Select the base of database viz: Microsoft Access,

foxpro, dBase, Excel, Text files or ODBC. Access is


default backend database.
 Select the database file name or type new database file

name Figure 8.1 will appear. By default , it will show


two windows.
 SQL window. For the use of SQL statements.
 Database Window. For creation/selection of database
tables. It is just like project explorer, showing various
table, properties, fields and indexes.

 On clicking right button of mouse on database windows,


four options pulldown menu will appear, rename, refresh
list new table, delete.

 Select new table. A dialogue box will appear. It has the


following editable fields.
 Table Name: Type the name of name.
  Field List: Displays the list of fields of table.
  Add Field: Add field selected when it is desirable to add a new
field. Click the push button meant for adding field. Another
dialogue box will appear as shown in figure 8.3.
  Name Allows you to type the name of the field you want to add.
 Type Lets you determine the operational or data type of the field.
 Size Lets you determine the maximum size, in bytes, of the field.
 Fixed Length If selected, allows you to have a field with a fixed
size.
 Variable Length If selected, allows you to have a field whose
length you can adjust.
 Auto Increment If selected, automatically updates the next row
or column.
 Allow Zero Length Allows you to have a zero-length string as a
valid setting.
  Required Indicates if the field requires a non-Null value.
 Ordinal Position Allows you to determine the relative position
of the field.
 Validation Text Lets you add the text of the message that your
application displays if a user tries to enter an invalid value for a
field.
 Validation Rule Lets you determine what data is valid in a field
as it is added.
 Default Value Lets you determine the default value for the field.
 Remove Field Removes the selected field (only available with jet
database engine Tables).
  Index List Lists the available indexes.
  Add index Allows to add new index.
  Name Allows you to type the name of the index.
 Primary If selected, indicates this is the primary
index for the table.
 Unique If selected, indicates that the index entry is
unique.
 Ignore Nulls If selected, indicates that fields with
Null values are not included in the index.
 Required Indicates whether the index requires a non-
Null value.
 Remove Index Removes the selected index.
 Build the Table Appends the new table to the current
database.
 Print Structure prints the table structure.
Structured Query Language
(SQL)
INTRODUCTION

Microsoft Jet database engine SQL is generally


ANSI-89 Level 1 compliant. However, certain ANSI
SQL features aren’t implemented in Microsoft Jet
SQL. Conversely, Microsoft Jet SQL includes
reserved words and features not supported in ANSI
SQL.
MAJOR DIFFERENCES
Microsoft Jet SQL and ANSI SQL each have different
reserved words and data types.

 Different rules apply to the Between...And construct,


which has the following syntax:
expr1 [NOT] Between value1 and value2
In Microsoft Jet SQL, value1 can be greater than value2;
in ANSI SQL, value1 must be equal to or less than value2.

 Different wildcard characters are used with the Like


operator.
 Microsoft Jet SQL is generally less restrictive. For
example, it permits grouping and ordering on
expressions.

 Microsoft Jet SQL supports more powerful


expressions.
Enhanced Features of Microsoft
Jet SQL
Microsoft Jet SQL provides the following enhanced
feature:

The TRANSFORM statement, which provides support


for crosstab queries
Additional aggregate functions, such as StDev and
VarP
The PARAMETERS declaration for defining
parameter queries
ANSI SQL Features Not Supported in Microsoft Jet
SQL
Microsoft Jet SQL doesn't support the following ANSI
SQL features:
 Security statements, such as COMMIT, GRANT,
and LOCK.

 DISTINCT aggregate function references. For


example, Microsoft Jet SQL doesn't allow
SUM(DISTINCT columnname).

 The LIMIT TO nn ROWS clause used to limit the


number of rows returned by a query. You can use
only the WHERE clause to limit the scope of a
query.
Accessing Database With Data
Control
You can use the data control to create applications that
display, edit, and update information from many types of
existing databases, including Microsoft Access, Btrieve,
dBASE, Microsoft FoxPro®, and Paradox.

You can also use it to access Microsoft Excel, Lotus 1-2-


3, and standard ASCII text files as if they were true
databases.

In addition, the data control allows you to access and


manipulate remote Open Database Connectivity (ODBC)
databases such as Microsoft SQL Server and Oracle.
The data control implements data access by using the
Microsoft Jet database engine, the same database engine
that powers Microsoft Access.

This technology gives you seamless access to many


standard database formats and allows you to create data-
aware applications without writing any code.
What You Can Do With Data
Control

You can use the data control to create simple database


applications without writing any code at all.

You can also use it together with Visual Basic code to


create full-featured applications that give you a high
degree of programming control over the behavior of your
application’s data.

This topic will consider the simple no-code approach.


The data control can perform the following tasks without
the use of code:

Connect to a local or remote database.


Open a specified database table or define a set of records

based on a Structured Query Language (SQL) query of the


tables in that database.
Pass data fields to bound controls, where you can display

or change the values.


Add new records or update a database based on any

changes you make to data displayed in the bound controls.


Trap errors that occur as data is accessed.

Close the database.


To create a database application, you add the data
control to your forms just as you would any other
Visual Basic control.

You can have as many data controls on your form as


you need.

As a rule, you will use one data control for each
database table that you need to manipulate.
The Data Control
The Visual Basic data control is the control used to gain
access to database tables.

The data control allows you to establish a link to a single


Dynaset data object in a database.

You can have more than one data control in your program
and more than one data control on a single form.
Data Control Properties

Database Name
Exclusive
Options
Read Only
Record Source

 There is a sixth data control property that is used only


for data access: the Connect property.

 The Connect property is used when you are accessing


non-Microsoft Access database.
Setting Database Name and Record
Source Properties
The Database Name property contains the name of the
database you want to access.

In Microsoft Access database this would be the


complete drive, path, and filename of the Microsoft
Access database file.

For Example, to connect to the BOOKS. MDB


Microsoft Access database located in the c:\DATA
directory, you would set the Database Name property to
c:\DATA\BOOKs.MBD.
You can do this through the Property box at design time
or through Visual Basic code at runtime.

Any time you use Visual Basic code to change data


control properties, you must invoke the Refresh method
to update the data control.

When you set the Database Name property, you are


telling Visual Basic the database you are using.

However, at this point, Visual Basic does not know


what data table you want to use with the data control.

Use the Record Source property to indicate the data


table you want to access.
Setting the Read Only and
Exclusive Properties
There are two more data control properties: Read Only
and Exclusive.

The Read Only and Exclusive properties are Boolean


(True/False) properties that you can use to limit access
to the database.

When you set the Exclusive property to True, you are


opening the database for your use only.
 In other words no one else open the database (or any of
the tables in the database) while you have it open.

 This is handy when you want to perform major updates


or changes to the database and do not want anyone else
in the file at the same time.
.
 For the example, you"ll open the database for exclusive
use. Modify the OpenDB procedure so that it sets the
Exclusive property to True.

Your code should look like the following code:


Public Sub OpenDB ()

Dim cDBName As String 'declare a string variable


Dim cTb1Name As String 'declare a string variable
Dim bExclusive As Boolean 'declare true/false var

CDBName=“c:\tysdbvb5\source\data\books5.mdb”
CTb1Name = “ Authors” 'point to authors table
bExclusive = True 'set to exclusive open
Data1.DatabaseName = cDBName 'set database property
Data1.RecordSource = cTb1Name
Data1.Exclusive = bExclusive
Data1.Refresh 'update data control properties

End Sub
The Read Only property opens the database with read
rights only.

You will not be allowed to make any changes,


additions, or deletions in any table while you have the
database open in read-only mode.

This is handy when you are using the data for creating
a report or for display purposes only.
Setting the options Property
The Options property of the Visual Basic data control
allows you to establish the properties of the Dynaset
opened in the RecordSource property of the data
control.

There are several options that can be set in the Options


property of the data control the three most commonly
used options.

Here are the three Options values for the data control
that is covered today:
dbDenyWrite
dbReadOnly
dbAppendOnly
These three options are actually Visual Basic constants
that are predefined in the language.

They are like Visual Basic variables, except that they


have a single, set value that cannot be changed.

Dynaset option values


Setting the dbDenyWrite option prevents other from
changing the data in the Dynaset while you have it open
(similar to the Exclusive database property).

The dbReadOnly option prevents you from changing the


data in the Dynaset (similar to the ReadOnly database
property).
The dbAppendOnly options lets you add new data to
the Dynaset but does not let you modify or delete
existing records.

Setting the dbReadOnly option speeds processing of


the Dynaset and is handy for generating displays or
reports.

The dbDenyWrite option is useful when you want to


make major changes to the Dynaset and want to prevent
other users from accessing the records in the Dynaset
until you are done making your changes.

Using the dbAppend only option lets you create data


entry routines that limit user rights to adding records
without deleting or modifying existing ones.
Data Control Methods

The Visual Basic data control has several methods, but


only three are database related. Here's a list of them:

Refresh
UpdateControls

UpdateRecord
Refresh method is used any time you change any of the
properties of the data control.

 Using the refresh method updates the data control and


forces it to rebuild the Dynaset.

This refresh updates not only the behaviors and


properties of the Dynaset but also the records in the set.

If records are added to the table by another user after


your program has created its Dynaset, invoking the
refresh method will make sure your Dynaset contains
the most recent records.
The UpdateControls method is used to update any
bound input controls.
Invoking the UpdateControls method is the same as

reading the current record and putting the values in the


fields of the data table into the input controls on a form.
This happens automatically each time you press the

arrow buttons on the data control.


But you can force the update to occur any time during

the data entry process.


It's especially handy if you want to undo user changes

to data record.
Using the UpdateRecord method updates the Dynaset

without moving the record pointer.


Data Control Events
There are three data control events that relate to database
functions:
 Reposition
 Validate
 Error
The Reposition event occurs each time the data control
moves to a new position in the Dynaset.
The Validate event occurs each time a data control leaves

the current record.


The Error event occurs each time a database error occurs

when the arrow buttons on the data control are used to


move the record pointer.
To create a simple database
application follow these steps:

1. Add the data control to a form.


2. Set its properties to indicate the database and
table from which you want to get information.
3. Add bound controls (such as text boxes, list
boxes, and other controls that you “bind” to the
data control).
4. Set the properties of the bound controls to
indicate the data source and data field to be
displayed.
5. When you run the application, these bound controls
automatically display fields from the current record
in the database.
Data Control Properties

Like all Visual Basic controls, the data control has some
properties that must be set in the Properties window at design
time.
Many of these properties can also be set at run time in Visual

Basic code.
To use the data control, at a minimum you must set the

DatabaseName and RecordSource properties.


Once you have set the DatabaseName property, Visual Basic

will retrieve the names of all tables and available queries in the
database and display them in the drop-down list for the
RecordSource property.
If you want to open an external database (FoxPro,
Btrieve, Paradox, dBASE, Microsoft Excel, Lotus 1-2-3,
Text, or ODBC), you must also set the Connect property
using the Properties window.

Once you choose a table or query from the list, you will
be able to use the Properties window to select a valid
DataField property setting on each of your bound controls.
You can also set or change the data control and bound

control properties at run time.

Once the correct properties are set, you can use the data
control’s Refresh method to reopen the database (if
necessary) and rebuild the recordset with the new property
settings.
Understanding Recordsets

Visual Basic retrieves and displays database records


using the Recordset object provided by the Microsoft
Jet database engine.

A Recordset object represents the records in a base


table or the records that result from running a query.

The following table lists the three types of Recordset


objects available on the data control.
Recordset type Description

Table-type Recordset (dbOpenTable) A set of records that represents


a single database table that you can use to add,
change, or delete records.
Dynaset-type Recordset (dbOpenDynaset) A dynamic set of records that
represents a database table or the results of a
query containing fields from one or more tables.
You can add, change, or delete records from a
dynaset-type Recordset, and the changes will be
reflected in the underlying table(s).
Snapshot-type (dbOpenSnapshot) A static copy of a set of
Recordset records that you can use to find data or
generate reports. A snapshot-type Recordset can
contain fields from one or more tables in a
database but can’t be updated.
You can choose the type of Recordset object that you want
the data control to create using the RecordsetType property.
The default value is vbDynasetType.

Dynaset- and snapshot-type Recordsets are stored in local


memory.

If you don’t need your application to select fields from


more than one table, and you are working with a non-ODBC
source, the table-type Recordset may be the most efficient in
speed and memory use and in local TEMP disk space.

Recordset objects created in code (not available in the


Visual Basic, Learning Edition) can be assigned to the
Recordset property of the data control, using the Set
statement:
Set Data1.Recordset = MyRecordset

 Similarly, a Recordset object created by one data


control can be assigned to another data control at run
time.

The Jet database engine provides a large number of


database and recordset properties and methods.

You can use these properties and methods directly with


the data control by referring to the data control’s
Database and Recordset properties.
Creating A Simple Database
Application
 The following procedure gives you a brief overview
of how to use the data control in a Visual Basic
application.
 The example uses the Biblio.mdb sample database
supplied with Visual Basic.

To use the data control in an


application
 Select the data control in the Toolbox, and draw a
data control on a form.
 After you draw the control on the form and size it, the
caption appears. The default name of the control is Data1.

 In the Properties window, set the Connect property to the


type of database you want to use.

 In the Properties window, set the DatabaseName property


to the file or directory name of the database to which you
want to connect.

 If your database is not available at design time, you will need


to fill in the DatabaseName and RecordSource properties at
run time. This example uses the Biblio.mdb sample database.
 Set the RecordSource property to the name of the
database table you want to access.

 If the database is currently available, you can


select a table from the drop-down list in the
Properties window.

 If your database could not be found, the drop-


down list will not appear in the RecordSource
Settings box and an error message will appear.
This example uses the Titles table.
Draw a text box on the form to display the database
information.

This control will be used to display and edit a selected


field from the database. You can also use other data-
bound controls, including check boxes, picture boxes,
image controls, labels, list boxes, combo boxes, and
grid controls.
In the Properties window, set the DataSource
property for Text1 to the name of the data control
(Data1). This binds the text box to the data control.
Add a label and set its Caption property to the name of
the database field this text box will expose.
Set the DataField property for Text1 to the name of the
field in the database table you want to view or modify.
The example uses the Title field of the Titles table.
Repeat steps 5, 6, 7, and 8 for each additional field you
want to access. In the following example, the Title, ISBN,
and Year Published fields have been selected from the
Titles table.
Now run the application. You can use the four arrow
buttons on the data control to move to the beginning of
the data, to the end of the data, or from record to record
through the data.

You can modify the information in the database by


changing the value displayed in any of the bound
controls.

When you click a button on the data control to move to


a new record, Visual Basic automatically saves any
changes you’ve made to the data.

Of course, you can add code to enhance your


application further.
Adding, Updating And Deleting
Records

You can add, update, and delete records automatically


using the data control and data-bound controls.

For greater flexibility and control, you can also write


Visual Basic code to perform these operations, using
methods of the data control’s Recordset object.
Adding a New Record

To add a new record to the database with the data control,
you must set the EOFAction property to True, which
allows a new record to be added to the end of the recordset.

EOFAction and BOFAction are properties of the data


control that determine what happens when you move past
the beginning or end of the data control’s recordset.

 The possible settings for the EOFAction property are


listed in the following table.
Setting Value Action

vbEOFActionMoveLast 0 A MoveLast method was used,


positioning the current record at the
last record in the recordset and
effectively preventing the user from
scrolling past the end of the
recordset.
vbEOFActionEOF 1 Positions the current record to the
invalid (EOF) record and disables the
MoveNext button on the data control.
vbEOFActionAddNew 2 Validates the last record and
automatically invokes the AddNew
method, and then positions the data
control on the new record.
 With the EOFAction property set to
vbEOFActionAddNew, when the user moves past the
last record, the data control will automatically create
a new record and allow the user to enter data.

 If new data is entered, moving off the current (new)


record will automatically trigger an update and save
the new record in the database.

 If the user moves off the new record without adding


data, the new record will be discarded.
Updating or Deleting a Record
To update or delete a record using the data control,
simply position the control on the desired record and
modify or delete it in any data-bound control in which it
is displayed.

After the record is changed or deleted, use the data


control to move the recordset forward.

The data control automatically handles the updating of


the changed or deleted record.
This method provides a convenient way of entering
many new records consecutively.

Users simply move to the end of the database and then


use the MoveNext button to move one record past the
end of the file.

They can then begin adding new records, moving the


recordset forward after each record is entered.

The data control automatically handles the addition


and updating of the records.
Summary
 A database is collection of related files.
 These databases can be accessed in two ways:
 Using Data Control. Data control provides limited
features.
 Using Data Access Object. DAO provides a wide
range of programming features.

 You can use the data control to create applications that


display, edit, and update information from many types
of existing databases, including Microsoft Access,
Btrieve, dBASE, Microsoft FoxPro®, and Paradox.
Summary cont…
 The data control implements data access by using the
Microsoft Jet database engine, the same database engine
that powers Microsoft Access.

 This technology gives you seamless access to many


standard database formats and allows you to create data-
aware applications without writing any code.

 You can use the data control to create simple database


applications without writing any code at all.
Summary cont…

 You can have as many data controls on your form as you


need.

 As a rule, you will use one data control for each database
table that you need to manipulate.

 There are three data control events that relate to database


functions:
 Reposition

 Validate

 Error
Summary cont…

 Like all Visual Basic controls, the data control has


some properties that must be set in the Properties
window at design time.

 To use the data control, at a minimum you must set the


DatabaseName and RecordSource properties.
Exercises:
Create data-base with following tables.
 
A) Employees
 
1. Employee
 
Emp-Cd
Name
DOJ
Des-Cd
Dept-Cd
Address
Salary
Age
 2.           Department
 
Emp-Cd
Dept-Cd
Dname

 
3. Designation
 
Emp-Cd
Desi-Cd
Description
Employees Database

Emp cd

Name
DOJ

Desg-cd Desg-Name

Depa-Cd Dept-Name

Address Age

Salary
1. Using data control display fields & data in three respective
forms.

B). Stu-Personel Fees

Stu-registration no(Stu-rgt) Fstatus (Paid 0r not)


Stu-name P-rs.
Stu-Fname Balance
DOB Stu-rgt
Address
 
Stu-Result
Stu-rgt
Rno
Class
ADM Screen
Rgt No.
Class Add Modify
R-no Delete Update
Name Next
H.W Marks Previous
Monthly Top
Dec Test View Bottom

Total Disabled
Save
Disabled Cancel
Grade Disable
Marks in H.W  = 10
Mark in Monthly list  = 15
Mark in Dec Test  = 75
Final test  = 100
Total  = 200
Grade For above data base make form
 
2. For database B make a form which will be displayed
as : (only for those student whose fee has been paid or
balance  = 500 (if paid)
Visual Basic

LECTURE-18
Topics to be covered

 Database programming using Data Access Objects.


Introduction To Data Access
Objects (DAO)

All applications use structured information of one kind


or another, whether it is accounting data, scientific
measurements, employee information, or a list of
recipes.

Data access in Microsoft Visual Basic gives you the


tools to create and use structured database systems to
manage your application's data.
These tools include the Microsoft Jet database engine,
the Data control, and the data access objects (DAO)
programming interface.

Using data access objects, you can create databases


and build full-featured applications that access existing
databases in many popular formats, including Microsoft
Access, Microsoft FoxPro, and Paradox, as well as
Open Database Connectivity (ODBC) client/server
databases like Microsoft SQL Server.

The ability to create and access structured database


systems gives you many programming advantages:
 It lets you write programs that use existing databases.

It allows your application to share data with other


programs.

It simplifies your programming, since you do not need


to handle low-level file accessing and searching.
Data Access In Visual Basic

Visual Basic provides two methods of interfacing with the Jet


database engine: the Data control and data access objects.

While the Data control gives you limited ability to access


existing databases without programming, the DAO model is a
complete programming interface that gives you total control of
the database.

These two methods are not mutually exclusive; in fact, there


are many situations where you will want to use both of them
together.
The DAO model is a collection of object classes that
model the structure of a relational database system.

They provide properties and methods that allow you to


accomplish all of the operations necessary to manage
such a system, including facilities for creating
databases, defining tables, fields and indexes,
establishing relations between tables, navigating and
querying the database, and so on.
The Jet database engine translates these operations on data
access objects into physical operations on the database files
themselves, handling all the mechanics of interfacing with the
different supported databases.

Database programming in Visual Basic consists of creating data


access objects, such as Database, TableDef, Field, and Index
objects, that correspond to the various parts of the physical
database you want to access.

You use the properties and methods of these objects to perform


operations on the database.

You can display the results of these operations and accept input
from the user on Visual Basic forms, using both bound and
unbound controls.
This approach simplifies the code you need to write and
insulates you from the underlying structure and
mechanics of retrieving and updating data.

It gives you great flexibility, because you can use the
same objects, properties, and methods to work with a
wide variety of supported database formats. Also, if you
change from one database format to another (for
example, porting a local Microsoft Access database to a
SQL Server database on a network), you'll need to make
few changes in your code to accommodate the change.
 You can even create applications that join tables from
two or more different databases in a single query or
report.

 There are three categories of databases that Visual Basic


recognizes through DAO and the Jet engine:
Visual Basic Databases
Also called native databases, these database files use the same
format as Microsoft Access. These databases are created and
manipulated directly by the Jet engine and provide maximum
flexibility and speed.

External Databases
These are Indexed Sequential Access Method (ISAM) databases
in several popular formats, including Btrieve, dBASE III, dBASE
IV, Microsoft FoxPro versions 2.0 and 2.5, and Paradox versions
3.x and 4.0. You can create or manipulate all of these database
formats in Visual Basic. You can also access text file databases
and Microsoft Excel or Lotus 1-2-3 worksheets.
ODBC Databases

These include client-server databases that conform to


the ODBC standard, such as Microsoft SQL Server. To
create true client-server applications in Visual Basic,
you can use ODBCDirect to pass commands directly to
the external server for processing.
Creating A Simple Database
Application (Using DAO’s)

Let’s see how to create a form in Visual Basic to


manage your database. In this project we are taking one
Employees database, the form gives you the features of
Navigating the employee table to see all the records one
by one and also you can Add, Modify, View or Delete
any on the records in the table.
The structures of all the tables in the Employee database
are given along with whole code.
Database Name : Employee.mdb
Tables :

1. Emp  ( It is employees master table)


2. Dept ( It is Department master table)
3. Desg (Its is Designation master table)
Table Name : Emp

Field Name Data Type Sizw


Empcd Integer 2
Ename Text 2.5

Desged Text 3

Depted Text 3

Salary Long 4

Doj Date/Time 8
Indexes:
Index Name Field Type
Empcd Empcd Unique
Depted Depted
Desged Desged
Table Name : Dept
Field Name Data Type Size

Deptcd Text 3

Deptnm Text 30

Loc Text 15
Indexes:
Index Name Field Type

Deptcd Deptcd Unique


Table Name : Desg
Field Name Data Type Size

Desgcd Text 3

Desgnm Text 25
Indexes:
Index Name Field Type

Desgcd Desgcd Unique


Layout of the form in the
Design Mode
Layout of the form in the Run Mode
List of Objects and their Properties
Object Name Property Name Value
Form Name Form 1
Caption RCC=>Employee Database

Label1 Index 0 (Control Array)


Caption Employee Code
Label1 Caption Employee’s Name
Index 1
Label1 Caption Department Code
Index 2
Label1 Caption Designation code
Index 3
Label1 Caption Salary
Index 4
Label1 Caption Data of Joining
Index 5
Text1 (it is a control array of 8 elements where only
index property of each text box is changing starting
from 0 to 7, they are used to display the values of
different fields in the table.
Command 1 Caption First (Control Array)
Index 0
Command 1 Caption Next
Index 1
Command 1 Caption Previous
Index 2
Command 1 Caption Last
Index 3

Command Name Chadm (Control Array)


Caption Add
Index 0
Command Name Chadm
Caption Modify
Index 1
Command Name Chadm
Caption View
Index 2
Command 1 Name Chadm
Caption Delete
Index 3
Command Name Chadm
Caption Exit
Index 4

Frame 1 Name Frame 1


Caption Save / Cancel

Option 1 Name Optsave


Caption Save
Option 1 Name Optcancel
Caption Cancel
Before you start writing the code for this program to
work and the object type variables you will be using to
store the reference the database or tables names you
have to invoke the reference for that to do that you have
to follow this :
1. Select References from the Project menu.
2. From the dialog box that gives you the list of
items select the “Microsoft DAO 2.5/3.5
compatibility library.

If you don’t select this option you are unable to use the
database type variables in you program.
Code for this program is given below
( General Declarations )

Dim Db As Database ' For a Database name


Dim RsEmp As Recordset` ' For EMP table
Dim RsDept As Recordset ' For Department Table
Dim RsDesg As Recordset ' For Designation table
Dim ButNav As Integer ' For Navigation command
buttons number
Dim ButAdm As Integer ' For ADM command
buttons number
Dim TxtNo As Integer ' for number of text box
Dim tb As TableDef ' tables defination
Dim EmpcdFound As Boolean ' to store whether empcode
found or not
Sub Enable_Disable_Text(Value As String)
For i = 0 To 7
Text1(i).Enabled = Value
Next i
End Sub

Public Sub Show_Values()


For i = 0 To 5
Text1(i) = RsEmp.Fields(i)
Next i
Search_Dept (Text1(2))
Search_Desg (Text1(3))
End Sub
Private Sub Blank_Values()
For i = 0 To 7
Text1(i) = ""
Next i
End Sub
Private Sub ChAdm_Click(Index As Integer)

ButAdm = Index
Select Case ButAdm
Case 4 ' Exit
End
Case 0 ' Add
RsEmp.AddNew
Blank_Values
Text1(0).SetFocus
Case Else ' Modify, View or Delete
Blank_Values
Text1(0).SetFocus
End Select

End Sub
Private Sub Search_Empcd()

Set tb = Db.TableDefs!emp
RsEmp.Index = "empcd"
RsEmp.Seek "=", Val(Text1(0))
If RsEmp.NoMatch Then
EmpcdFound = False
Else
EmpcdFound = True
End If

End Sub
Sub Save_Update_Data()
If ButAdm = 0 Then ' ADD button is selected
RsEmp.AddNew
Else
If ButAdm = 1 Then ' MODIFY button is selected
RsEmp.Edit
End If
End If
For i = 0 To 5
RsEmp.Fields(i) = Text1(i)
Next i
End Sub

Sub Search_Dept(tdeptcd As String)


td = Db.TableDefs!dept
RsDept.Index = "deptcd"
RsDept.Seek "=", Trim(tdeptcd)
If RsDept.NoMatch Then
MsgBox ("Department does not exists")
Text1(2) = ""
Text1(2).SetFocus
Else
Text1(6).Text = RsDept!deptnm
End If
End Sub

Sub Search_Desg(tdesgcd As String)


td = Db.TableDefs!desg
RsDesg.Index = "desgcd"
RsDesg.Seek "=", Trim(tdesgcd)
If RsDesg.NoMatch Then
MsgBox ("Designation does not exists")
Text1(3) = ""
Text1(3).SetFocus
Else
Text1(7).Text = RsDesg!desgnm
End If
End Sub
Private Sub Command1_Click(Index As Integer)

ButNav = Index
Select Case ButNav
Case 0
RsEmp.MoveFirst
Case 1
RsEmp.MoveNext
Case 2
RsEmp.MovePrevious
Case 3
RsEmp.MoveLast
End Select
Show_Values

End Sub
Private Sub Form_Load()
Set Db = OpenDatabase(app.path & \"employee.mdb")
Set RsEmp = Db.OpenRecordset("emp")
Set RsDept = Db.OpenRecordset("dept")
Set RsDesg = Db.OpenRecordset("desg")
RsEmp.MoveFirst
Show_Values
End Sub

Private Sub optcancel_Click()


Blank_Values
End Sub

Private Sub optsave_Click()


Save_Update_Data
RsEmp.Update
Blank_Values
End Sub
Private Sub Text1_LostFocus(Index As Integer)
TxtNo = Index
Search_Empcd
Select Case TxtNo ' to check for from which text box
code is executed
Case 0
If ButAdm = 0 Then 'ADD to check for the adm button
selected
If EmpcdFound Then
MsgBox ("Employee Code exists")
Text1(0) = ""
Text1(0).SetFocus
End If
Else
If Not EmpcdFound Then ' MODIFY, VIEW, DELETE
MsgBox ("Does Not exists")
Text1(0) = ""
Text1(0).SetFocus
Else
Show_Values
If ButAdm = 2 Then ' VIEW
Enable_Disable_Text (False)
MsgBox ("Press any key to cont .....")
Blank_Values
Enable_Disable_Text (True)
Else
If ButAdm = 3 Then ' DELETE
Enable_Disable_Text (False)
ans = MsgBox("Are you Sure to Delete", vbYesNo)
If ans = 6 Then
RsEmp.Delete
End If
Enable_Disable_Text (True)
Blank_Values
End If
End If
End If
End If
Case 2
Search_Dept (Text1(2))
Case 3
Search_Desg (Text1(3))
End Select
End Sub
Summary

 Using data access objects, you can create databases and


build full-featured applications that access existing
databases in many popular formats, including
Microsoft Access, Microsoft FoxPro, and Paradox, as
well as Open Database Connectivity (ODBC)
client/server databases like Microsoft SQL Server.

 While the Data control gives you limited ability to


access existing databases without programming, the
DAO model is a complete programming interface that
gives you total control of the database.
Summary cont…
 The DAO model is a collection of object classes that
model the structure of a relational database system.

 They provide properties and methods that allow you to


accomplish all of the operations necessary to manage
such a system.
Exercises:

1. Make ADM's using DAO's


Visual Basic

LECTURE-19
Topics to be covered

 Database programming using ADO Data Control.


ADO Data Control
Introduction

 The ADO data control presents a fast and easy way to


create a bound form by providing built-in functions that
define, navigate, display, add to, and update the records
in a recordset.

 The resulting form makes it easy for a user (non-


developer) to maintain records. Although the data
control defines the recordset, you’ll still need a control
for each field to automatically display the bound records.
 Figure displays a simple form with several bound
controls. The data control at the bottom of the form
contains four navigation buttons. These buttons, from
left to right, allow you to move to the first, previous,
next, and last records in the form’s recordset.
 If you update a record, VB will save that change when
you move to another record. If you close the form before
moving to another record, VB won’t save changes
you’ve made to the current record.
Creating a bound form
 Now, let’s create the form shown in Figure A. First,
launch a new standard .exe project, insert a form, and
change that form’s name to frmDataControl. Then, save
the project as DataControl.
Adding the ADO data control

 The control you’ll be working with in this article isn’t


the data control you’re accustomed to.
 The control on the Toolbox is for backward
compatibility when running applications created in older
versions of VB.
 The data control we’ll be working with--the new ADO
version-is available via the Components option. To add
the ADO data control to the Toolbox, press Ctrl+T to
open the Components dialog box.
 Select MS ADO Data Control 6.0 (OLEDB), and click
Apply, and then click Close. Once you’ve added the
ADO data control to the toolbox, you can add one to the
bottom of your form (fromDataControl). Name the new
control adoData.
Connecting AdoData to a Jet
database
 At this point, you must establish where the data control
will find its records. You have more than one option.
You can connect the data control to a SQL Server or a
Jet database.

 For our example, we’re going to connect to a Jet


database; the Nwind.mdb database (MS Access) that
comes with VB. To get started, we’ll need to change a
few of our ADO data control’s default properties. Refer
to Table A for those settings.
Table A

CommandTyp
1 - adCmdText
e

EOFAction 2 - adDoAddNew

SELECT * FROM Customers ORDER BY


RecordSource CompanyName
 Now you’re ready to set theConnectionString property.
First, select the ConnectionString property field and then
click the resulting Build button.

 Choose the Use Connection String option (if it isn’t


already selected). Next, click that option’s Build button
to display the Data Link Properties dialog box.

 Then, choose Microsoft Jet 3.51 OLE DB Provider in


the Provider tab. At this point, select the Connection tab
and identify the database you’re connecting to in the
Select or enter a database name control.

 We connected to
C:Program FilesMicrosoft Visual StudioVB98Nwind.mdb
 Of course, your setup will probably be different, so be
sure to specify the correct path to your database file.

 To test the connection, click the Test Connection button at


the bottom of the dialog box. If the connection is sound,
click OK twice to return to your form. If the connection
fails, you’ll need to adjust the entry until it works.
Adding the remaining controls

 Add the appropriate label and text box controls until


your form resembles the one shown in Figure A.
 Set each text box control’s DataSource property to
AdoData (or the name of your ADO data control) to
bind the text box to the data control.
 Now you need to bind each control to a field. To do so,
select a field from the text box control’s DataField
property. It’s also a good idea to name each control.
Table B lists the names we chose for our controls.
Table B

txtCompanyName CompanyName
txtAddress Address
txtCity City

txtRegion Region

txtZip PostalCode

txtCountry Country
Quick Tip

 You can save time when creating several controls of the


same type by creating one control and setting all the
shared properties.

 Then, use the Copy and Paste commands to create the


total number of controls you’ll need.

 When VB asks if you’re creating a control array, answer


"No". Once you have all the controls you need, simply
select them individually and enter the unique properties--
such as the Name property.
 Now, let’s finish our form by adding the last control--a
command button. Name that button cmdExit.

 If you like, add the caption property E&xit. At this


point, double-click the command button to open the
form’s module and add the procedure shown in below.

 Close the window to return to your form.


Code A

Private Sub cmdExitCommand_Click()


    Unload frmDataControl
End Sub

Running the Project


 At this point, you’re ready to run the project so click F5.
The form (in Figure A) displays the first record in the
bound table (from Nwind.mdb).

 Click the navigational controls to move from one record


to another. Remember, if you change the data in a record
and then move to another record, VB will save the
change.
 Try to add a new record by first clicking the Last button
and then clicking the Next button. The first click will
display the last record in the bound table.

 The second click will display a blank record--if you’ve


set the data control’s properties accordingly--as shown in
Figure B.

 If your form doesn’t display a blank record, return to


Design View, select the ADO data control and change
it’s EOFAction property to 2 - adDoAddNew.
 Once you view a blank (new) record, you may encounter
a problem if you try to return to a previous record.

 If your form includes any required fields, VB won’t let


you leave the new record until you enter something in the
required fields.

 This behavior includes primary key fields and any


required fields you may not have displayed on your form.
You can however, exit your form by clicking the Exit
command button.
Properties

 The following is a brief introduction to ADO data control


properties. It isn’t meant to encompass every situation--
especially in the area of cursors and locks.
 The first article in our series, "Creating an ADO Data
Control", introduced you to the ease with which you can
define a recordset using the ADO data control. Before we
continue with that series, you should familiarize yourself with
that control’s many properties, which we've reviewed in Table
A.
 We’ve discussed only those properties that play a part in the
actual data retrieval and management process. (Remember,
we’re not working with the standard data control--we’re
working with the ADO data control.)
Property Description
string that tells ADO how to connect to the data source.
Connec
This string might contain an OLEDB provider, the name of a
tionStri
ng
server, or it might identify just the database you’re
accessing.

A string that identifies the actual data source. This string


Record might be the name of a table. More than likely it will be a
Source SELECT statement identifying only those fields and records
you want to access.

This property specifies the type of information identified by the


Comm RecordSource property. There are four possibilities: adCmdText
(SQL), adCmdTable (table), adCmdStoredProc, and
andTy
adCmdUnknown. The default property setting is adCmdUnknown.
pe Specifying a more specific type improves performance. However, a
mismatch will return an error.
Determines how the control reacts when you try to move past
the last record when the current record is the last record in
EOF
the recordset. The setting adDoMoveLast (the default), keeps
Acti
on
the cursor at the last record; adStayEOF disables the control’s
Next button; adDoAddNew moves past the last record and
displays a blank form so you can enter a new record.

This property is similar to the EOFAction, except that it works


BOF with the first record instead of the last. In other words, if you
Acti click the Previous button while sitting on the first record, the
on adDoMoveFirst will stay at the first record; adStayBOF disables
the Previous button.
ActiveX Data Objects
 ADO is the object-based interface that provides a logical
set of objects you can access from code. These objects
are:
Object Functionality

Connection Manages the connection with the data source

Command Defines the commands that will be executed


against the data source

Recordset Contains the data that is retrieved from the


data source
 These objects present an interface in the form of properties
and methods that can be queried and manipulated.

 ADO was specifically developed to be small, lightweight,


fast, and feature complete – everything you need when you
are programming either for the database applications or the
Internet.

 An important thing in ADO is that the objects in this model


are not dependent on one another.

 This means that you can create instances of objects


independently of one another, for example, you can create
a Recordset object without creating a connection object.
 Unlike the older technologies, ADO is more flexible,
ADO code is easier to write, read and maintain. ADO is
built on top of OLE DB and is capable of accessing any
sort of data that is wrapped and exposed by an
appropriate OLE DB provider.
DISPLAYING DATA WITH A
RECORDSET (USING A
CONNECTION OBJECT)

 Recordset is quite useful in real world applications. If


anything, there are too many ways to do the same thing.
The example below uses an explicit Connection object
and is written to be used in Active Server Pages.
 Set conn = server.createobject(“ADODB.Connection”)
Set objRec = server.createobject(“ADODB.Recordset”)
Conn.open “DSN=myDB;UID=sa;Password=;”
objRec.ActiceConnection = conn
objRec.open “select * from table1”
while not objRec.EOF
            Response.write objRec(“fname”) & “ ”
            Response.write objRec(“Address”)  & “<br>”
            ObjRec.MoveNext
Wend
ObjRec.Close
Conn.Close
Building an ODBC Definition

To build an ODBC steps:definition, you need to call up


the ODBC Administrator. Follow these steps.

1. Choose Start  Settings  Control Panel from the main


Windows 95 (or WinNT4) menu. The Control Panel
appears. Double-click the 32-bit ODBC icon to open
the ODBC administrator.

2. After the ODBC Data Source Administrator dialog box


appears, select the System DSN tab and click ADD.
The Create New Source dialog box appears.
3. Double-click the Microsoft Access 7.0 Database
drives. The OBBC Microsoft Access 97 Setup dialog
box appears. In the Data Source Name field, enter
Database Name. In the description field, enter
Remote Data Connection. In the Database section,
specify the path at Database by clicking Select and
navigating to it in the Select Database dialog box.

4. Click OK to save the definition and then exit the


ODBC administrator applet. You now have an
ODBC data source definition that you can use with
the RDC and the RDOs.

5. Programming with the RDC is very similar to


programming with the standard data control with all
versions of Visual Basic 5.0
Summary

 The ADO data control presents a fast and easy way to


create a bound form by providing built-in functions
that define, navigate, display, add to, and update the
records in a recordset.

 ADO was specifically developed to be small,


lightweight, fast, and feature complete – everything
you need when you are programming either for the
database applications or the Internet
Summary cont…
 An important thing in ADO is that the objects in this
model are not dependent on one another.

 Unlike the older technologies, ADO is more flexible,


ADO code is easier to write, read and maintain. ADO is
built on top of OLE DB and is capable of accessing any
sort of data that is wrapped and exposed by an
appropriate OLE DB provider.

 The three important properties of ADO data control are


connectionstring, recordsource and commandtype
properties.
Exercises:
1. Make ADM's using ADO's .
Visual Basic

LECTURE-20
Topics to be covered

 Creating Reports in VB using Data Environment.


Creating a Report
 
Follow the steps to create a report:
 
1.    Create a DSN through ODBC connectivity.
 
2.    Open up a VB project.
 
3. Click project, Add data environment. A default
connection is added go to the properties and give the
DSN name (eg Biblio) and test the connection. Once
the test succeeded, Add command to the connection,
and go to properties.
  Choose command name,
  Select database object as table
 Choose object name as one of the tables
available with the given DSN eg: publishers.
 Or
SQL statement can be used such as "select *
from publishers".
 
 Click OK.
1.Click, Project, Add data report drag the
command object from data environment and
place on the data report.

2. Set DataSource and Data member properties to


Data Environment name and connection name
respectively.

3.Do setting for headers and columns in the


report and preview.
Summary

 Customised reports can be created in VB using number


of steps in the Data Environment.
Visual Basic

LECTURE-21
Topics to be covered

 ActiveX DLL’s

 ActiveX EXE

 Creating a user control


Object Oriented Programming
with Visual Basic
Activex Components

Classes

The advantages are excellent performance and no


registration issues.
The disadvantages are twofold:
Code is compiled into the application. If you use a

class in many applications, this duplication can be


wasteful.

If you a bug in a class module, you must recompile


every application that uses the class in order to correct
the problem. To distribute the fix, you must distribute
every executable and component that uses the class.

In summary, classes are ideal for object that are specific


to an application and do not need to be reused.
ActiveX DLLs (Code Components)(In
Process)

These are the advantages of DLLs:

 Code can be easily shared among applications.


 DLLs offer excellent performance due to the in-process
nature of the component.
 Fixing a bug in a DLL Implement object only requires
distributing an updated DLL.All applications using the
DDL are immediately fixed.
 DLLs can be used by any OLE automation client,
including all VBA_based applications (such as
Microsoft Office) and other Windows development
languages.
The following are the disadvantages:

 If an updated DLL is incompatible with its


predecessor, you can break every application that
uses the DDL.
 It cannot create new threads of execution.
 It increases the complexity of deploying an
application.
 It requires registration, version checking, and
component verification for safe distribution.
In summary, a DLL is ideal for implementing standard
objects that you might want to reuse or share among
applications. It is also ideal for defining interfaces to be
implemented by order objects. And it is the preferred
way to create high-performance objects that do not have
a user interface.
ActiveX EXE Servers (Out of
Process)

The advantages are the following:

 Objects can execute in their own thread.


 Object can be created and used both by client
applications and by running the server as a
standalone application.
These are the disadvantages:

 Performance is considerably worse than ActiveX DLLs


or classes.
 There is a higher system overhead due to the necessity
of launching a separate task to support the object.
 The complexity of deploying an application is
increased.
 Registration, version checking, and component
verification are required for safe distribution.

In summary, a server is ideal for exposing an


application model to other programs. It is also useful
for implementing objects that can run in the
background (separate threads) asynchronously to your
main application.
ActiveX Controls
There are many advantages to ActiveX controls:
 Good performance. ActiveX controls always run
in process. However, there is additional overhead
involved in using an ActiveX control that does not
occur with an ActiveX DLL server.
 Controls are compatible with many containers,
including Microsoft Office applications and
Internet browsers.
 Controls offer seamless integration into the VB
environment.
 Property pages allow design-time user interface, as
well as runtime inter-face within Visual Basic.
 Controls have the ability to persist design-time
properties in most containers.
These are the disadvantages:

 Controls are considerably faster than ActiveX EXE


servers, but somewhat slower than ActiveX DLL
servers due to the additional overhead required to
support ActiveX controls.
 There is some complexity involved in creating good
quality controls.
 Controls increase the complexity of deploying an
application.
 Registration, version checking, and component
verification are required for safe distribution.
 In summary, controls are ideal for implementing
reusable objects that have a user interface. They are
useful in many cases for improving the modularity
of an application.
ActiveXDocuments (DocObjects)
The following are the advantages of ActiveX documents:

ActiveX documents associate data in a document file with


a user interface object. This allows distribution of
arbitrarily complex data across the Internet and across
intranets.
ActiveX documents may provide an effective way to

distribute software across the Internet. They offer a


potential alternative to VBScript and Java for some
applications.
ActiveX documents makes it easy to convert standalone

Visual Basic applications to applications that run across a


network.
There are two disadvantages:

 Features vary considerably from container to container.

The technology has not received widespread


acceptance. This means documentation and information
resources are limited and raises questions about long-
term support.

In summary, ActiveX documents may be a good way to


create applications that run across the Internet and
intranets.
User Controls
An user control (by default) supports various events which
are as follows :
 The Initialize Event

The Initialize event is the first event received by your control.


During this event, you should:
      Initialize any module-level variables for your control.
   Initialize properties of constituent controls to their default
values.
 During this event, you may:
      Access or initialize the properties of any constituent
controls.
All constituent controls exit at this time.
      
 Initialize variable that are used to hold the control’s
property values to their default value.

During this event, you may not:

 Access the Extender or Ambient properties of the


UserControl object or any of their properties. This is
because while your control object does exist at this
time, it has not yet been placed on the container (or, as
they usually phrase it, the control has not yet been sited
at this time).
 Access property values that were saved previously for
the control. Properties have not yet been read at this
time.
During this event, you should not:

 Rearrange constituent control or perform any operations


that are based on the expected size of the control. No
only has the control not yet been sited, it has not been
resized to its final dimensions.

 Perform any operations that are dependent on features,


attributes, or properties of the container.

  Display anything.
The Terminate Event
 The terminate event is triggered before the object
closes. It is the last event to be triggered for a control
and (with rare exceptions) the last code to run in the
control module.

During this event. You should:


   Make sure that any objects your control is using are
properly released.

During this event, you may:


  Perform any other “cleanup” operations that are
necessary for your control.
    Access the properties of any constituent controls. All
constituent controls still exist at this time.
During this event, you may not:

 Access the Extender or Ambient properties of the


UserControl object or any of their properties. This is
because your control has already been removed from
the container when this event is called. In fact, when
Visual Basic is the container, the form has already been
unloaded by the time this event is called.

During this event, you should not:

  Perform any operations that are dependent on features,


attributes, or properties of the container.
The InitProperties Event
 
The InitProperties event is received by a control instance
only when it is created for the very first time (when drawn
on a form, for example).
During this event, you should:
    Set persisted to their initial values, not to their default
value. Default values are set during the ReadProperties
event. In the case of a standard text box, the default value
for the Text property is he empty string; the initial value
is the name of the control.
 Call any control initialization routines that need to be

performed after a control is created. You may wish to


place this type of initialization in a seprate function,
because you may need to perform the same operations
after the ReadProperties event.
   Set non-persisted properties to their initial values. The
idea of “default” values does not really exist for non-
persisted properties. You may wish to place this code in
a separate routine, because it will typically be called
during the ReadProperties event as well.

During this event, you may:


 
  Perform most of the initialization that depend on the
container. The control is already sited when this event
occurs, thus the Extender and Ambient properties are
valid.
During this event, you should not:

 Display anything. The control will not yet be visible at this


time.

 Perform operations that depend on the size of the control.


The control and container may not yet be at their final size.

  Perform operations that assume that the control window is


actually present on the container. Example of these include
API functions that manipulate windows. The control
window is not actually on the container during this event
(though from the point of view of the object relationships, it
has already been sited).
The ReadProperties Event
 
The ReadProperties event occurs any time a control is
created except for the very first time it is placed on a
form.

During this event, you should:

 Use the PropBag object to read the values of persisted


properties.
 Call any control initialization routines that need to be
performed after a control is created. You may wish to
place this type of initialization in a separate function,
because you may need to perform the same operations
after the InitProperties event.
 Set non-persisted properties to their initial values. The
idea of default values does not really exist for non-
persisted properties. You may wish to place this code in
a separate routine, because it will typically be called
during the InitProperties event as well.
During this event, you may:

 Perform most of the inilizations that depend on the


container. The control is already sited when this event
occurs, thus the Extended and Ambient properties are valid.
 
During this event, you should not:
 
 Display anything. The control will not yet be visible at this

time.
 Perform operations that depend on the size of the control.

 The control and container may not yet be at their final size.
 Perform operations that assume that the control window
is actually present on the container. Examples of these
include API functions that manipulate windows. The
control window is not actually on the container during
this event (though from the point of view of the object
relationships, it has already been said).
The WriteProperties Event
 
 This function is called any time a control is saved to a
project or executable or saved to memory in preparation
for entering run mode. You cannot tell which of these
operation functions automatically channel the data to
the correct place.

During this event, you should:


 Use the PropBag object to save the values of persisted

properties.
During this event, you should not:
 
  Perform any required termination operations. There are

situations when this event will not be triggered.

There are two situations you should be aware of in which


this event is not triggered:
 
 When switching from run mode to design mode in the

VB environment.
 When Visual Basic believes no property values have

changed.
 The decision of when to invoke the WriteProperties
event belongs to the container. Containers that don’t
support a design mode may never call this function.
Example 1 :
Creating ActiveX User Control:

This control will check if the numstring property is number


only number should be entered in the textbox else is
numstring is string only string should be entered.

1. Open an new ActiveX project


2. Draw a text box naming it text1
Coding for the Control
Private mNumString As String

Private Sub Text1_LostFocus()


If mNumString = "number" Then
If Not IsNumeric(Text1) Then
MsgBox ("Only NUMERIC enteries are allowed")
Text1.SetFocus
End If
Else
If IsNumeric(Text1) Then
MsgBox ("Only CHARACTERS enteries are allowed")
Text1.SetFocus
End If
End If
End Sub
Private Sub UserControl_InitProperties()

MyCaption = Extender.Name
NumString = "number“

End Sub

Private Sub UserControl_ReadProperties(PropBag As PropertyBag)

MyCaption = PropBag.ReadProperty("mycaption",
Extender.Name)
NumString = PropBag.ReadProperty("NumString", "number")

End Sub
Private Sub UserControl_Resize()
Text1.Move 0, 0, ScaleWidth, ScaleHeight
End Sub

Public Property Get MyCaption() As Variant


MyCaption = Text1.Text
End Property

Public Property Let MyCaption(ByVal NewValue As


Variant)
Text1.Text = NewValue
End Property
Private Sub UserControl_WriteProperties(PropBag As
PropertyBag)

PropBag.WriteProperty "mycaption", MyCaption,


Extender.Name
PropBag.WriteProperty "NumString", NumString, "number“

End Sub
 
Public Property Get NumString() As String
NumString = mNumString
End Property

Public Property Let NumString(ByVal NewValue As String)


mNumString = NewValue
End Property
The project properties has following details
Select the Make ocx option from the file menu:
Using the control

Open a standard exe project and from project components select the ocx created by you.
Use the control on the form and set numstring to string as shown below :
Try writing the number it will display the message as set by
you.
Control Classes
Now that you appreciate what's going on behind the
scenes when form objects are created, you can move on to
considering the object-oriented nature of controls-or, to
give them a more accurate title, control classes.

Although controls are classes, they differ from forms and


the other classes in Visual Basic in two important ways.

They cannot exist on their own. They have to be


contained within a form. In fact, a form class is known as
a container for the control classes that appear on it.
Therefore, when you delete a form class from your
project, all the control classes that are contained within it
are deleted, too.
Whereas forms and other classes are implemented
within Visual Basic itself, controls can be implemented
outside, as separate programs that conform to the
ActiveX Control Extension (OCX) standard.
Through the OCX standard, third-party suppliers can
produce their own specialist controls. (We'll call these
controls OCX controls from now on.)
This is an important way in which Visual Basic’s

functionality can be extended.


If you want to add some special functionality to your

project, it is likely that someone has already written an


OCX that does what you need.
If they haven't, you can write your own. OCXs couldn't be

written in VB4 and had to be implemented in C++.


One of the important improvements in Visual Basic is the

ability to create your own OCXs in Visual Basic.


Introducing User-Defined
Classes
User-defined classes are really the key to making the
most of Visual Basic’s object-oriented features. Without
them, your project cannot be considered fully object-
oriented.

Although you've been using classes for some time


now, the classes that you have been using to date have
been limited in two important respects.
They have been written by someone else. You have
been reusing them rather than creating your own. The
reusability of classes is an important feature of object-
oriented programming and, of course, you have been
able to customize the behavior of these classes by
setting their properties, calling their methods, and
programming their events. So far, however, you have
been unable to develop your own classes from scratch.

They have been mainly concerned with the user


interface of your project. The single-instance classes are
used for accessing operating system services such as the
clipboard, but if you consider the two main type of class
that you have used so far (forms and controls), it should
be clear that they address only the user interface of your
projects.
Why You Might Implement Your
Own Classes

It is important that you understand why there should be


a need for you to implement your own classes. The
problem is that your project's user interface may
account for only a fraction of the code that you have to
write.
What Does a Class Module
Contain?

A class module can contain three things:

Subroutines and functions that you add to its General


Declarations section: These become the methods of the
class.

Properties that you add to the class module: These are the
variables that the class will manipulate. Some of the
properties are declared as Public, accessible from any part
of the supporting program, and some are private,
accessible only from within the class.
 Events that you add to the class module

 Events are different from methods.

 Events are procedures that are called from within


the class and have an effect on objects outside the
class object.

 They are outgoing interfaces.

 Methods are procedures that are called from outside


the class module and have an effect on the class
object. They are incoming interfaces.
User-Defined Properties
It is possible to add your own properties to classes. Why
you might want to do this?

The Benefits Of Properties


To see how a user-definable property might work, let's have
a closer look at some of the properties built into the form
class and see how they differ from ordinary class variables.

Take the Top, Left, Width and Height properties, for


example. When the values of those properties are changed,
the size or position of the form changes accordingly.
The form's caption property also does something
spectacular. When you assign some text to it, that text
magically appears in the title bar of the form.

There is no magic connection between the caption


property of a Visual Basic from and the title bar of a
window.

Instead, the property is able to recognize and respond


to changes in its value.

This ability sets properties apart from mere class


variables. It's as if they have a built-in event that gets
triggered when the property is set to something.
 This is important because the code that you write in an
object-oriented program can be simplified somewhat if
the properties of a class can react when they are accessed
by code in other parts of the program.
Summary
 A DLL is ideal for implementing standard objects that
you might want to reuse or share among applications.
 It is also ideal for defining interfaces to be
implemented by order objects.
 It is the preferred way to create high-performance
objects that do not have a user interface.
 An ActiveX EXE server is ideal for exposing an
application model to other programs. It is also useful
for implementing objects that can run in the
background (separate threads) asynchronously to your
main application.
Summary cont…
 ActiveX controls are ideal for implementing reusable
objects that have a user interface.
 They are useful in many cases for improving the
modularity of an application.
 User can create his own controls in VB.
 Whereas forms and other classes are implemented
within Visual Basic itself, controls can be implemented
outside, as separate programs that conform to the
ActiveX Control Extension (OCX) standard.
 One of the important improvements in Visual Basic is
the ability to create your own OCXs in Visual Basic.

You might also like