Вы находитесь на странице: 1из 49

By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 1

Q1: What is Visual Basic, and what are the major components
of visual basic IDE.

Visual Basic
Visual basic is a Microsoft tool, which is used to create windows
based applications.
For example Notepad, Calculator, Window media player, Internet
Explorer etc
Visual basic is both a tool and a language. The tool is the Visual Basic
Integrated Development Environment. It provides facilities for writing,
debugging and running programs in one environment. It is used to
develop GUI (Graphical User Interface) of the program. The language is
used to write the code that execute behind the GUI of the program.

Components of Visual Basic IDE


The major components of visual basic IDE are
1) Form Window 2) Properties Window
3) Project Explorer Window 4) Toolbox 5) Form
Layout Window
1) Form Window
The most important component of Visual Basic IDE is the
form window. The GUI of the Visual Basic program is created and
displayed on this form. The user provides input through various
controls on this form and the output is also displayed on the form. It is
also called container control.

2) Properties Window
The characteristics of any thing are called property. In
Visual Basic each control has a unique set of properties. Some
properties are common to all the controls such as Height, width, name,
caption etc, while other properties are unique to each control. When a
control is selected, its respective properties are displayed in the
properties window.

3) Project Explorer Window


Project explorer window displays forms, modules, classes
etc used in the project. This window is used to bring a particular
component of the project into focus.

4) Toolbox
Toolbox contains controls that are used on the form
window to develop an application. Toolbox contains most of the tools
are usually used in application programs. However new controls can
also be added.

5) Form Layout Window


By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 2

Form layout window is used to specify the position of the


form on the computer screen when the program is executed.
Q2: Discuss the different features of object in visual basic.
In visual basic each object support three features. These are
properties, method and events.

(A) Object Properties


The characteristics of an object are called its properties. It
specifies the appearance and behavior of an object.

(a) Types of Properties/ Property Value


Each visual basic object has several types of properties. Some of
these are
1) Boolean Values
The property that has either True or False value is called
Boolean type of property. e.g. Enable, Visible etc
2) Predefined Values
An object can have a list of predefined values. These
values are given in a drop down list. e.g. BoderStyle property has 6
predefined values.
3) String Values
The properties in which the text is specified by the user.
For example Name and caption properties of an object.
4) File Name Values
The property through which we can load a file from the
hard disk is called filename property. For example Icon, Picture etc
5) Size Value
Left, Top, Height, Width are called the size values. These
properties specify the size and location of an object. These values
are given in twips.
6) Hexadecimal Values
The values of color property are specified in hexadecimal
code, instead of entering the hexadecimal color code, the required
color can be selected.

(b) Some Common Object Properties


The common properties of an object in VB are
1) Name
This property specifies the name of object. This name is
used by VB to refer to the object in the code.
2) Caption
The text that is displayed as a title on the object is called
its caption. It is used to identify the object on the form. For example
if the button is used to close the program then its caption is
specified as End.
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 3

3) Enable
It is a Boolean property that is either True or False. This
property specifies the functionality of object on the form during run
time.
4) Visible
This property specifies that whether an object is to be seen
on the form or not. This property can be either true or false.
5) Left and Top
These properties specify the distance of the object from
the upper left corner of the window. It is measured in twips. One
twip is equal to 1/20th of the point. In one inch there are 72 points.
So 1 inch = 1440 twips.
6) Height and Width
These properties specify the size of the object. It is
measured in twips.
7) BackColor
This property is used to identify the background color of
the object. The color setting is defined in hexadecimal code. Since it
is difficult to remember the code, therefore VB IDE provides the
color palette to select a color.
8) ForeColor
This property is used to specify the foreground color of the
object. The foreground color is the color of the text that is displayed
on the object.
9) Appearance
This property is used to specify the look of the object on
the computer screen. It has two pre-defined values.
0- Flat Look (Specifies Flat Look)
1-3D Look (Specifies 3D Look)
10) Font
The format, style, type of the text is specified in this property.

(B) Object Method


Object methods are the built in functions that are attached
with the object that operates on the data of the object.
Its syntax is
Object. Method
For example
Form1.cls

(C) Object Events


The interaction of user generates a message in the
computer, which is called an event. The user can interact with the
object in several different ways. For example if text box is placed on
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 4

the form then user can click, double click, enter text in the text box. All
these events are associated with the specified object that is text box.
(i) Events Triggered By Mouse
The most common events that are triggered with mouse are
1) Click, Db Click
The click event takes place when the user presses the left
mouse button. The double click event takes place when the user
presses the left mouse button twice in quick succession.

2) Mouse Down Event


The mouse down event occurs when any mouse button is
pressed.
3) Mouse Up Event
The mouse up event occurs when any mouse button is released.
4) Mouse Move Event
This event occurs when the mouse pointer is moved to a new
point.

(ii) Events Triggered By Keyboard


The event triggered by pressing a key on the keyboard is called
keyboard event. The most common are

1) KeyDown
This event occurs when the key is pressed on the keyboard.
2) KeyUp
The keyup event occurs when a key is released.
3) KeyPress
Keypress event take place when the key is pressed. Keypress
differs from keydown because keypress cannot detect Shift, Alt, Ctrl
keys.

Changing Object Properties at Run Time


Properties of an object can also be changed during run time with
the following syntax.
ObjectName.PropertyName = Value
For Example
Form1.Caption = “NotePad”
Form1.Visible = True
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 5

Q3: Discuss Form in VB; also discuss its properties, methods and
events.

Form
Form is the most important object of GUI. The GUI application is
created on this object through placing different controls on it and result
can also be displayed on this form.

(i) Properties of Form


Some commonly used properties of an object are.
1) Form Caption
The title of the form that appears on the top of the form is
called it Caption. By default the caption of first form is Form1, the
user can change it according to his/her requirement.
2) Form Name
Each form has a unique name. This name is used in the code.
3) Border Style
The appearance of the border of the form is called border
style. This property specifies that whether or not a form can be
maximized, resized etc.
4) Control Box
This property specifies that whether the control box appears
or not. It is a Boolean property; if true is selected then control box
appears otherwise not.
5) BackColor
The backcolor property specifies the background color of the
form.
6) ForeColor
This property specifies the foreground color of the form. The
foreground color is the color of the text that are displayed on the
form.
7) ShowInTaskBar
This property specifies whether or not the form is to be
displayed on the form or not. It has two values True or False. if True
form is displayed as a icon on the taskbar otherwise not.
8) Icon
This property is used to specify a picture for the icon. When
the executable file is created, this picture is assigned to it as its
icon.
9) Window State
The size of the form at run time is called its caption. A form
window can have three states. These are
0 – vbNormal – Form appears in Normal size
1- VbMinimized- Form appears as an icon on the taskbar
2- VbMaximized-Form covers the entire computer screen.
10) StartUp Position
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 6

This property specifies the position of the form when it first


appears during run time.

11) Font
The type, style, size of the text that appears on the form is
specified in this property.

(ii) Form Method


The most commonly used methods of form are
1) Hide Method
This method is used to hide the form from the screen. When
the form is hidden, it remains in computer memory
Syntax
FormName.Hide
2) Show Method
This method is used to show a form that has been hidden by
the hide method.
Syntax
FormName.Show
3) Unload Method
This method is used to close the form. When the form is
closed then it is removed from computer memory. Removing the
form from the computer memory is called unloading of the form.
Syntax
FormName.Unload
Or Unload Me

(iii) Form Events


The most commonly used from events are
1) Initialize Event
This event occurs when the form is being configured before it is
loaded.
2) Load Event
This event occurs when the form is loaded into the memory from
the disk. It is called after the form has been initialized and before
the from is displayed on the computer screen.
3) Activate Event
This event occurs when the form has been loaded from the
computer memory and it becomes the active form.
4) Deactivate Event
It is opposite to activate event. This event occurs when the form
ceases to be the current form.
5) Unload Event
It is opposite to load event. This event occurs when the
application is closed. When the application is closed, form is removed
from the computer memory.
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 7

6) Resize Event
Resize event occur when the size of the form is changed.

Q4: What is Multiple Document Interface (MDI) form? Discuss


its design and run time features.

Multiple Document Interface


An application in which other form can be opened within one
container form is called the MDI. Word, Excel are the examples of MDI
form.
In MDI, the container form is called the parent form and the other
forms are called the child form. An application can have only one
parent form.

Design Time Features of MDI Child Forms


At design time the child form are not displayed to the area inside
the parent form. Whether or not the MDI Child property of the child
forms is set to true or not.

Run Time Features of MDI Child Forms


1) At run time all child forms are displayed within the parent form.
2) When the child form is minimized, its icon appears on the
MDI parent form instead of users desktop.
3) When the child form is maximized, its caption is combined
with the parent form caption, and is displayed on the title bar of
the parent form.
4) By setting the AutoShownChildren property to true, the
child forms are displayed automatically when they are loaded. By
setting this property False, the child forms are loaded as hidden.
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 8

Q5: Discuss Command Button, Label and Timer control. Also


discuss their properties, methods and events.

Command Button
Command button is the most important control of GUI. It is
used to execute an action, when it is clicked.

Label Control
A label box control is used to display information for
various controls on the form.

Properties
1) AutoSize This property can be either True or False
If True, the label is resized to fit the text specified in the caption
property.
If False, the size of the label remains fixed as defined at design time.

2) Caption It specifies the text to be displayed in label box.

Events
1) Click This event is triggered when the user clicks on the
label
2) DbClick This event is triggered when the user double clicks
on the label

Timer Control
The timer control is used to generate an event at regular
interval. The event generated is called the timer event.
The timer event is used to move graphics or to change the color at
regular at regular interval. Application program also used this event to
save document files at regular interval.

Properties
1) (1) Interval Interval property specifies the interval between each
timer event. It is measured in milliseconds. Thus 1000 intervals are
equal to 1 second.
2) Enabled This property switches the timer On or OFF

Timer Event Timer event occur after a specified interval of time.


By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 9

Q6: Discuss Textbox, Checkbox and Option button with their


properties, methods and events.

Text Box
The text box control is used to get and display information on the
form. The information in the text box can be entered at design time.
The user can enter the text at run time through the code. It is the most
commonly used control of the window user interface.

Properties
1) MaxLength
MaxLength property specifies the maximum number of character
to be displayed in the text box. The 0 value indicate unlimited length.
2) Multiline
Multiline property specifies whether the textbox displays single
line or multi line. The True value specifies multi line and False value
specifies single line.
3) PasswordChar
It specifies the character that is displayed in place of characters
that are entered in the text box. Usually a * is used to get password
from the user in this property.
4) ScrollBars
It specfies the display of scrollbars. This property works in
conjunction with multi line property. The scrollbars are displayed when
the MultiLine property is set to True
5) SelLength
This property returns the length of the selected text in the text
box. It is used during run time only.
6) SelStart
It returns the starting position of the selected text in the text
box. It is also used during run time only.
7) SelText
It returns the selected text in the text box. It is also used during
run time only.
8) Text
It set or returns the text in the text box.
9) Locked
If this property is set to True then the text in the text box
becomes read only

Events
1) Change
This event occurs every time the Text Property in the
text box changes.
2) KeyPress
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 10

This event occurs whenever a key is pressed. It is used to


find out the key is pressed on the keyboard.

Methods
1) SetFocus
This method places the cursor in the specified text box.

CheckBox
Check boxes are used when one or more options are
selected from a list of given options. An option is selected by clicking
on the check box. When an option is selected, a tick mark appears in
the text box, which indicates that the option is selected.
When an already selected checkbox is again clicked, then the tick
mark disappears which is also called deselecting.

Properties
1) Caption
It specifies the text that appears next to the checkbox
2) Value
It indicates the state of check box. Three states are possible,
unchecked return 0, checked return 1 and grayed out state return 2.
Events
1) Click
This event occurs when the check box is clicked. When the
checkbox is clicked, then its value property is automatically changed
by the visual basic.

Option Button
Option Buttons are also called radio buttons. Option
buttons are used when only one option is to be selected from a list of
given options. These options are such that if one option is selected,
other option cannot be selected; these options are therefore mutually
exclusive.

Properties
(1) Caption
It specifies the text that appears next to the option button.
(2) Value
It indicates the state of option button. If the button is selected
then it has True value otherwise False value.
Events
(1) Click
This event occurs when the option button is clicked. When the
option button is clicked, then its value property is automatically
changed by the visual basic.
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 11

Q7: Discuss List Box and Combo box control with their
properties, methods and events.

List Box Control


A list box displays a list of items from which a user can select
one or more items. This control occupies the specified space on the
form. If the number of items exceeds the number that can be displayed
in the specified space, then a scrollbar is automatically added with the
list box.
List box control is normally used, when there is a large number
of options and the user is required to select any one of them.

Properties
1) List
This property adds a list of items at design time in the list box.
The following procedure is adopted to add items in the list box at
design time.
• Select the List property and click the arrow at the right and an empty
box will appear.
• Type the items that is to be added and press Ctrl+Enter to type the
next item.
• To complete the entry and to close the list property box
press Enter key and the entered items will be added to the
list box.
2) MultiSelect
This property specifies how items may be selected. Any one of
three values may be selected.
0- No Multiple selection allowed
1- Multiple selection allowed
2- Group selection allowed
3) Sorted
This property is used to display the items sorted in
ascending order if the property is set to True otherwise items appear
in the order in which they are inserted.
4) Style
This property is used to specify the manner in which the items
are displayed and selected in the list box.
The list items can be displayed either as normal text or a check box
is placed before each item.
(5) List Count
This property returns the total number of items in a list. It can be
used during run time only.
(6) List Index
This property specifies or returns the index value of the most
recently selected item in the list box. If no item is selected then the
ListIndex = -1 will be returned. It is also used during run time only.
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 12

(7) Text
This property is used to return the text of the most recently
selected item. It can be used during run time only.
(8) Index
This property returns the index value of the item most recently
added item in the list box. It can be used during run time only.

List Box Methods


1) AddItem
This property is used to add items to the list box at run time. Its
syntax is
List1. AddItem “ItemName”
(2) Clear
This method is used to remove all items from the list box. Its
syntax is
List1. Clear
(3) RemoveItem
This method is used to remove an item from the list box. The
item to be removed is specified by the index of that item. Its syntax is
List1. RemoveItem (List1. ListIndex)

List Box Methods


Click
This event occurs when an item in the list box is
clicked
DbClcik
This event occurs when an item in the list box is
double clicked.

Combo Box Control


Combo box control is similar to list box control but it takes
less space on the form than the list box. It consist of a text box and a
drop down list box, from which user can select an item. It is used to
display a list of Items.

Combo Box Properties


Combo box properties are almost identical to list box, however
combo box does not have the multi select property and its style
property is different.
Style
0- VBComboDropDown
1- VbComboSimple
2- VBComboDropDownList

Combo Box Methods


The methods of combo box and list box are same.
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 13

Q8: What are File Controls?


File controls are used to locate files on the disk. VB has three
Basic ActiveX controls to locate files from the disks. These are
DriveList, DirectoryList and FileList control. These controls are
used together to access files on the disk.

1) DriveList Box Control


The DriveList box control is used to get disk drives installed on
the computer. It displays all available drives in a drop down combo
box. No code is needed to load a drive list box.
Properties
DriveThis Property contains the name of the currently selected drive.

Events
Change This event occurs whenever the drive selection is changed.

2) DirList Box Control


The DirList Box control displays an ordered and hierarchical list of
the directories and subdirectories on the disk. The directory structure
is displayed in a list box. Like the drive list box, no code is needed to
use the directory list box.
Properties
Path This property specifies the current directory path selected by the
user.

Events
Change This event occurs whenever the directory selection is
changed.

3) FileList Box Control


This control displays list of filenames of the selected folder. This
control looks like a list box.

FileList Box Properties


1) FileName This property contain the currently selected filename
2) Path This Property contains the current path directory.
3) Pattern This property contains a string that determines which
files will be displayed. It support the use of wildcard characters (*
and ?). For example, using *.dat displays all files with the .dat
extension.

FileList Box Events


1) PathChange occurs when the path in the file list box
changes
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 14

2) Click occurs whenever a filename is clicked


3) DbClick occurs whenever a filename is double clicked.

Q9: Discuss Scroll bar and frame controls with their properties,
methods and events.

Scroll Bar Control


The scroll bar is a graphical way of selecting a value between
two ends of the control. It is a long strip with an indicator through
which a user can select a value. VB has two scroll bar controls,
Horizontal and vertical. The function of these is similar but only the
orientation is different.
Scroll Bar Properties
1) LargeChange
Return or sets the amount of change in the value property of the
scroll bar, when the scroll bar area is clicked.
2) Max
It specifies the maximum value of the scroll bar. The value of the
horizontal scroll bar at the right most position and the value of the
vertical scroll bar at the bottom is specified. The value can range from
-32768 to 32767. The default value is 32767.
3) Min
It specifies the minimum value of the scroll bar. The value of the
horizontal scroll bar at the leftmost position and the value of the
vertical scroll bar at the top is specified. The value can range from
-32768 to 32767. The default value is 0.
4) SmallChange
The SmallChange specifies the movement of the scroll box
when either of the scroll arrows is clicked.
5) Value
This property is used to set or return the value of the current
position of the scroll box.

Scroll Bar Events


1) Change
Change event occurs when the position of the scroll box is changed.
2) Scroll
Scroll event occurs continuously whenever the scroll box is being
moved.

Frames
Frames are used for grouping related controls on the form.
Since a frame is used to contain other control on the form, therefore it
is also called container control.
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 15

To group controls in the frame, the frame is drawn on the form,


then the controls are drawn in the frame. When controls are drawn in
the frame, then the frame and the control are moved together.

Frame Property
(1) Caption It specifies the title of the frame that is displayed at its top.

Q10: Discuss Message Box and Input Box with example.

Message Box
The Message Box is used to provide information to the user. It
is usually used to display error messages or to provide information to
the user.

Syntax
Msgbox “Message”,VbButtons + Icon, “Title”

Example
Msgbox “Are You Sure You Want To Exit”,VbYesNo +
VbInformation,”Exit Application”

Input Dialog Box


The input dialog box is used to receive input from the user during
execution of program. The inputBox() function is used to display this
dialog box.

Syntax
Variable = InputBox (“Prompt”, Title, “Default” )
Example
Var = InputBox ("Enter Number", "Enter Values", "Here Type
Numeric Values")

Example Using Input Box and Message Box

Develop a project in VB to input two values using input


box add then and display the result in Message box.

1. Start a new Project.Exe


2. Place one command button on the form.
3. Attach the following code to the Click event of Command1
Private Sub Command1_Click ( )
Dim a, b, c as Integer
a = InputBox (“Enter 1st Value”, “1st Number”)
b = InputBox (“Enter 2nd Value”, “2nd Number”)
c = Val(a) + Val(b)
MsgBox "Sum of" & a & "and" & b & "=" & c
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 16

4. Run the project

Q11: What is Error, what are the types of Error and what are
Error Handling Techniques.

Error or Bug
Whenever a problem, error occur in a system, or when
application does not produce correct or required result or when
application halts unexpectedly or when application converts into
infinite loop is called bug

Types of Error
There are three main types of errors.
1) Syntax Error
Error in the syntax of the program is called syntax error. For
example
Far I= 1 To 10
In the above example the word “Far” in used instead of word “For”.

2) Run Time Error


Run time error arises when an attempt is made to run an invalid
operation. For example
Dim a as integer
a = 40000

3) Logical Error
Error in the logic of the program is called logical error. For
example instead of using the “*” operator programmer use “+”
operator, which causes an incorrect result.

Error Handling
Error handling is a process to recover and remove errors
from a program. In VB two statements are used for error handling.
These are
1) On Error Goto Statement
2) On Error Resume Next

1) On Error Goto Statement


This statement transfers the control to a specified label,
when an error is recovered.
Syntax
On Error Goto Label
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 17

__________
Label:
Error Handling Code

Example
Private Sub Command1_Click ( )
On Error Goto abc
Dim a, b, c as integer
a = 10
b=0
c = a/b
Print c
Print “Above is Output”
abc:
Print” Division by Zero Error”
End Sub
Output
Division by Zero Error

2) On Error Resume Next Statement


In this statement, if an error is recovered, then the execution of
that statement is resumed and the execution of other statements is
continues.
Syntax
On Error Resume Next
Example
Private Sub Command1_Click ( )
On Error Goto abc
Dim a, b, c as integer
a = 10
b=0
c = a/b
Print c
Print “Error in Program”
Output
Error in Program
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 18

Q12: Discuss Web browser, Internet Explorer controls


The WebBrowser Control
The WebBrowser Control is used to develop Web Browser to
access the web page web pages on word wide web, local files such as
word or excel documents with in the VB application.

Methods
The commonly use methods are:
1) Navigate Method

It is used to display the Web page into the Web Browser control.
Syntax
Object.Navigate URL

2) GOBack Method
The WebBrowser control and the Internet Object automatically
maintain the list of visited URLs. This list is called the history. This
method is used to display one previous item in the history list of the
URLs that have already have been displayed.
Syntax
Object.Goback

3) GoForward Method

This method is used to display the next page in the history list of
URLs that have already been accessed. It works opposite to the
GoBack method. This method is available only if the GoBack Method
has been used to display a previous page
Syntax
Obect.GoForward

4) GoHome Method

This method is used to display to thecurrent Home Page.


Syntax
Object.GoHome

5) Refresh Method

This method is used to reload the page that is currently being


displayed on the WebBrowser control.
Syntax
Object.Refresh

6) Stop Method
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 19

This method is used to stop or cancel the downloading process of


the current page into the webBroser control. Its syntax is
Object.Stop

WebBrowser Properties
The commonly used properties of the WebBrowser control are:
1) Busy Property

This property returns a value whether the WebBrowser Control is


downloading the Web page or not

2) LocationName Property

This property is used to return the title of the web page that is
displayed on the WebBrowser control.

3) LocationURL Property

This property is used to return the URL address of the Web Page
that is displayed on the WebBrowser control.

WebBrowser Events:
The commonly used events of the WebBrowser are
1) DownloadBegin Event

This event occurs at the beginning of the download process.If the


WebBrowser Control name is WebBrowser1, The DownloadBegin
event is declared as:
Private Sub WebBrowser1_Downloadbegin ()
- -------
End Sub

2) DownloadComplete Event:

This event occurs when the download process is completed or it


halts or it fails. Suppose the WebBrowser control name is
WebBrowser1, The downloadcomplete event is declared as
Private Sub WebBrowser1_DownComplete ()
- ------
End Sub

3) ProgressChange Event

This event periodically occurs during the download operation to


show the Progress of the download operation to show the progress
of the download operation .It declaration is:
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 20

Private Sub WebBrowser1_ProgressChange (ByVal Progress as long,


Byval PrograssMax as Long)
---- --
End sub

4) TitleChange Event

This event occurs when the title of the current document or page
changes. When a
Page begins to download; The WebBrowser also returns its title.
After the title of the new document is displayed, the title change
event is triggered .This event is normally used to change the
caption of the form
Private Sub WebBrowser1_TitleChange (ByVal text as string)
End sub

(5) NewWindow Event


This event occurs when a new window is opened to display a new
page

Internet Explorer
The Visual Basic also has Internet Explorer Object that supports
the same methods, properties and events as the WebBrowser Control.
But it also has some extra methods, properties, and events. The
instance or variable of Internet Explorer type is created in programs
codes and its methods and properties are used to build the Browser
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 21

Data and Data Types


The values used in a program are called data. There are three
different types of data in VB. These are numeric data type, string data
type and special data type.
Numeric type data consist of numbers. e.g. 7, 22, -33 etc
String type data consist of text. e.g. Imran, vb, college etc
Special type of data consist of variant type, user defined data.

Q13: What are Variables. How variables are declared, what is


the scope of variables and what are the types of variables.
Variables are the holder of data. A quantity that might be change
during the execution of program is called variable. The value of
variable may be a numeric or non-numeric quantity.
A variable name is made up of one or more alphabet and is
written according to the following rules.
(a) A variable name may be the combination of letters, numbers
and underscore.
(b) The first character must be an alphabet.
(c) Blank spaces are not allowed in a variable name.
(d) The uppercase and lowercase alphabet may be used in a
variable name.
(e) Visual basic reserve words cannot be used as variable name.
(f) Maximum length for a variable is 255 characters.

Declaration of Variables
Specifying the name and data type is known as the declaring of
variable.
When a variable is declared, a certain number of bytes in the
memory are allocated to the variable name. The amount of memory is
allocated according to the type of data that is to be stored in it.
There are three ways of declaring a variable in VB.
(i) Implicit Declaration
(ii) Explicit Declaration
(iii) Default Declaration

(i) Implicit Declaration


Declaration of variable during the execution of program when a
value is assigned to it is called implicit declaration. For example,
a% = 10

(ii) Explicit Declaration


Declaring of variable of a specific type before assigning a value
to it is called explicit declaration. For example,
Dim st as String
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 22

(iii) Default Declaration


When a variable is neither implicitly nor explicitly declared,
then they are assigned variant type by default.
A variable that can hold any type of data is called variant type
variable. For example,
Dim var

Scope Of Variables
The scope of variable specifies the range in the
applications within which the value of the variable can be accessed
and used. There are different levels of scope in VB. These are
(i) Procedure Level
These are also called local variables. The variables defined
within a procedure are procedure level variables. They can be used in
that procedure and cannot be used in any other procedure.
These are declared using the Dim Statement. For example
Dim xyz As Integer

(ii) Form Level


Form level variables are available to all procedure within
the form. These variables are declared in the Declaration part of the
code window. For example
Dim abc As Integer

(iii) Application or Global Level


These variables are available to all procedures within an
application. They retain their value as long as application is running.
The keyword Global is used to declare global level variables.
Global num As Integer

Types of Variables OR Data Types


There are different types of variable in visual basic. These are
1. Numeric Variables
2. String Variables
3. Special Variables
1. Numeric Type variable
The variables that can hold only numeric data are
called numeric type variables. There are five numeric type variables in
VB. These are
(i) Integer Variable
The whole number without a decimal point are called integer. In
VB, an integer can occupy 16 bits or 2 bytes in memory. Its value can
be from –32768 To 32767. Its Syntax is
Dim var-name as Integer
For Example
Dim n as Integer
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 23

(ii) Long Type Variable


A long type integer takes 32 bits or 4 bytes of memory.
Its Syntax is
Dim var-name as Long
For Example
Dim var as Long

(iii) Single Type Variable


The variables that consist of both whole number and a fractional
part. Its takes 32 bits or 4 byte in memory.
Its Syntax is
Dim var-name as Single
For Example
Dim n as Single

(iv) Double Type Variables


These variables are used to store very large or very small numbers.
They also increase the accuracy of calculations. It takes 64 bits or 8
bytes in memory.
Its Syntax is
Dim var-name as Double
For Example
Dim n as Double

(v) Currency Type Variables


Currency type data is used to represent money in calculations. It
takes 64 bits or 8 bytes in memory.
Its Syntax is
Dim var-name as Currency
For Example
Dim money as Currency

(2) String Type Variables


The text type data is called string type data. It consists of
alphabets, digits and special character. It can consist of anything that
can be typed on the keyboard.
In VB, there are two types of string variables.

(i) Variable Length String Variable


The string type variables in which the numbers of characters of a
string are not specified are called variable length string variables. The
maximum length of a string in 32-bit operating system is
approximately 2 billion characters. In a 16-bit operating system, the
maximum length is 65,500 characters. For example
Dim Name as String
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 24

(ii) Fixed Length String Variables


The string type variables in which the maximum numbers of
characters of a string are specified are called fixed length string
variables.
Its Syntax is
Dim var-name as String * Size
For Example
Dim Name as String * 30

(3) Special Variables


VB has several variables to hold special variables.
These includes Boolean and Date Variables.
(i) Boolean Variables
The data that can have either True or False value is called Boolean
data and Boolean type variables are used to hold this data.
For Example
Dim test as Boolean

(ii) Date Variables


Date variables are used to hold date and time. It is a double
precision number. The integer part represents the date and the
fractional part represents the time.
For Example
Dim DOB as Date

Q14: What is Constant? And what is Assignment Statement.

Constant
A quantity that cannot be change during the execution of
program is called constant.
Types of Constants in VB
(i) User Defined Constant
A variable name can also be assigned a value in such a manner
that its value does not change in the program. It behaves as a constant
value and is called user defined constant. The keyword const is used
to define the user defined constant.
For example
Const PI = 3.14159

(ii) Visual Basic Symbolic Constant


VB uses values to specify various operations, properties etc.
These values are numeric constant. Based upon their numeric values,
these constant are difficult to understand and interpret. To make these
constant numeric values more understandable, VB assign names to
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 25

them. These are called symbolic constant and each represent a unique
value. All symbolic constant in VB start with vb.
For example
Form1. BackColor = &HFF0000
So using VB symbolic constant
Form1. BackColor = vbBlue

Assignment Statement
The assignment statement is used to assign a value to a
variable is called assignment statement. The assignment operator “=”
is used to assign a value to a variable.
Syntax
Variable-name = Expression
Example
a = 10 + 20

Q15: what is Expression. What are the types of expression?


Expression
An expression is used for calculating the value of a
formula. It is the combination of different operands and operators. It
gives a single value. For example
AXBXC
In the above example, A, B, C are operands and “X” is the
multiplication operator. The combination of operands and operators
makes an expression.
Types of Expression
There are three types of expression in VB. These are
(i) Arithmetic Expression
(ii) Relational Expression
(iii) Logical Expression

(i) Arithmetic Expression


An arithmetic expression is used for calculating the value of an
arithmetic formula. It consists of operands and arithmetic operators.
Operation Symbol Example Result
Addition + 5+8 13
Subtraction - 8-4 4
Multiplication * 5*7 35
Division / 10 / 2 5
Exponentiation ^ 3^3 27
Integer Division \ 5/2 2
Modulus Mod 5 Mod 2 1

An arithmetic expression gives only one value after computing


the formula. The type of calculated value depends on the type of
operands used in the expression.
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 26

(ii) Relational Expression


An expression which tests the relation between two
operands is called relational expression. After computing the two
operands it gives an answer of True of False.
VB use the following relational operators.

Operator Meaning & Example


> A>B
If A is greater than B, value returned by the
expression will be TRUE, otherwise it will be FALSE.

< A<B
If A is less than B, value returned by the expression
will be TRUE, otherwise it will be FALSE

>= A>=B
If A is greater than or equal to B, value returned by
the expression will be TRUE, otherwise it will be
FALSE

<= A<=B
If A is less than or equal to B, value returned by the
expression will be TRUE, otherwise it will be FALSE

= A=B
If A is equal to B, value returned by the expression
will be TRUE, otherwise it will be FALSE

<> A<>B
If A is not equal to B, value returned by the
expression will be TRUE, otherwise it will be FALSE

(iii) Logical Expression


An expression consisting of logical constant, logical variables or
relational expressions combined together with a logical operator is
called logical expression. It gives a single value of TRUE or FALSE.
VB has the following logical operators.
Operator Example and Meaning
And Exp1 And Exp2
AND The output will be True only if, both Exp1 and Exp2 are true

Or Exp1 Or Exp2
OR The output will be True if, both Exp1 and Exp2 are true. Or either
Exp1 or Exp2 is true
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 27

Not if the expression is true, result will be False, and if expression is


false, output will be True.

Xor Exp1 Xor Exp2


The output will be True if the expressions are different.

Eqv Exp1 Eqv Exp2


The output will be True if both the expressions have the same
values, otherwise output will be False.

Q16; Discuss the Built-in-Functions used in Visual Basic.


A function is a built-in-function that performs a specific task. Its
syntax is
FunctionValue = FunctionName (ArgumentsList)
Some important built-in functions are discussed below.
(1) Asc Function
This function returns the ASCII code of a character. Its syntax is
Asc (Character)
For Example
Asc (“A”) will return 65

(2) Chr Function


This function returns the character corresponding to the
specified ASCII value. Its syntax is
Chr (n)
For Example
Chr (65) will return A

Type Conversion Functions


(1) Str & CStr Functions
These functions are used to convert a numeric value into a
string. Its syntax is
Str (Value)
CStr (Value)
For Example
Str (125) or CStr (125) will returns “125”

(2) Int & Fix Functions


These functions are used to convert a numeric value into a whole
number. Both these functions remove the fractional part of the number
and return the resulting integer value.
The difference between Int and Fix function is that if the numeric
value in the argument is negative then Int returns the first negative
integer less than or equal to the value, whereas the Fix returns the first
negative integer greater then or equal to the value. The syntax is
Int (Number)
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 28

Fix (Number)
For Example
Int (11.2) will returns 11
Fix (11.2) will returns 11
Int (-11.2) will returns 12
Fix (-11.2) will returns 11
(3) CInt Function
This function is used to convert the value to an integer by
rounding off the value. For example
CInt (11.67)will returns 12

String Functions
(1) Val & CVal Functions
These functions are used to convert a string consisting of
numeric digits into numeric value. Its syntax is
Val (String)
CVal (String)
For Example
Val (“1122”) or CVal (“1122”) will returns 1122

(2) Len Function


This function is used to find the length of a string. Its syntax is
Len (string)
For example
Len (“Imran”) will returns 5

(3) Left Function


This function is used to obtain a specified number of left most
characters. Its syntax is
Left (String, n)
For example
Left (“Imran Hussain”, 5) will returns Imran

(4) Right Function


This function is used to obtain a specified number of right most
characters from a string. Its syntax is
Right (String, n)
For example
Right (“Imran Hussain”, 7) will returns Hussain

(5) Mid Function


This function extracts a specified numbers of characters form
anywhere in the string. Its syntax is
Mid (String, s, n)
For example
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 29

Mid (“Muhammad Imran Hussain”, 9, 5) returns


Imran

(6) UCase Function


This function converts all characters in a string into their upper
case equivalent. Its syntax is
UCase (String)
For example
UCase (“Imran”) returns IMRAN

(7) LCase Function


This function converts all characters in a string into their lower
case equivalent. Its syntax is
LCase (String)
For example
LCase (“Imran”) returns Imran

(8) Instr Function


This function finds the position of a sub string within a string
variable. Its syntax is
Instr (a, String, “substring”)
For example
Instr (1, “Imran Hussain”, “ran”) will return 4

(9) Rnd (Random Number) Function


This function is used to generate a random number. Its syntax is
Rnd

Date & Time Functions


(1) Date Function
This function is used to get the current date of the system. Its
syntax is
Date

(2) Month Function


This function is used to get the month of the year. Its syntax is
Month (Date)

(3) Day Function


This function is used to get the day of the month. Its syntax is
Day (Date)

(4) Year Function


This function is used to get the year of the specified date. Its
syntax is
Year (Date)
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 30

Example
BirthDay = #05/04/1984#
Print “Day = “; Day (BirthDay)
Print “Month = “; Month (BirthDay)
Print “Year = “; Year (BirthDay)

(5) Time Function


This function is used to get the current time of the system.
Its syntax is
Time

(6) Hour Function


This function is used to get the hour of the day for the specified
time. Its syntax is
Hour (Time)

(7) Minute Function


This function is used to get the minute of the specified time. Its
syntax is
Minute (Time)

(8) Second Function


This function is used to get the Second of the specified time. Its
syntax is
Second (Time)

(9) Now Function


This function is used to get the current date and time of the system.
Its syntax is
Now
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 31

Q17: Define Selection Structure.


Selection Structures
The control structures that select a statement or set of
statements for execution after testing a condition are called selection
structures.
These are
1) If.......Then
2) If.......Then........Else
3) Select case

1) If.......Then Structure

This structure executes a statement if the given condition is true


and ignores the statement if the condition is false.

Syntax
If (Condition) Then
Statement(s)
End If
Example
If (Marks >= 33) then
Print “ You are Pass”
End If

2) If.......Then.......Else Structure
In this structure one condition and two statements or two blocks
of statements are given. When the condition is true, the first statement
is executed and the second statement is ignored. When the condition
is false, the first statement is ignored and the second statement is
executed.
Syntax
If (condition)
Statement(s)
Else
Statement(s)
End if
Example
Private Sub Command1_click ()
Dim marks as integer
Marks = Inputbox(“Enter Your marks”)
If (marks is >=33) then
Print “You are Pass”
Else
Print “You are Fail”
End if
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 32

End sub

3) Nested If.......Then......Else Structure


Multiple conditions can also be tested by using If......Then
structure. To test multiple conditions nested If.....Then structure is
used. In a nested structure, one If......Then......Else structure is placed
inside another If......Then.......Else structure.
Syntax
If (condition) Then
Statement (s)
Else If (condition) Then
Statement (s)
Else If (condition) Then
Statement (s)
-
-
-
Else
Statement (s)
End If
Example
Private Sub Command1_click ( )
Dim m As Integer
m = InputBox("Enter Marks")
If (m > 80) Then
MsgBox ("Your Grade is A+")
ElseIf (m >= 70 And m < 80) Then
MsgBox ("Your Grade is A")
ElseIf (m >= 60 And m < 70) Then
MsgBox ("Your Grade is B")
ElseIf (m >= 50 And m < 60) Then
MsgBox ("Your Grade is C")
ElseIf (m >= 40 And m < 50) Then
MsgBox ("Your Grade is D")
ElseIf (m >= 33 And m < 40) Then
MsgBox ("Your Grade is E")
Else
MsgBox ("You are Fail")
End If
End Sub

Select Case Structure:


The If......Then.......Else structure is manageable in cases where
one or two conditions are to be tested. When more then two conditions
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 33

are to be tested, the if structure becomes completed. In such


conditions Select case structure is used.
The select case structure is used where one condition and many
choices are given. This is better than the If......Then.......Else structure.
Syntax
Select Case Expression
Case expression1
Statement(s)
Case expression2
Statement(s)
Case expression3
Statement(s)
Case Else
Statement(s)
End select

Example
Private Sub Command1_click ()
Dim marks as integer
Marks = InputBox (“Marks Obtained”)
Select Case marks
Case 0 to 32
MsgBox “Fail”
Case 33 to 49
MsgBox “Third Division”
Case 50 to 59
MsgBox “Second Division”
Case 60 to 100
MsgBox “First Division”
Case Else
MsgBox “Not valid marks percentage”
End Select
End Sub
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 34

Q18: Define Looping Structure

Loop Structure
A structure in which a set of statements are executed repeatedly
are called loop structure. In VB there are different types of loop
structure
1) For loop:
This loop repeats a set of statements for a specified number of
times. It is also called counter loop.
Syntax
For Initial value To Final value
VB Statement(s)
Next [Variable]
Example
Private Sub Command1_click ( )
Dim n as integer
For n = 1 to 10
Print n
Next n
End sub

2) While......... Wend Structure.


The While........Wend structure executes a statement or set of
statements as long as the condition remains true.
Syntax
While (Condition)
VB Statement(s)
Wend
Example
Private Sub Command1_click ()
Dim n as integer
n=1
While (n<= 10)
Print n
n = n+1
Wend
End Sub

3) Do........While Loop Structure:


The Do...... While Loop structure executes a statement or set of
statements as long as given condition remains true.
Syntax
Do While (Condition)
VB Statement(s)
Loop
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 35

Example

Private Sub Command1_click ( )


Dim n as integer
n=1
Do While (n<=10)
Print n
n = n+1
Loop
End Sub

4) Do........Until Loop Structure:


The Do...... Until Loop structure executes a statement or set of
statements as long as given condition remains false.
Syntax
Do Until (Condition)
VB Statement(s)
Loop
Example
Private Sub Command1_click ()
Dim n as integer
n=1
Do Until (n > 10)
Print n
n = n+1
Loop
End Sub

5) Do……Loop While:
The Do......Loop While is similar to the Do......While Loop except
that, in this syntax, the condition is tested at the end of the loop
structure.
Syntax
Do
VB Statement(s)
Loop While (Condition)
Example
Private Sub Command1_click ()
Dim n as integer
n=1
Do
Print n
n = n+1
Loop While (n <= 10)
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 36

End Sub
Do……..Loop Until:
This loop structure is also similar to the Do......Until Loop except
that the condition is tested at the end of the loop structure. The loop
statements are executed at the as long as the given condition remains
false.
Syntax
Do
VB Statement(s)
Loop until (Condition)
Example
Private Sub Command1_click ()
Dim n as integer
n=1
Do
Print n
n = n+1
Loop until (n > 10)
End Sub
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 37

Q19: what is array and what are the types of array in Visual
Basic.
Array
Array is the collection of finite homogeneous type of data, which
are stored in successive memory locations.
The memory locations are identifies by a name, which is called the
array name. The data items of the array are called the elements of
array and each data item is stored in separate memory location.
Each memory location within the array is identifies by its position
value, which is called the index of the array.
110 112 114 116 118 120 Memory Location
22 11 13 52 21 05
x[1] x[2] x[3] x[4] x[5] x[6] Element

Index
Types of array
There are two types of array.
1) One dimensional array
2) Two Dimensional array
One Dimensional Array (Linear Array)
One-dimensional array represent the data in the form of vector, list
or linear form. It is used to store similar type of data consisting of only
one row or column.
110 112 114 116 118 120 Memory Location
22 11 13 52 21 05
x[1] x[2] x[3] x[4] x[5] x[6] Element

Index
Declaration of One Dimensional Array
The method of informing the computer of the name, data type
and total number of elements of an array is called declaring of array.
Its syntax is
Dim Array-Name (n) As DataType
For example
Dim Month (11) As String
Example
Private Sub Command1_Click( )
Dim A (4) As Integer
Dim I As Integer
For I = 0 To 4
A (I) = Inputbox (“Enter value in 1-D array”)
Next I
Print (“Element of the 1-D array are”)
For I = 0 To 4
Print A (I)
Next I
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 38

End Sub

Two Dimensional Array


Two-dimensional array represent the data in the form of
table or matrix. It consists of rows and columns. Each element of 2-D
array is referenced by two subscripts, one represent the row and
second represents the column. The syntax to declare 2-D array is
Dim Array-Name (r, c) As DataType
For example
Dim A (2, 2) As Integer
Example
Private Sub Command1_Click( )
Dim a (2, 2) As Integer
Dim r, c As Integer
For r = 0 To 2
For c = 0 To 2
a (r, c) = r + c
Next c
Next r
For r = 0 To 2
For c = 0 To 2
Print a (r, c);
Next c
Print
Next r
End Sub

Control Array
A group of control that share the common the same name, type
and event procedure is called control array. Since all control in the
control array have the same name, they call the same procedure and
are distinguish from each other by their index property.
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 39

Q20: What are Procedure and Functions, how they are called.
Also describe argument passing mechanism with examples.

Procedure
Group of statements that cannot return a value is called
procedure. It is also called Sub Procedure or Subroutine. Its syntax is
Specifier Sub ProcName ( Argument Seperated by Commas)
- --
- --
End Sub
Where
Specifier specifies the scope of procedure. It can be private or
public.
Sub The Keyword Sub is used to specify Sub Procedure.
ProcName It specifies the name of procedure. The procedure is
called by its name.

Calling Sub Procedure


A procedure is executed by Call statement. The procedure that
execute a sub procedure is called calling procedure. While calling a sub
procedure its name is mentioned and required argument are supplied.
Its syntax is
Call ProcName (Arguments)
For example
Call Sum (a, b)
Example (Calling Procedure without Arguments)

Private Sub Command1_Click( )


Call message ( )
Print “ Good Bye procedure without arguments”
End Sub

Public Sub message ( )


Print “ Welcome to procedure without argument”
End Sub

Argument Passing Mechanism


The arguments can be passed to a procedure in two ways.
1. Pass By Value
2. Pass By Reference
1. Pass By Value
In this mechanism, the actual value is passed to the procedure
and the called procedure cannot change the original value.
The keyword ByVal is used to specify that the argument be being
passed
by value.
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 40

2. Pass by Reference
Pass by reference is called pass by address. In this the memory
address is passed to the procedure. If the value of the variable is
changed in the procedure, the value of the variable is also changes in
the calling procedure.
Example (Calling Procedure with Arguments)
Pass By Value Pass By Reference
Private Sub Command1_Click( ) Private Sub Command1_Click( )
Dim a, b As Integer Dim a, b As Integer
a=4 a=4
b=5 b=5
Call Sum (a, b) Call Sum (a, b)
Print a Print a
Print b Print b
End Sub End Sub
Public Sub Sum (ByVal I As Integer, Public Sub Sum (ByRef I As Integer,
ByVal J As Integer) ByRef J As Integer)
Dim c as Integer Dim c as Integer
c=i+j c=i+j
Print c Print c
I = 10 I = 10
J = 20 J = 20
End Sub End Sub

Function
A function is an independent procedure that is written to perform
a specific task. It is a non-event procedure. It is executed by another
procedure and it returns a single value to the procedure that executes
it.
Syntax
Specifier Funtion Fname (Arguments) As Type
- ---
- ---
Fname = Expression
End Function
Example
Private Sub Command1_Click( )
Dim A as integer
A = Sum (4, 5)
End Sub

Public Function Sum (A As Integer, B As Integer) As


Integer
Sum = A+B
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 41

End Function
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 42

Q21: Discuss Database, BDMS, Visual Data Manager, Data


Management Tools, Data Bound Controls and Recordset
Object.
Data Base
A database is a collection of related information organized in a
specific format that can be easily retrieved for processing. The data in
the database is arranged in tabular form, i.e. in rows and columns. The
rows referred to database records and columns provide the
characteristics of records, and these are called fields.

Database management System


The DBMS manages all the information contained in database. It
is used to create and maintain database. The commonly used DBMS
systems are Microsoft Access, SQL Server 2000 etc

Visual Data Manager


It is used to develop database in Visual Basic. To create a
database in VB, the following steps are taken.
Click Add Ins menu Choose Visual Data Manager File New
Microsoft Access Version 7.0 and go on.

Data Management Tools


VB provide following tools for managing database.
1. Data Control
2. Data Access Object (DAO)
3. ActiveX Data Object (ADO)

1. Data Control
Data control is a primary interface between VB application
and a database. It provides direct access to database without writing
any code. Setting the properties and methods of this control accesses
the records form database tables.
2. Data Access Object (DAO)
DAO is a collection of objects, which are used for managing
and manipulating databases. The DAO collection contains several
objects. The properties and methods associated with these objects are
used to perform database management operation.
3. ActiveX Data Object (ADO)
It is a latest data object technology. It used the best
features of old DAO technology. The ADO is specially designed for
client-server applications. It is also used for database management on
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 43

World Wide Web. The following tools/objects of ADO are used to


manage databases.
- ADO Data Control - ADO Objects
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 44

Data Bound Control


The controls that can be connected with the
databases are called data bound controls. For example, Label, Textbox,
Checkbox etc.

RecordSet Object
The recordset object consists of a collection of
records. In database programming, a recordset is equivalent to a
variable that is used to store records.
Methods of RecordSet

Navigation Methods. These methods are used to navigate form one


record to another in the database.
MoveFirst Method Move to first record
MoveNext Method Move to next record
MovePrivious Method Move to previous record
MoveLast Method Move to last record

Record Entering Methods of Recordset Object


Add New Add a new record
Edit Method Used to change a record
Update Method Used to save a record
Delete Method Delete a record
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 45

Q22.1: Consider a table student (rno, name) of database


college.mdb.
Write the VB code to perform the functions seen on the below
form using Data Control.

Private Sub First_Click( )


Data1.Recordset.MoveFirst
End Sub

Private Sub Next_Click( )


If Data1.Recordset.EOF Then
Data1.Recordset.MoveLast
Else
Data1.Recordset.MoveNext
End If
End Sub

Private Sub Privious_Click( )


If Data1.Recordset.BOF Then
Data1.Recordset.MoveFirst
Else
Data1.Recordset.MovePrevious
End If
End Sub

Private Sub Last_Click( )


Data1.Recordset.MoveLast
End Sub

Private Sub AddNew_Click( )


Data1.Recordset.AddNew
Text1.SetFocus
End Sub
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 46

Private Sub Save_Click( )


Data1.Recordset.Fields ("rno") = Cint (Text1.Text)
Data1.Recordset.Fields ("name") = CStr (Text2.Text)
Data1.Recordset.Update
MsgBox "Record Has Been Saved"
End Sub

Private Sub Delete_Click( )


Dim d As Integer
d = InputBox("Enter the Roll No. You Want To Delete")
Data1.Recordset.FindFirst ("rno=" & d & "")
If Data1.Recordset.NoMatch Then
MsgBox "Reocrd does not exist"
Else
Data1.Recordset.Delete
MsgBox "Record Has Been Deleted"
Data1.Recordset.MoveFirst
End If
End Sub

Private Sub SearchByRollNo_Click( )


Dim st As Integer
st = InputBox("Enter the Roll No. You Want To Delete")
Data1.Recordset.FindFirst ("rno=" & st & "")
If Data1.Recordset.NoMatch Then
MsgBox "Reocrd does not exist"
Else
Text1.Text = Data1.Recordset.Fields("rno")
Text2.Text = Data1.Recordset.Fields("name")
End If
End Sub

Private Sub SearchByName_Click( )


Dim st As String
st = InputBox("Enter the Name of Student You Want To Delete")
Data1.Recordset.FindFirst ("name='" & st & "'")
If Data1.Recordset.NoMatch Then
MsgBox "Reocrd does not exist"
Else
Text1.Text = Data1.Recordset.Fields("rno")
Text2.Text = Data1.Recordset.Fields("name")
End If
End Sub
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 47

Private Sub Change_Click( )


If Change. Caption = "Edit" Then
Dim ed As Integer
ed = InputBox("Enter Roll No of Student You Want To Update")
Data1.Recordset.FindFirst ("rno=" & ed & "")
If Data1.Recordset.EOF = True Then
MsgBox "Record not found"
Else
Text1.Text = Data1.Recordset.Fields("rno")
Text2.Text = Data1.Recordset.Fields("name")
Change. Caption = "Update"
End If
ElseIf Change. Caption = "Update" Then
Data1.Recordset.Edit
Data1.Recordset.Fields("rno") = Text1.Text
Data1.Recordset.Fields("name") = Text2.Text
Data1.Recordset.Update
MsgBox "Record Has Been Updated"
Change. Caption = "Edit"
End If
End Sub

Q22.2: Consider a table student (rno, name) of database


college.mdb.
Write the VB code to perform the functions seen on the below
form using ADO Data Control.

Private Sub First_Click( )


Adodc1.Recordset.MoveFirst
End Sub

Private Sub Next_Click()


If Adodc1.Recordset.EOF Then
Adodc1.Recordset.MoveLast
Else
Adodc1.Recordset.MoveNext
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 48

End If
End Sub

Private Sub Previous_Click()


If Adodc1.Recordset.BOF Then
Adodc1.Recordset.MoveFirst
Else
Adodc1.Recordset.MovePrevious
End If
End Sub

Private Sub Last_Click()


Adodc1.Recordset.MoveLast
End Sub

Private Sub AddNew_Click()


Adodc1.Recordset.AddNew
Text1.SetFocus
End Sub

Private Sub Save_Click()


Adodc1.Recordset.Fields("rno") = CInt(Text1.Text)
Adodc1.Recordset.Fields("name") = CStr(Text2.Text)
Adodc1.Recordset.Update
MsgBox "Record Has Been Saved"
End Sub

Private Sub Delete_Click()


Dim d As Integer
d = InputBox("Enter the Roll No. You Want To Delete")
Adodc1.Recordset.Find ("rno=" & d & "")
If Adodc1.Recordset.EOF Then
MsgBox "Reocrd does not exist"
Else
Adodc1.Recordset.Delete
MsgBox "Record Has Been Deleted"
Adodc1.Recordset.MoveFirst
End If
End Sub

Private Sub SearchByRollNo_Click()


Dim st As Integer
st = InputBox("Enter the Roll No. You Want To Delete")
Adodc1.Recordset.Find ("rno=" & st & "")
If Adodc1.Recordset.EOF Then
MsgBox "Reocrd does not exist"
By: Haji Asif Sohail, BERGER Paints Pakistan Limited, Lahore, Pakistan 49

Else
Text1.Text = Adodc1.Recordset.Fields("rno")
Text2.Text = Adodc1.Recordset.Fields("name")
End If
End Sub

Private Sub SearchByName_Click()


Dim st As String
st = InputBox("Enter the Name of Student You Want To Delete")
Adodc1.Recordset.Find ("name='" & st & "'")
If Adodc1.Recordset.BOF Then
MsgBox "Reocrd does not exist"
Else
Text1.Text = Adodc1.Recordset.Fields("rno")
Text2.Text = Adodc1.Recordset.Fields("name")
End If
End Sub

Private Sub Change_Click()


If Change. Caption = "Edit" Then
Dim ed As Integer
ed = InputBox("Enter Roll No of Strudent You Want To Update")
Adodc1.Recordset.Find ("rno=" & ed & "")
If Adodc1.Recordset.EOF = True Then
MsgBox "Record not found"
Else
Text1.Text = Adodc1.Recordset.Fields("rno")
Text2.Text = Adodc1.Recordset.Fields("name")
Change. Caption = "Update"
End If

ElseIf Change. Caption = "Update" Then


Adodc1.Recordset.Fields("rno") = Text1.Text
Adodc1.Recordset.Fields("name") = Text2.Text
Adodc1.Recordset.Update
MsgBox "Record Has Been Updated"
Change. Caption = "Edit"
End If
End Sub

Q22.3: Consider a table student (rno, name) of database


college.mdb,
Write the VB code to perform the functions seen on the below
form using ADO Library.

Вам также может понравиться