Learning Visual Basic & Oracle
Learning Visual Basic & Oracle
Visual Basic
&
Oracle
VISUAL BASIC
Topics to be covered
Introduction to OOPs
Features of VB
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
trigger procedures
converts it to a number
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…
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:
Their Scope
Their Datatypes
Basic Controls in VB
Property Changes…
Name
d use it in a program TextBox Name
Text By default text1 and value that is
written in textbox
Property Changes…
Name
d use it in a program Label Name
Caption By default label1 and value that is
displayed on screen.
Properties Purpose
Default Boolean value if true sets that button to
be default on form.
Enter text
Exit
Code
Clear Button
Text1.text=“”
Date Button
Text1.text=date
Exit button
Unload me
Summary
Result
Text2
Number 2
Text3
Result
Exit
Visual Basic
Topics to be covered
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?
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
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
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
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()
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
Syntax
DateDiff(interval, date1, date2)
6. DatePart Function
Returns a Variant (Integer) containing the specified part
of a given date.
Syntax
DatePart(interval, date)
Q Quarter
M Month
Y Day of year
D Day
W Weekday
Ww Week
H Hour
N Minute
S Second
e.g.
vbNormal 0 Normal
vbHidden 2 Hidden
to a power.
Syntax
Exp(number)
10. Format Function
Syntax
Format(expression[, format[, firstdayofweek[,
firstweekofyear]]])
expression valid expression.
format(Optional) A valid named or user-defined format
expression.
Syntax
Hour(time)
The required time argument is any Variant, numeric
is an array.
Syntax
IsArray(varname)
e.g.
been initialized.
Syntax
IsEmpty(expression)
Syntax
IsNull(expression)
The required expression argument is a Variant
containing a numeric expression or string
expression.
e.g.
Syntax
IsNumeric(expression)
Syntax
Ltrim(string)
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
Syntax
Rtrim(string)
e.g.
dim a as string, b as string
b=”hello “
a=rtrim(a) will return “hello”
22. Trim Function
Syntax
trim(string)
e.g.
dim a as string, b as string
b=” hello “
a=trim(a) will return “hello”
23. Val Function
Syntax
Val(string)
Syntax
Weekday(date)
e.g.
Dim MyDate, MyWeekDay
MyDate = #February 12, 1969# ' Assign a date.
MyWeekDay = Weekday(MyDate)
Second(time)
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
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
Syntax
Time()
e.g.
Dim MyTime
MyTime = Time ' Return current system time.
31. MsgBox Function
Syntax
MsgBox(prompt[, buttons] [, title] [, helpfile,
context])
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
VbCancel 2 Cancel
VbAbort 3 Abort
VbRetry 4 Retry
VbIgnore 5 Ignore
VbYes 6 Yes
VbNo 7 No
32. Inputbox Function
Syntax
InputBox(prompt[, title] [, default] [, xpos] [,
ypos])
Where
Prompt(Required) String expression displayed as the
Text2
Text3 Compute
Code Modules
User-defined Procedures
User-defined Functions
Modules
A module is collection of procedures, functions and event
Debugging is easy
Form Modules
Form modules (.FRM file name extension) are the
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
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
Pass by value
intA is unchanged.
project)
Class modules(related to classes. Used to create
objects)
LECTURE-7
Topics to be covered
VB controls:
Frames
Option Buttons
Checkboxes
Timer control
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
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
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
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
End Sub
Summary
Option Buttons allow the user to choose any one option
out of a group of buttons.
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…
Order Type
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.
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
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
Method Description
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
Move Move a control. The Syntax object. Move left, top, width,
height
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
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
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"
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
Picture1.Picture=LoadPicture("c:\Windows\Winlog.bmp")
LECTURE-9
Topics to be covered
VB controls
ListBoxes
Comboboxes
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
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)
Dim c As Short
txtChosen.Text = ""
For c = 0 To lstSports.SelCount - 1
txtChosen.Text = txtChosen.Text & " " & _
lstSports.Selected (c) & " "
Next c
End Sub
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
object.RemoveItem index
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
Design–time properties:
•The ComboBox DropDownStyle property is
changed to DropdownList.
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.
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.
File
Names
List1
Read only
Hidden System
Status bar
Exercises cont…
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
CommonDialog1.FontSize = 12
code statements use the new property values to
•Color Dialog.
•Font Dialog.
•Open Dialog.
•Save Dialog
The ColorDialog control
picHoliday.Image Image.FromFile(dlgOpenFile.FileName)
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
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.
•Also, place an ampersand (&) before the letter you want to be the
access key for that menu item.
•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.
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.
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.
Loading a file:
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.
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
Object.SelFontSize = Integer
RichTextBox1.SelFontSize = 12
'The following text will be size 12
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
'RichTextBox1 display:
'Hello
RichTextBox1.SelAlignment = 2
'RichTextBox1 now display:
' Hello
Colors, bullets & superscript
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
Object.SelCharOffSet property
SuperScript:
Dim VariableName As Integer
Object.SelFontSize = Integer / 3 * 2
Object.SelCharOffSet = Temp * 5
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
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:
Eg.
Dim x as string
x = “Visual basic”
text1.sellength = len(x)
Summary
LECTURE-13
Topics to be covered
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.
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.
Method 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.
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:
•Cascade
•Tile horizontal
•Tile vertical.
Windows
Arrange
Vertical
Horizontal
Visual Basic
LECTURE-14
Topics to be covered
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
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.
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.
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
LECTURE-15
Topics to be covered
•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.
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.
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
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
(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;
SELECT CARS.Make,
CARS.Model,
EMPLOYEES.FirstName
EMPLOYEES.LastName
FROM CARS INNER JOIN EMPLOYEES
ON CARS.CarNo = EMPLOYEES.CarNo
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
UNION
• Tables
• Forms
• Queries
• Reports
Summary cont…
LECTURE-16
Topics to be covered
•Types of relationships
Single table databases
Assume:
1000 employees and 1Kbyte of data each.
100,000 sales and 2Kbytes each.
•Stock No.
•Purchase date
•Purchase price
•Sale date
•Sale price
•Colour
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.
• one to many
• one to one
• many to many
• none
One to many
5 + 4 + 3 + 2 + 1 = 15
Modelling relationships
The relationships between tables is achieved
by using:
• 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
Generally these are a bad idea and slow down the database.
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
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
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
LECTURE-17
Topics to be covered
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.
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
what data table you want to use with the data control.
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.
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.
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.
Refresh
UpdateControls
UpdateRecord
Refresh method is used any time you change any of the
properties of the data control.
to data record.
Using the UpdateRecord method updates the Dynaset
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
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
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
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.
As a rule, you will use one data control for each database
table that you need to manipulate.
Validate
Error
Summary cont…
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.
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
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.
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
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
Desgcd Text 3
Desgnm Text 25
Indexes:
Index Name Field Type
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 )
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
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
LECTURE-19
Topics to be covered
CommandTyp
1 - adCmdText
e
EOFAction 2 - adDoAddNew
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.
txtCompanyName CompanyName
txtAddress Address
txtCity City
txtRegion Region
txtZip PostalCode
txtCountry Country
Quick Tip
LECTURE-20
Topics to be covered
LECTURE-21
Topics to be covered
ActiveX DLL’s
ActiveX EXE
Classes
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.
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.
properties.
During this event, you should not:
Perform any required termination operations. There are
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:
MyCaption = Extender.Name
NumString = "number“
End Sub
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
End Sub
Public Property Get NumString() As String
NumString = mNumString
End Property
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.
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