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

Visual Basic

1. INTRODUCTION........................................................................................................................................
2. OPTION BUTTONS....................................................................................................................................
3. CHECK BOXES...........................................................................................................................................
4. SCROLLBARS.............................................................................................................................................
5. CONTROL STRUCTURES........................................................................................................................
6. MOUSE EVENTS........................................................................................................................................
7. KEYBOARD EVENTS................................................................................................................................
8. DIALOG BOXES.........................................................................................................................................
9. LIST BOX & COMBO BOX.......................................................................................................................
10. FOCUS.........................................................................................................................................................
11. TIMER CONTROL....................................................................................................................................
12. ARRAYS......................................................................................................................................................
13. MENUS........................................................................................................................................................
14. MICROSOFT ACCESS.............................................................................................................................
15. DATABASE PROGRAMMING...............................................................................................................
16. ACTIVEX CONTROLS............................................................................................................................
17. WEB BROWSER.......................................................................................................................................

Visual Basic

1. INTRODUCTION
Application development Using Visual Basic
Microsoft Visual Basic is a powerful development platform that you can use to create feature-rich
applications for the Windows 95 and Windows NT operating systems quickly and easily. Although
professional programmers use visual Basic, it is easy for novices to program in Visual Basic with
professional result.
Features in Visual Basic
Visual Basic provides a rapid application development (or RAD) environment, a rich object-based
language, and an easy to use set of debugging tools. For companies developing custom applications, using
Visual Basic reduces the development time and costs. Its intuitive interface makes the makes Visual Basic
an excellent tool for programmers.
New users benefit from mouse operations and a consistent look and feel; more advanced users benefit from
ease of use features, such as drop down list boxes and multiple windows applications.
Visual Basic supports a number of features that make it an excellent language for quickly creating fullfeatured solutions, including:
Multiple Windows Platforms
OLE programmability
Rapid Application Development (RAD)
Editions of Visual Basic
Visual Basic Version 6.0 is available in 3 editions
The Learning Edition: This is the introductory edition, which carries all the tools required to build and
maintain a windows application.
Professional Edition: The professional edition is for application developers and includes advanced
features such as tools for developing Active X controls
Enterprise Edition: The enterprise edition is the most advanced edition and is aimed at programmers
who build distributed applications in a team environment. It includes all the features of the professional
edition, plus the tools such as Visual SourceSafe (a version control system) and the automation and
Component Manager, which are not covered in this book.
Visual Basic Terminology
Visual Basic requires an understanding of some common terminology. The following table lists some key
terms used in visual Basic. you will learn more about each term later in the course.
Term
Design Time

Definition
Any time an application is being developed in the Visual Basic environment.

Run Time

Any time an application is running. At run time, the programmer interacts with the
application as the user would.

Forms

Windows that serve as the interface for an application or as dialog boxes used to gather
information from the user.

Controls

Graphical representations of objects, such as buttons, list boxes, and edit boxes that users
manipulate to provide information to the application.

Properties

The characteristic of an object such as size, Text or color.

Methods

The actions that an object can perform or that can be performed on the object.

Events

Actions recognized by a form or control. Events occur as the user, operating system, or
application interacts with the objects of a program.

Visual Basic
Event Driven

When a program is event driven, its code executes in response to events invoked by the
user, operating system or application.

Types of Applications in Visual Basic 6.0

Standard.Exe: A standard Exe project is a typical application.


Active X EXE, Active X DLL: These types of projects are available with the Professional edition.
Active X components are OLE automation servers and there are the basic code-building components that
do not have a visual basic interface and that you can add special functionality to your application.

Active X Control: This type of project is also a feature of the professional edition. Use it to develop your
own Active X control.

Active X Document EXE, Active X DLL: Active X documents are in essence Visual Basic applications
that can run in the environment of a container that supports hyperlinking (such as Internet Explorer).

VB Application Wizard, VB Wizard Manager: The Application Wizard takes you through the steps of
setting up the skeleton of a news application. The Wizard Manager lets you build your own Wizard. A
wizard is a sequence of windows that collects information from the user and builds an application based
on it.

Data Project: This feature is available in the Enterprise edition, and it does not correspond to a new
project type. It is identical to the Standard.EXE project type, but it automatically adds the controls that
are used in accessing the databases to the toolbox.

DHTML Application: VB6 allows you to build Dynamic HTML pages that can be displayed in the
browser's window on a client computer.

IIS Application: VB6 allows you to build application that run on the Web server and interact with clients
over the Internet with the Internet Information Server.

Addin: You can create your own add-ins for the Visual Basic IDE.
Visual Basic Programming
Visual Basic is an event-driven programming language
Visual Basic Programming

Visual Programming
Programs are designed here
using the tools that come with
the Visual Basic Package
{Objects are defined here}

Code Programming
Events are coded here

The Integrated Development Environment (IDE)


The IDE of Visual Basic consists of a variety of elements. The most commonly used are
Menu Bar
Toolbars
Toolbox: On the extreme left of the screen is the Toolbox. Toolbox contains the icons of the controls that
you can place on a Form. The default Toolbox is called as the General Toolbox.

Solution Explorer: The window titled Project is the Solution Explorer Window, which displays the
components of the project organized in folders.

Visual Basic
Properties Window: The Properties Window contains the property settings for the selected control.
Properties are attributes of an object.
The Form Designer: It is the main window in the middle of the screen where you can design and edit the
applications user interface. The Form Designer displays two windows for each form the Form itself
and the Code window.

THE CONTROLS OF VISUAL BASIC


Pointer

Picture box

Textbox

Frame

Checkbox

Option Button

Combo box

List box

Horizontal Scrollbar

Vertical Scrollbar

Timer

Drive List box

Directory List box

File List box

Draw Shapes

Draw Lines

Image Control

Data Access Object

OLE Container

Naming Conventions for Controls


Control
Form
Check Box
Combo Box
Button Button
Directory List
Drive List
File List
Frame
Horizontal Scrollbar
Vertical Scrollbar
Image
Label
List Box
Menu
Option Button
Shape
Text Box
Timer

Label
Button Button

First 3 characters of Name


Frm
Chk
Cmb
BTN
Dir
Drv
Fil
Fra
Hsb
Vsb
Img
Lbl
Lst
Mnu
Opt
Shp
Txt
tmr

Visual Basic
The Form

The form is the screen area where controls are placed and events are coded to make modules of an
application. It has many properties some of which are given below
Name
Left
Top
Width
Height
Icon
MousePointer
WindowState

The default name given to the form


The x coordinate of the upper left corner of the form.
The y coordinate of the upper left corner of the form
Width specifies the width of the form in pixels
Height specifies the height of the form in pixels
The icon that appears when the form is minimized
The shape of the mouse pointer when it runs over the form at execution time.
The state of the form (maximized, minimized or normal) when the form is run.

The Textbox
Textboxes are used to enter and display information as String values. They have various properties.
Following are some of the commonly used properties.
Name
Text
Enabled
Max Length
Multi Line

Scrollbars
Password
Char
BorderStyle

Returns the name used to identify the textbox.


Sets the text contained in the textbox.
Sets the value that determines whether or not the textbox can respond to user generated
events.
Determines the maximum number of characters allowed in the textbox.
Allows text to wrap as text is entered into a textbox. When the multi line property is true,
you can use the Alignment property to left, right, or center justify text, and enter more than
one line. When the multi line property is set to false, Visual Basic does not allow the user
to specify the alignment property.
Enables you to attach built in scrollbars to the textbox so that users can scroll text in the
textbox when the program is running. The default value is 0, which signifies no scrollbars.
The values 2 and 3 can be used if the multi line property is set to true.
Is used for displaying specified characters when the user types a password. Normally, this
property is not set it is empty. For example, if Password Char is set to X, and the user
enters a 5-character password then XXXXX will be displayed in the textbox.
The default BorderStyle value is 1, which provides a thin line around the box.

The Label: Labels are used as tags to describe what kind of information the Textboxes contain. They are normally
placed on the left of the Textbox. If the Textbox is displaying an Employee Name, then The Labels Text
property will be set to the String First Name: Following are some of the properties of the Label control
Name
Returns the name used to identify the label box.
Text
Determines the text displayed in the label.
Visible
Determines whether the label box should be visible or not.
Autosize
Determines whether Visual Basic should automatically resize the labels border to fit the
label Text.

Visual Basic
Alignment
Border Style

The values 0, 1 and 2 indicate left, right and center alignment respectively. By default,
captions are aligned to the left.
Determines whether a visible border appears around the label.

The Button Button:


Button Buttons are used to trigger a sequence of action or check for a condition when the mouse is clicked
on them. They have properties similar to the ones described for the previous controls. Of special interest are
the Visible And Enabled properties which when set to False make the Button invisible and Disabled when
the program is run. Disabled means that even if there is a mouse click on the Button then it will be
disregarded and no event or action will be triggered.
Name
Returns the name used to identify the Button button.
Text
Determines the text to be displayed.
Value
Returns or sets a value indicating whether the button is chosen or not. The property is not
available at design time.

Visual Basic
Program 1 Hello Program

Form

Name
Text
WindowState

FRMHELLO
The Hello Program
2-Maximized

Text 1

Name
TextAlignment
BackColor
ForeColor
Font
ReadOnly

TXTHELLO
2-Center
Any Light Color
Any Dark Color
Change if Reqd.
True

Button 1

Name
Text

BTNDISPLAY
&DISPLAY

Button 2

Name
Text

BTNCLEAR
&CLEAR

Button 3

Name
Text

BTNX
E&XIT

Code:
Private Sub BTNCLEAR_Click( )
TXTHELLO.Text = " "
End Sub
Private Sub BTNDISPLAY_Click( )
TXTHELLO.Text = "HELLO"
End Sub
Private Sub BTNX_Click( )
End
End Sub
Some Important Statements

Private Sub: When you are writing the code for a particular object, the first line of the code, which
Visual Basic writes for you begins with the words Private Sub. Sub is a keyword indicating the
beginning of a procedure. A procedure is a code dedicated to a particular event. The name of the
procedure is Objectname_Event
End Sub: It is the last line of the procedure and marks the end of the procedure.
End: It causes a Visual Basic program to terminate.
Dim: It is an instruction to Visual Basic that the following word is the name of a variable.

Visual Basic

2. Option Buttons
The Option Button
Option Buttons are controls that are used together within a group. They indicate alternative options to be
chosen in response to a particular type of information. They are grouped together within one frame and at
any time only one option button can be chosen from a group. Some of the properties are: Name
Text
Alignment
Checked

Assigns a name to identify the option button.


Specifies the text that appears besides the option button.
Determines the alignment of the option button with respect to the Text.
Returns or sets the state of the option button.

The GroupBox
Groupboxes are used to enclose checkboxes and option buttons which are other controls discussed later in
this chapter. They indicate a group of controls on the form, which contain related information of one type.
Their properties are: Name
Assigns a name to identify the frame.
Text
Specifies the Text text.
Visible
Returns or sets the value indicating whether or not the frame is visible.
Enabled
Determines whether a control can respond to user generated events.
Picture Control
The Image control is similar to the Picture box control except that that it has the special stretch property,
which allows the picture to fit and adjust to the size of the contained Bitmap image .
Name
Picture
Stretch

The name of the image control


By default, there is no image displayed in the control, but Can be set to the
pathname of a .BMP,.ICO,.JPG file. Then The image will be displayed.
This property, if set to true resizes the Image control to fit the size of the bmp file it
displays.

Public Procedures
A public procedure is accessible to any object on a form. It is written in the General Declaration area of the
form. A public procedure can be created using Tools > Add Procedure (in the code window only)
Program 2 Option Button Program

Form

Name
Text
WindowState

FRMOPTION
The Option Button Program
2-Maximized

Visual Basic
Text 1

Name
Text

Name
TextAlignment
Font
ReadOnly
Text
Option 1
OPTRED
&RED

TXTOPTION
2-Center
Change if Reqd.
True
Visual Basic
Option 2
OPTGREEN
&GREEN

Button 1

Name
Text

BTNX
E&XIT

GroupBox 1

Text

ForeColor

Name
Text

Option 4
OPTR
RE&D

Option 5
OPTG
GREE&N

Option 3
OPTBLUE
&BLUE

Option 6
OPTB
B&LUE

Code
Private Sub BTNX_Click( )
End
End Sub

Private Sub OPTGreen_ Click ( )


TXTOPTION.BackColor = Color.Green
End Sub

Private Sub OPTBlue_Click( )


TXTOPTION.BackColor = Color.Blue
End Sub

Private Sub OPTG_ Click ( )


TXTOPTION.ForeColor = Color.Green
End Sub

Private Sub OPTB_ Click ( )


TXTOPTION.ForeColor = Color.Blue
End Sub

Private Sub OPTRed_ Click ( )


TXTOPTION.BackColor = Color.Red
End Sub
Private Sub OPTR_ Click ( )
TXTOPTION.ForeColor = Color.Red
End Sub

Program 3 Face Program

Form

Name
Text

Name
Text
WindowState
Option 1
OPTHAPPY
&HAPPY

FRMFACE
The Face Program
2-Maximized
Option 2
OPTOK
&OK

Option 3
OPTSAD
&SAD

Path for Images: C:\Program Files\Microsoft Visual Studio\Common\Graphics\Icons\Misc


Picture 1
Picture 2
Picture 3
Name
PCTHAPPY
PCTOK
PCTSAD
Picture
Face02
Face01
Face04
Visible
False
False
False
Name
Text
BorderStyle
Visible
Button 1

Label 1
LBLHAPPY
I am Happy
1-FixedSingle
False

Label 2
LBLOK
I am Ok
1-FixedSingle
False

Name
Text

Code
Public Sub Face( )
If OPTHAPPY.Checked = True Then
PCTHAPPY.Visible = True
LBLHAPPY.Visible = True
Else
PCTHAPPY.Visible = False
LBLHAPPY.Visible = False
End If
If OPTOK.Checked = True Then
PCTOK.Visible = True
LBLOK.Visible = True
Else
PCTOK.Visible = False
LBLOK.Visible = False
End If
If OPTSAD.Checked = True Then
PCTSAD.Visible = True
LBLSAD.Visible = True
Else
PCTSAD.Visible = False
LBLSAD.Visible = False
End If

Label 3
LBLSAD
I am Sad
1-FixedSingle
False

BTNX
E&XIT
End Sub

Private Sub BTNX_Click( )


End
End Sub
Private Sub OPTHAPPY_Click( )
FACE ( )
End Sub
Private Sub OPTOK_ Click ( )
FACE ( )
End Sub
Private Sub OPTSAD_ Click ( )
FACE ( )
End Sub

3. Check Boxes
The Check Box:
The Checkbox is a control that asks the user for Yes-No type of information. Some of the properties are: Name
Assigns a name to identify the checkbox
Text
Specifies the text that appears besides the checkbox
Enabled
Sets a value that determines whether the checkbox can respond to user generated
events
Checked
Is used to specify the state of a checkbox. If the value is false, the checkbox is
deselected. If the value is true, the checkbox is selected.
Program 4 Flag Program

Form

Name
Text

Name
Text
WindowState
Check 1
CHKAUS
&AUSTRALIA

FRMFLAG
The Flag Program
2-Maximized
Check 2
CHKUSA
&USA

Check 3
CHKUK
U&K

Path for Images: C:\Program Files\Microsoft Visual Studio\Common\Graphics\Icons\Flags


Picture 1
Picture 2
Picture 3
Name
PCTAUS
PCTUSA
PCTUK
Picture
Flgastrl
Flgusa02
Flguk
Visible
False
False
False
Button 1
Code
Private Sub CHKAUS_ Click ( )
If CHKAUS.Checked = True Then
PCTAUS.Visible = True
Else
PCTAUS.Visible = False
End If
End Sub
Private Sub CHKUSA_ Click ( )
If CHKUSA.Checked = True Then
PCTUSA.Visible = True
Else
PCTUSA.Visible = False
End If
End Sub

Name
Text

BTNX
E&XIT
Private Sub CHKUK_ Click ( )
If CHKUK.Checked = True Then
PCTUK.Visible = True
Else
PCTUK.Visible = False
End If
End Sub
Private Sub BTNX_Click( )
End
End Sub

Program 5 Check Box Program

Form

Name
Text

Name
Text
WindowState
Check 1
CHKRED
&RED

FRMCHECK
The Check Box Program
2-Maximized
Check 2
CHKGREEN
&GREEN

Label 1

Name
Text
BorderStyle

LBLCHECK
1-FixedSingle

Button 1

Name
Text

BTNX
E&XIT

Code
Private Sub CHKBlue_ Click ( )
CHECK ( )
End Sub
Private Sub CHKGreen_ Click ( )
CHECK ( )
End Sub
Private Sub CHKRed_ Click ( )
CHECK ( )

Check 3
CHKBLUE
&BLUE

End Sub
Private Sub BTNX_Click( )
End
End Sub
Private Sub Form_Load( )
CHECK ( )
End Sub

Public Sub CHECK( )


Dim INFO
If CHKRed.Checked = True Then
INFO = "YOU HAVE SELECTED THE RED CHECK BOX"
Else
INFO = "YOU HAVE DESELECTED THE RED CHECK BOX"
End If
If CHKBlue.Checked = True Then
INFO = INFO + Chr(13) + "YOU HAVE SELECTED THE BLUE CHECK BOX"
Else
INFO = INFO + Chr(13) + "YOU HAVE DESLECTED THE BLUE CHECK BOX"
End If
If CHKGreen.Checked = True Then
INFO = INFO + Chr(13) + "YOU HAVE SELECTED THE GREEN CHECK BOX"
Else
INFO = INFO + Chr(13) + "YOU HAVE DESELECTED THE GREEN CHECK BOX"
End If
LBLCHECK.Text = INFO
End Sub

Assignment

The label should display the status of each check box ON or OFF and the selected level.

10

4. Scrollbars
Scrollbars
Scrollbar is a commonly used control in Windows programs. The object enables the user to select a value
by positioning the thumb (the square tab on the scrollbar) to a desired position. A scrollbar represents a set
of positive integer values. To cover a range of negative values or decimal numbers you must use a little
Maths in your code. For e.g., to set the range from 2.5 to 8.5, set the Min and Max properties to 25 and 85
respectively and divide the controls value by 10. If the range you need is -2.5 to 8.5 set the Min and Max
properties to 0 to 110 (25 + 85) respectively. To get the required value, divide the controls value by 10 and
subtract 2.5 from it.
The Horizontal Scrollbar
The Horizontal Scrollbar is used to scroll up and down a list of items in a list box , a file list box, a drive
list box, and a directory list box. It is provided with a thumb, which moves to and from the extreme left and
right of the scrollbar. You can set the following properties
Name
Min
Max
Value

Represents the name of the scroll bar


The value the scroll bar has when the thumb is at the extreme left.
The value when the thumb is on the extreme right
The current value of the thumb

The Vertical Scrollbar


The Vertical Scrollbar is similar to the horizontal scrollbar except that it is vertically aligned to the form.
The movement of the thumb is upward and downward instead of to the right and left. The Vertical Scrollbar
also has a Min, Max and Value property which can be set and changed to monitor the movement of the
thumb.
Name
Min
Max
Value

Represents the name of the scroll bar


The value the scroll bar has when the thumb is at the extreme left.
The value when the thumb is on the extreme right
The current value of the thumb

The Scrollbar Control Events


The user can change the scrollbars value in 3 ways:
By clicking the arrows at the end. The value changes by the amount specified with the SmallChange
property.
By clicking the area between the indicator and the arrows. The value changes by the amount specified
with the LargeChange property.
By scrolling the indicator with the mouse.
You can monitor the changes on the scrollbars value from within your code with two events:
Change Event: The change event occurs every time the user changes the indicators position and
releases the mouse button. For e.g., if the user clicks on the indicator and holds down the mouse button
while moving the indicator, no change event is triggered. The change event occurs only when the
mouse button is released.
Scroll Event: The scroll event occurs continuously while the indicator is moving. After the mouse
button is releases, the control stops triggering the scroll event and triggers a single change event.
Specifying Colors with RGB() Function
The FromArgb() function enables you to specify colors. The letters RGB stand for Red, Green and Blue.
All colors that can be displayed are generated by mixing these 3 primary colors. The FromArgb() function
has 3 parameters; representing amount of red, green and blue in the final color. The minimum value of each
parameter in the FromArgb() function is 0 and the maximum value is 255.

11

Program 6 Multiplication Program

Form

Name
Text
BorderStyle

Name
Text
WindowState
Label 1
LBLVSB
1-FixedSingle

FRMMULTIPLY
The Multiplication Program
2-Maximized

Label 2
LBLHSB
1-FixedSingle

Label 3
Label1
Result:
1-FixedSingle

HScroll 1

Name
Min
Max

HSBNUM
1
100

VScroll 1

Name
Min
Max

VSBNUM
1
100

Button 1
BTNMULTIPLY
&MULTIPLY

Button 2
BTNX
E&XIT

Name
Text

Label 4
LBLRESULT
1-FixedSingle

Code
Private Sub BTNMULTIPLY_Click( )
LBLRESULT.Text = HSBNUM.Value * VSBNUM.Value
End Sub
Private Sub BTNX_Click( )
End
End Sub
Private Sub Form_Load( )
LBLVSB.Text = VSBNUM.Value
LBLHSB.Text = HSBNUM.Value
End Sub
Private Sub HSBNUM_Scroll( )
LBLHSB.Text = HSBNUM.Value
End Sub

Private Sub VSBNUM_Scroll( )


LBLVSB.Text = VSBNUM.Value
End Sub

12

Program 7 The Scrollbar Program

Form

Name
Text
WindowState

FRMSCROLL
The Scroll Bar Program
2-Maximized

Label 1

Name
Text
BorderStyle

LBLSCROLL
1-FixedSingle

HScroll 1

Name
Min
Max

HSBNUM
1
100

VScroll 1

Name
Min
Max

VSBNUM
1
100

Button 1

Name
Text

BTNX
E&XIT

Code
Private Sub BTNX_Click( )
End
End Sub
Private Sub Form_Load( )
SCROLL
End Sub
Private Sub HSBNUM_Scroll( )
VSBNUM.Value = HSBNUM.Value
SCROLL
End Sub
Private Sub VSBNUM_Scroll( )
HSBNUM.Value = VSBNUM.Value
SCROLL
End Sub
Public Sub SCROLL( )
LBLSCROLL.Text = "VALUE OF VSB : " & Str(VSBNUM.Value) & Chr(13) & _
"VALUE OF HSB : " & Str(HSBNUM.Value)
End Sub

13

Program 8 The RGB () Function

Form

Name
Text
WindowState

FRMRGB
The RGB() Function
2-Maximized

Text

Label 1
Red

Label 2
Green

Label 3
Blue

Name
Min
Max

HScroll 1
HSBRED
0
255

HScroll 2
HSBGREEN
0
255

HScroll 3
HSBBLUE
0
255

Name
Text
BorderStyle

Label 4
LBLHSBR
1-FixedSingle

Label 5
LBLHSBG
1-FixedSingle

Label 6
LBLHSBB
1-FixedSingle

Text

Label 7
Red

Label 8
Green

Label 9
Blue

Name
Min
Max

Trackbar 1
TRKRED
0
255

Trackbar 2
TRKGREEN
0
255

Trackbar 3
TRKBLUE
0
255

Name
Text
BorderStyle

Label 10
LBLTRKR
1-FixedSingle

Label 11
LBLTRKG
1-FixedSingle

Label 12
LBLTRKB
1-FixedSingle

Text

Label 13
Red

Label 14
Green

Label 15
Blue

Name
Min
Max

NumericUpDown 1
UDRED
0
255

NumericUpDown 2
UDGREEN
0
255

NumericUpDown 3
UDBLUE
0
255

14

Name
Text
ReadOnly
Button 1
Code
Private Sub BTNX_Click( )
End
End Sub

Text 1
TXTSCROLL
True

Text 2
TXTTRACK
True

Name
Text

Text 3
TXTUPDOWN
True

BTNX
E&XIT
Private Sub Form_Load( )
SCROLL
SLIDER
UD
End Sub

Public Sub SCROLL( )


LBLHSBR.Text = HSBRed.Value
LBLHSBG.Text = HSBGreen.Value
LBLHSBB.Text = HSBBlue.Value
TXTSCROLL.BackColor = Color.FromArgb(255, HSBRed.Value, HSBGreen.Value, HSBBlue.Value)
End Sub
Public Sub TRACK( )
LBLTRKR.Text = TRKRED.Value
LBLTRKG.Text = TRKGREEN.Value
LBLTRKB.Text = TRKBLUE.Value
TXTTRACK.BackColor = Color.FromArgb(255, TRKRed.Value, TRKGreen.Value, TRKBlue.Value)
End Sub
Private Sub HSBBlue_Scroll( )
SCROLL
End Sub

Private Sub HSBGreen_Scroll( )


SCROLL
End Sub

Private Sub HSBRed_Scroll( )


SCROLL
End Sub

Private Sub TRKBlue_Scroll( )


TRACK
End Sub

Private Sub TRKGreen_Scroll( )


TRACK
End Sub

Private Sub TRKRed_Scroll( )


TRACK
End Sub

Private Sub UDBlue_Change( )


UD
End Sub

Private Sub UDGreen_Change( )


UD
End Sub

Private Sub UDRed_Change( )


UD
End Sub

Public Sub UD( )


TXTUPDOWN.BackColor = Color.FromArgb(255, UDRed.Value, UDGreen.Value, UDBlue.Value)
End Sub

15

5. Control Structures
DECISION MAKING STATEMENTS

If Then Else End If


If <condition> Then
<statementblock>
End If
If <condition1> Then
<statementblock1>
Else
<statementblock2>
End If

If Then ElseIf End If


If <condition1> Then
<statementblock1>
ElseIf <condition2> Then
<statementblock2>
ElseIf <condition3> Then
<statementblock3>
Else
<statementblock4>
End If
The If End If structure tests the condition specified, and executes the statements that follow, if the
condition is True.

Select Case End Select


Select Case <expression>
Case <value1>
<statementblock1>
Case <value2>
<statementblock2>
Case <value3>
<statementblock3>
Case Else
<statementblock4>
End Select
The Select Case End Select structure tests a single expression, which is evaluated once at the top of
the structure. The result of the test is then compared with several values, and if it matches one of them,
the corresponding statements are executed.

LOOP STRUCTURES

Do While Loop
Do while <condition>
<statementblock>
Loop
The Do While Loop executes a block of statements as long as the specified condition is true.

While Wend
While <condition>
<statementblock>
End While

16

Do Loop While
Do
<statementblock>
Loop While <condition>
The statements in this type of loop are executed atleast once, since the condition is executed at the end
of the loop. Then the statements are executed depending upon the specified condition.

For Next
For <variable> = <start value> To <end value> <step value>
<statementblock>
Next
Note: If you accidentally enter an indefinite loop, press Ctrl + Break to exit.

With End With


With <objectname>
<properties>
End With
The With End With structure enables you to set several properties of an object without typing the name of
the object for each property.
Comments
Comments in Visual Basic are written either by adding a single quote () or writing the word REM before
the line.
Option Explicit
This statement tells the compiler to check each variable before using it and to issue an error message if you
attempt to use a variable without declaring it. If you omit the Option Explicit statement, Visual Basic
creates variables as needed.
Tab Order
All windows applications allow the user to move the focus from one control to another with the Tab key.
The order in which the focus moves from one control to another, each time the user presses the tab key is
called as Tab Order. You can use the TabIndex property to change the Tab Order.
If you dont want the user to move to a specific control, you can remove it from the Tab Order by setting its
TabStop property to False.
The members of an option button group have a single TabStop, as only one button can be selected from the
group. Within a group, you can use the arrow keys to select to the next / previous button and deselect the
currently selected button.
Program 9 Control Structures

17

Form

Name
Text
WindowState

FRMSTRUCTURE
Programming Structures
2-Maximized

Name
Text

Button 1
BTNS1
STRUCTURE&1

Button 2
BTNS2
STRUCTURE&2

Button 3
BTNS3
STRUCTURE&3

Name
Text

Button 4
BTNS4
STRUCTURE&4

Button 5
BTNS5
STRUCTURE&5

Button 6
BTNS6
STRUCTURE&6

Name
Text

Button 7
BTNS7
STRUCTURE&7

Button 8
BTNS8
STRUCTURE&8

Button 9
BTNS9
STRUCTURE&9

Button 10
BTNS10
STRUCTURE1&0

Name
Text

Button 11
BTNX
E&XIT

Label1

Name
Text

LBLSTRUC
-

Code
Option Explicit
Private Sub BTNS9_Click( )
LBLSTRUC.Text =
Dim M
M=0
While M < 1 Or M > 12
M = InputBox("ENTER A NUMBER")
End While
LBLSTRUC.Text "YOU HAVE CHOSEN THE MONTH: " & Choose(M, "JANUARY", _
"FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", _
"OCTOBER", "NOVEMBER", "DECEMBER")
End Sub
Private Sub BTNS10_Click( )
LBLSTRUC.Text =
Dim NAMEARRAY(6)
NAMEARRAY(0) = "A"
NAMEARRAY(1) = "R"
NAMEARRAY(2) = "C"
NAMEARRAY(3) = "H"
NAMEARRAY(4) = "A"
NAMEARRAY(5) = "N"
NAMEARRAY(6) = "A"
Dim CTR, NO
NO = 1
For Each CTR In NAMEARRAY
LBLSTRUC.Text = LBLSTRUC.Text & Chr (13) & "Character " + Str(NO) & " of your name is " & CTR
NO = NO + 1
Next
End Sub

18

Private Sub BTNS1_Click( )


LBLSTRUC.Text =
Dim I
I=1
Do While I <= 25
LBLSTRUC.Text = LBLSTRUC.Text & _
Chr (13) & I
I=I+1
Loop
End Sub

Private Sub BTNS2_Click( )


LBLSTRUC.Text =
Dim I
I = 50
Do
LBLSTRUC.Text = LBLSTRUC.Text & _
Chr (13) & I
Loop While I <= 25
End Sub

Private Sub BTNS3_Click( )


LBLSTRUC.Text =
Dim I
For I = 1 To 50 Step 2
LBLSTRUC.Text = LBLSTRUC.Text & _
Chr (13) & I
Next
End Sub

Private Sub BTNS4_Click( )


LBLSTRUC.Text =
Dim I
For I = 1 To 50
LBLSTRUC.Text = LBLSTRUC.Text & _
Chr (13) & I
If I = 25 Then
Exit For
End If
Next
End Sub

Private Sub BTNS5_Click( )


LBLSTRUC.Text =
Dim I
I=1
Do While I <= 50
I=I+1
LBLSTRUC.Text = LBLSTRUC.Text & _
Chr (13) & I
If I = 30 Then
Exit Do
End If
Loop
End Sub

Private Sub BTNS6_Click( )


LBLSTRUC.Text =
Dim I
I=1
Do While I <= 50
LBLSTRUC.Text = LBLSTRUC.Text & _
Chr (13) & I
I=I+1
If I = 30 Then
Exit Do
End If
Loop
End Sub

Private Sub BTNS7_Click( )


LBLSTRUC.Text =
Dim I
I=1
While I <= 20
LBLSTRUC.Text = LBLSTRUC.Text & _
Chr (13) & I
I=I+1
End While
End Sub

Private Sub BTNS8_Click( )


Dim INTVALUE, INTABSVALUE
INTVALUE = InputBox("ENTER A
NUMBER")
If Not IsNumeric(INTVALUE) Then
MsgBox "NOT A VALID NUMBER"
Exit Sub
Else
INTABSVALUE = IIF(INTVALUE < 0, -1 *
INTVALUE, INTVALUE)
LBLSTRUC.Text = "ABSOLUTE VALUE =
" & Str(INTABSVALUE)
End If
End Sub

Private Sub BTNX_Click( )


End
End Sub

19

Assignment

The value of the scrollbar should be displayed in the label below it. When you click on the SUM IT button,
the RESULT label should display the result as 1 + 2 + 3 + + scrollbar value.

20

6. Mouse Events
Client Area
The unutilized area enclosed by the Title bar of the form and the edges of the form window is called as the
client area.
QBColor() Function
The QBColor() function is used to specify colors. It has only one parameter that takes any integer value
from 0 15. i.e., it generates 16 colors. Following is the QBColor () Chart
Value
0
1
2
3
4
5
6
7

Color
Black
Blue
Green
Cyan
Red
Magenta
Yellow
White

Value
8
9
10
11
12
13
14
15

Color
Gray
Light Blue
Light Green
Light Cyan
Light Red
Light Magenta
Light Yellow
Bright White

Program 10 The Mouse Events Program

Form

Name
Text
WindowState

FRMMOUSE
The Mouse Events Program
2-Maximized

Label 1

Name
Text
BorderStyle

LBLMOUSE
1-FixedSingle

Button 1

Name
Text

BTNX
E&XIT

Code
Private Sub BTNX_Click( )
End
End Sub
Private Sub Form_MouseDown( )
If e.Button = Windows.Forms.MouseButtons.Left Then
LBLMOUSE.Text = "YOU HAVE PRESSED THE LEFT BUTTON"
End If
If e.Button = Windows.Forms.MouseButtons.Right Then
LBLMOUSE.Text = "YOU HAVE PRESSED THE RIGHT BUTTON"
End If
If e.Button = Windows.Forms.MouseButtons.Middle Then
LBLMOUSE.Text = "YOU HAVE PRESSED THE MIDDLE BUTTON"
End If
End Sub

21

Private Sub Form_MouseMove( )


If e.Button = Windows.Forms.MouseButtons.Left Then
LBLMOUSE.Text = "YOU ARE MOVING THE LEFT BUTTON"
End If
If e.Button = Windows.Forms.MouseButtons.Right Then
LBLMOUSE.Text = "YOU ARE MOVING THE RIGHT BUTTON"
End If
If e.Button = Windows.Forms.MouseButtons.Middle Then
LBLMOUSE.Text = "YOU ARE MOVING THE MIDDLE BUTTON"
End If
End Sub
Private Sub Form_MouseUp( )
If e.Button = Windows.Forms.MouseButtons.Left Then
LBLMOUSE.Text = "YOU HAVE RELEASED THE LEFT BUTTON"
End If
If e.Button = Windows.Forms.MouseButtons.Right Then
LBLMOUSE.Text = "YOU HAVE RELEASED THE RIGHT BUTTON"
End If
If e.Button = Windows.Forms.MouseButtons.Middle Then
LBLMOUSE.Text = "YOU HAVE RELEASED THE MIDDLE BUTTON"
End If
End Sub

7. Keyboard Events

KeyDown: The KeyDown event occurs when you press any of the keys on the keyboard.

22

KeyUp: The KeyUp event occurs when you release the pressed key.
KeyPress: The KeyPress event occurs when you press a key that has a corresponding Ascii character.
For e.g., if you press the function key F1, the KeyPress event does not occur, but if you press the A
key, the KeyPress event takes place.

Parameters of Keyboard Events


The KeyDown and KeyUp events have 2 parameters:

KeyCode: It is an integer that represents the pressed / released key.


Shift: This parameter represents the state of Shift key.

The KeyPress Event has only one parameter

KeyChar: It represents the character value of the pressed key.

Chr() Function
The Chr() function converts the integer KeyAscii to a character value.
Asc() Function
The Asc() function returns an integer that represents the Ascii value of the pressed key.
KeyPreview Property
A form can have the keyboard focus if there are no controls on it or if the controls are disabled. However in
most programs, a form does have some enabled controls on it, so the Form_KeyDown, Form_KepUp and
Form_KeyPress procedures are not executed.
To force the execution of these procedures, even when the form does not have the keyboard focus, set the
KeyPreview property of the form to True. The KeyPreview property enables the program to trap or preview
the keyboard events.
Program 11 The Keyboard Events

Form

Name
Text
BorderStyle
Button 1

Name
Text
WindowState
KeyPreview

FRMKEY
The Keyboard Events
2-Maximized
True

Label 1
LBLKEY
1-FixedSingle

Label 2
LBLASCII
1-FixedSingle

Name
Text

BTNX
E&XIT

Code
Private Sub BTNX_Click( )
End

23

End Sub
Private Sub Form_KeyDown( )
LBLKEY.Text = "THE KAY HAS BEEN PRESSED" + Chr(13) + _
"KEYCODE =" + Str(e.KeyCode) + Chr(13) + "SHIFT:" + Str(e.Shift)
End Sub
Private Sub Form_KeyPress( )
Dim C As String
C = e.KeyChar
LBLASCII.Text = "THE KEY HAS BEEN PRESSED" & Chr(13) & _
"ASCII VALUE=" & Asc(C) & Chr(13) & "CHARACTER=" & C
End Sub
Private Sub Form_KeyUp( )
LBLKEY.Text = "THE KAY HAS BEEN RELEASED" + Chr(13) + _
"KEYCODE =" + Str(e.KeyCode) + Chr(13) + "SHIFT:" + Str(e.Shift)
End Sub
Program 12 The Caps Lock Program

Form

Name
Text
WindowState

FRMCAPS
The CapsLock Program
2-Maximized

Text 1

Name
Text
MultiLine

TXTCAPS
True

Button 3

Name
Text

BTNX
E&XIT

Code
Private Sub BTNX_Click()
End
End Sub
Private Sub TXTCAPS_KeyPress(KeyAscii As Integer)
Dim C AS String
C = e.KeyChar
e.KeyChar = UCase(C)
End Sub
Program 13 The Validation Program

24

Form

Name
Text
WindowState

FRMVALID
The Validation Program
2-Maximized

AutoSize

Label 1
Enter Only
Numbers
True

Label 2
Enter Only Lower
Case Characters
True

Label 3
Enter Only Upper
Case Characters
True

Name
Text

Text 1
TXTNUM
-

Text 2
TXTLCASE
-

Text 2
TXTUCASE
-

Text

Button 1

Name
Text

BTNX
E&XIT

Code
Private Sub BTNX_Click()
End
End Sub
Private Sub TXTLCASE_KeyPress(KeyAscii As Integer)
If Asc(e.KeyChar) < 97 Or Asc(e.KeyChar) > 122 Then
e.KeyChar = Chr(0)
End If
End Sub
Private Sub TXTNUM_KeyPress(KeyAscii As Integer)
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 56 Then
e.KeyChar = Chr(0)
End If
End Sub
Private Sub TXTUCASE_KeyPress(KeyAscii As Integer)
If Asc(e.KeyChar) < 65 Or Asc(e.KeyChar) > 90 Then
e.KeyChar = Chr(0)
End If
End Sub

25

8. Dialog Boxes
Dialog boxes are used to display and accept information from the user.
There are 3 types of dialog boxes

Pre-defined

MsgBox

Custom

Common

InputBox

Pre-defined Dialog Boxes


As the name implies, pre-defined dialog boxes are pre-defined by Visual Basic. To display a pre-defined
dialog box, you have to use Visual Basic statements with parameters that specify how and when the dialog
box should appear. You can display a pre-defined dialog box using:

MsgBox
It takes 3 parameters the message to be displayed, the buttons / icons to be displayed and the title for
the dialog box, respectively.
It can be used in two ways

Statement
{It is used to display
messages only}

Function
{It is used for accepting some
information from the user and
storing it in a variable for
processing}

further
Button Constants for MsgBox
Button Constant
vbOKOnly
vbOKCancel
vbAbortRetryIgnore
vbYesNoCancel
vbYesNo
vbRetryCancel

0
1
2
3
4
5

Button Constants for MsgBox


Icon Constant
vbCritical
vbQuestion
vbExclamation
vbInformation

16
32
48
64

Value

Displayed Button
OK
OK, Cancel
Abort, Retry, Ignore
Yes, No, Cancel
Yes, No
Retry, Cancel

Value

Displayed Icon

Possible Return Values from the MsgBox() Function


Button Constant
Value
vbOK
1
vbCancel
2
vbAbort
3
vbRetry
4
vbIgnore
5
vbYes
6
vbNo
7

Clicked Button
OK
Cancel
Abort
Retry
Ignore
Yes
No

26

InputBox() Function
InputBox() function can be used to accept information from the user. The InputBox() function displays
a dialog box with a message, a text box and buttons for OK and Cancel. The user has to type the
information in the text box. The first parameter is the message of the dialog box and the second
parameter is the title of the dialog box. You can also use some optional parameters with the InputBox()
function. The third parameter specifies the default string that appears in the text box of the dialog box.
The fourth and fifth parameters specify the X and Y co-ordinates at which the dialog box should be
displayed.

Custom Dialog Boxes


Custom dialog boxes are customized / designed by the user as opposed to pre-defined dialog boxes that
only let you customize limited things like buttons and icons in the dialog box. Designing a custom dialog
box is the same as designing a form. In fact, a custom dialog box is a regular form used to display and
accept information from the user.
Cancel and Default Properties
Setting the Cancel property of a Button button to True, makes this button the default cancel button, i.e., the
button which is considered to be clicked when the user presses the Esc key.
Setting the Default property of a Button button to True, makes this button the default button, i.e., the button
which is considered to be clicked when the user presses the Enter key.
Tag Property
Tag property is used to store the information passed back from a form.
Common Dialog Boxes
All Windows application use some standard dialog boxes for common operations such as selecting a font or
opening a file. These dialog boxes are built in the operating system and any application can use them. The
Microsoft Common Windows Dialog Controls provides the following built-in Windows dialog boxes.
Method
ShowOpen
ShowSave
ShowColor
ShowFont
ShowPrinter
ShowHelp

Value
1
2
3
4
5
6

Dialog Box
Open
Save
Color
Font
Print
Help

CancelError Property
Each dialog box has a Cancel button, which should notify the application the users intention to cancel the
current operation. The cancel action can be reported by means of an error. To specify whether an error is
generated when the user clicks the Cancel button, set the CancelError property of the common dialog
control to True.
If you set the CancelError property to True, you must also provide an error handler, that will detect this
condition and act accordingly.
Format() Function
Date Stores current date
Time Stores current time
Now Stores current date and time

27

Date and Time Format Strings


String
d
dd
ddd
dddd
h
hh
H
HH
m
mm
M
MM
MMM
MMMM
s
ss
AM/PM
y
yy
yyyy

Description
The one or two-digit day
The two-digit day. Single digit day values will be preceded by a zero
The three character day-of-week abbreviation
The full day-of-week name
The one or two-digit hour in 12-hour format
The two-digit hour in 12-hour format. Single digit values will be preceded by a zero
The one or two-digit hour in 24-hour format
The two-digit hour in 24-hour format. Single digit values will be preceded by a zero
The one or two-digit minute
The two-digit minute. Single digit values will be preceded by a zero
The one or two-digit month number
The two-digit month number. Single digit values will be preceded by a zero
The three character month abbreviation
The full month name
The one or two-digit second
The two-digit seconds. Single digit values will be preceded by a zero
The two-letter AM/PM abbreviation
The one-digit year (i.e., 1999 will be displayed as 9)
The last two digits of the year (i.e., 1999 will be displayed as 99)
The full year

Program 14 The MsgBox Program

Form

Name
Text

Name
Text
WindowState

FRMMSG
The Message Box Program
2-Maximized

Button 1
BTNMSG
&MESSAGE

Button 2
BTNX
E&XIT

Code
Private Sub BTNMSG_Click()
Dim MSG As String
Dim BTN As Integer
Dim TIT As String
MSG = "THIS IS A TRIAL MESSAGE"
BTN = vbExclamation + vbOKOnly
TIT = "TRY"
MsgBox MSG, BTN, TIT
End Sub

Private Sub BTNX_Click()


Dim MSG As String
Dim BTN As Integer
Dim ANS As Integer
Dim TIT As String
MSG = "Are you sure you want to quit?"
TIT = "EXIT"
BTN = vbYesNo + vbQuestion
ANS = MsgBox(MSG, BTN, TIT)
If ANS = vbYes Then
End
End If
End Sub

28

Program 15 The InputBox () Program

Form

Name
Text

Name
Text
WindowState
Button 1
BTNNAME
&NAME

Button 2
BTNAGE
&AGE

FRMINPUT
The Input Box Program
2-Maximized
Button 3
Button 4
BTNDOB
BTNX
&DATE OF BIRTH E&XIT

Code
Private Sub BTNAGE_Click()
Dim AGE
AGE = InputBox("ENTER YOUR AGE:", "AGE INPUTBOX")
If AGE = "" Then
MsgBox "PLEASE ENTER YOUR AGE"
Exit Sub
End If
If Not IsNumeric(AGE) Then
MsgBox "PLEASE ENTER ONLY DIGITS"
Exit Sub
End If
MsgBox "YOUR AGE IS " + Str(AGE)
End Sub
Private Sub BTNDOB_Click()
Dim DT As Date
Dim MSG, DOFW
DT = InputBox("ENTERYOUR DOB:", "DOB INPUTBOX")
If Not IsDate(DT) Then
MsgBox "INVALID DATE"
Exit Sub
End If
DOFW = Format(DT, "dddd")
MSG = "YOUR DOB IS:" + DT + Chr(13) + Chr(10) + "DAY OF THE WEEK:" + DOFW
MsgBox MSG, vbInformation + vbOKOnly, "DATE CONFIRMATION"
End Sub
Private Sub BTNNAME_Click()
Dim NAME
NAME = InputBox("ENTER YOUR NAME:", "NAME INPUTBOX")
If NAME = "" Then
MsgBox "PLEASE ENTER YOUR NAME"
Else
MsgBox "HELLO " + NAME
End If
End Sub
Program 16 The Custom Dialog Box Program

29

Form

Name
Text
Form

Name
Text

Name
Text
WindowState

FRMCUSTOM
The Custom Dialog Box Program
2-Maximized

Button 1
BTNCOUNTRY
&SELECT COUNTRY

Button 2
BTNX
E&XIT

Name
Text
Control Box

FRMCOUNTRY
Select the Country
False

Option 1
Option 2
OPTAUS
OPTSWIT
&AUSTRALIA &SWITZERLAND

Name
Text

Option3
OPTCAN
&CANADA

Button 1
BTNOK
&OK

Option4
Option5
OPTMAU
OPTUK
&MAURITIUS &UK

Button 2
BTNCANCEL
&CANCEL

Code
Private Sub BTNCOUNTRY_Click()
FRMCOUNTRY.ShowDialog ( )
If FRMCOUNTRY.Tag = "" Then
MsgBox "OH!SO YOU DON'T WANT TO GO FOR A VACATION"
Else
MsgBox "ENJOY YOUR VACATION TO " + FRMCOUNTRY.Tag
End If
End Sub
Private Sub BTNX_Click()
End
End Sub
Private Sub BTNCANCEL_Click()
Me.Tag = ""
Me.Hide
End Sub
Private Sub BTNOK_Click()
If OPTAUS.Checked = True Then Me.Tag = "AUSTRALIA"
If OPTSWIT.Checked = True Then Me.Tag = "SWITZERLAND"
If OPTCAN.Checked = True Then Me.Tag = "CANADA"
If OPTMAU.Checked = True Then Me.Tag = "MAURITIUS"
If OPTUK.Checked = True Then Me.Tag = "UK"
Me.Hide
End Sub

30

9. List Box & Combo Box


The List Box
The List box is similar to the combo but differs in the sense that the user cannot edit any value displayed ,
nor can he manually add an item to the list of strings at runtime . Some of the common properties are
Name
List

The name used to identify the list box


The user can enter a list of items at design time.

The Combo Box


The Combo is a combination of a textbox and a list box. You can enter text in the combo as well as display
a list of strings from which a particular item can be selected. Some of the common properties are
Name
Text
Editable
List

The name of the Combo Box


The text displayed in the edit area of the Combo Box
Indicates that the user can edit or changer the values displayed in the combo.
The user can enter a list of items at design time itself

Program 17 The List Box Program

Form

Name
Text
WindowState

FRMLIST
The List Box Program
2-Maximized

Label 1
Enter a Name

Label 2
List of Names

Text 1

Name
Text

TXTNAME
-

List 1

Name

LSTNAMES

Text

Name
Text
Button 5

Button 1
BTNADD
&ADD
Name
Text

Button 2
BTNREMOVE
&REMOVE

Button 3
BTNCLEAR
&CLEAR

Button 4
BTNCOUNT
C&OUNT

BTNX
E&XIT

31

32

Code
Private Sub BTNADD_Click()
If TXTNAME.Text = "" Then
MsgBox "Please enter a name"
TXTNAME.SetFocus
Exit Sub
End If
LSTNAMES.Items.Add (TXTNAME.Text)
BTNCLEAR.Enabled = True
BTNREMOVE.Enabled = True
TXTNAME.Text = ""
TXTNAME.Focus ( )
End Sub
Private Sub BTNCOUNT_Click()
MsgBox " Total no. of names in the list:" + Str(LSTNAME.Items.Count)
End Sub
Private Sub BTNCLEAR_Click()
LSTNAMES.Items.Clear( )
BTNREMOVE.Enabled = False
BTNCLEAR.Enabled = False
End Sub
Private Sub BTNREMOVE_Click()
If LSTNAMES.SelectedItem = Then
MsgBox "PLEASE SELECT THE NAME TO REMOVE"
Exit Sub
End If
LSTNAME.Items.Remove (LSTNAMES.SelectedItem)
If LSTNAMES.Items.Count = 0 Then
BTNREMOVE.Enabled = False
BTNCLEAR.Enabled = False
End If
TXTNAME.Text = ""
End Sub
Private Sub BTNX_Click()
End
End Sub
Private Sub Form_Load()
FRMLIST.WindowState = 2
BTNREM.Enabled = False
BTNCL.Enabled = False
End Sub
Private Sub LSTNAMES_SelectedIndexChanged()
TXTNAME.Text = LSTNAMES.SelectedItem
End Sub

33

Program 18 The Double List Program

Form

Name
Items
Button 1

Name
Text
WindowState

FRMDL
The List Box Program
2-Maximized

List 1
LST1
A, B, C, D, E

List 2
LST2
1, 2, 3, 4, 5

Name
Text

BTNX
E&XIT

Code
Private Sub BTNX_Click()
End
End Sub
Private Sub LST1_DoubleClick()
LST2.Items.Add (LST1.SelectedItem)
LST1..Items.Remove (LST1. SelectedItem)
End Sub

Private Sub LST2_DoubleClick()


LST1.Items.Add (LST2.SelectedItem)
LST2..Items.Remove (LST2. SelectedItem)
End Sub

Program 19 The Combo Box Program

Form

Name
Text
WindowState

FRMCOMBO
The Combo Box Program
2-Maximized

Text 1

Name
TextAlignment
Font
ReadOnly
Text

TXTCOMBO
2-Center
Change if Reqd.
True
Visual Basic

Label 1
ForeColor
Combo 1

Label 2
BackColor
Combo 2

Text

34

Name
Items

CMBFC
Any 5 colors

CMBBC
Any 5 colors

Button 1

Name
Text

BTNX
E&XIT

Code
Private Sub CMBBC_SelectedIndexChanged()
Select Case CMBBC.Text
Case "WHITE"
TXTCOMBO.BackColor = Color.White
Case "BLACK"
TXTCOMBO.BackColor = Color.Black
Case "RED"
TXTCOMBO.BackColor = Color.bRed
Case "GREEN"
TXTCOMBO.BackColor = Color.Green
Case "BLUE"
TXTCOMBO.BackColor = Color.Blue
Case "CYAN"
TXTCOMBO.BackColor = Color.Cyan
End Select
End Sub
Private Sub BTNX_Click()
End
End Sub
Private Sub Form_Load()

Private Sub CMBFC_Click()


Select Case CMBFC.Text
Case "WHITE"
TXTCOMBO.ForeColor = Color.White
Case "BLACK"
TXTCOMBO.ForeColor = Color.Black
Case "RED"
TXTCOMBO.ForeColor = Color.Red
Case "GREEN"
TXTCOMBO.ForeColor = Color.Green
Case "BLUE"
TXTCOMBO.ForeColor = Color.Blue
Case "CYAN"
TXTCOMBO.ForeColor = Color.Cyan
End Select
End Sub
CMBFC.SelectedIndex = 0
CMBBC. SelectedIndex = O
End Sub

35

10. Focus
FOCUS
The 3 types of focus are

GotFocus: i.e., when the focus moves to the object.


LostFocus: i.e., when the focus moves away from the object.
SetFocus: i.e., the focus should move to the object.

Program 20 The Focus Program

Form

Name
Text
WindowState

FRMFOCUS
The Focus Program
2-Maximized

Text 1

Name
Text

TXTFOCUS
-

Name
Text
BorderStyle

Label 1
Do not change
FOCUS
Do not change

Label 2
LBLFOCUS
1-FixedSingle

Name
Text

Button 1
Do not change
-

Button 2
BTNX
E&XIT

Code
Private Sub BTNX_Click()
End
End Sub
Private Sub TXTFOCUS_GotFocus()
LBLFOCUS.Text = "The text box has the focus"
End Sub

Private Sub TXTFOCUS_LostFocus()


If TXTFOCUS.Text = "" Then
MsgBox "PLEASE ENTER SOME TEXT"
TXTFOCUS. Focus ( )
Else
LBLF.OCUSText = TXTFOCUS.Text
End If
End Sub

36

11. Timer Control


The Timer is an interesting control of Visual Basic which is not displayed at run time, but instead it helps
the program by executing a piece of code given in its Timer() event every few seconds or as given in the
time interval property of the timer. The properties listed below will help you in understanding the Sample
Program that follows. Some of the properties are
Name
Enabled
Interval

The name of the timer control


If the timer is enabled then just like a clock it checks for the condition every few
seconds and then acts accordingly as specified by the programmer.
The time interval in milliseconds.

Pset Method
The Pset Method draws a point at the X, Y co-ordinate that is specified by its parameter. The Pset method
has an optional parameter called Step, which draws the point in relation to the CurrentX and CurrentY coordinates. For e.g., if CurrentX = 100 and CurrentY = 50, if you issue the statement
Form1.Pset Step (10,20)
A point is drawn at 110, 70, i.e., 10 units to the right of CurrentX and 20 units below CurrentY. The values
of CurrentX and CurrentY are automatically updated to 110 and 70 respectively.
Program 21 The Timer Control Program

Form

Name
Text
WindowState

FRMCLOCK
The Clock Program
2-Maximized

Label 1

Name
Text
BorderStyle
Font

LBLCLOCK
1-FixedSingle
Size - 24

Timer 1

Name
Interval
Enabled

TMRCLOCK
1000
True

Code
Private Sub TMRCLOCK_Tick()
LBLCLOCK.Text = "TIME: " & Format(Now, "hh:mm:ss tt") & Chr(13) _
& "DATE: " & Format(Now, "dd/mm/yyyy")
End Sub

37

12. Arrays
Data Types
Data Type
Byte
Integer
Long
Single Positive
Single Negative
Double Positive
Double Negative
Currency
String
Date
Boolean
Variant
E.g.
Or

Shortcut Notation
%
&
!
!
#
#
@
$

Range
0 To 255
-32768 To 32767
-2,147,483,648 To 2,147,483,647
1.401298E-45 To 3.402823E-38
- 3.402823E-38 To -1.401298E-45
4.94065645841247D-24 To 1.79769313486232D308
-1.79769313486232D308 To - 4.94065645841247D-24
-922337203685477.5808 To 922337203685477.5807
Up to 2 billion characters
1/1/0000 To 31/12/9999
Logical Values
Any of the above types

Dim N As Integer
Dim N%

ARRAYS
The declaration of an array specifies the arrays name and the maximum number of elements it can hold.
All elements in an array must have the same data type. If the data type is variant, individual elements can
contain different kinds of data.
By default, the first element of an array has index 0. The number that appears in parentheses in the Dim
statement is the arrays upper limit and is one less than the arrays total capacity.
E.g.
1.

Dim A(15) As Integer


The above array contains 16 elements with index 0 for the first element and index 15 for the last
(16th) element.

2.

Dim A(10 To 15) As Integer


The above array contains 6 elements with index 10 for the first element and index 15 for the last
(6th) element.

Static Variables
After you declare a static variable and you execute the program for the first time, Visual Basic sets the
value to 0. During the execution of a procedure, the value of the static variable changes to another value.
When the procedure is executed again, the value of non-static variable is initialized back to zero. But it is
not so for static variables.
There is a similarity between a variable declares in the general declaration area and a variable declared as a
static variable in a procedure. In both cases, the variable retains it value as long as the program is in the
execution stage. The difference is that a general variable is accessible to any procedure, whereas a static
variable is accessible only to the procedure which declares it.
Dynamic Arrays
Sometimes, after creating the array you may want to change its size. This is possible if you create a
dynamic array. A dynamic array can be resized at run time using the Redim Statement. A dynamic array is
defined in the general declaration area of the form without specifying the upper and lower bounds.

38

Preserve Keyword
It is used to change the size of the array without losing the data in it, i.e., it redefines the array by
preserving the elements of the previously defined (resized) array.
Control Array
A control array is an array of controls, sharing the same name, type and event procedures. A control array
has atleast one element and can grow to any number of elements depending on the memory and resources.
Each element of a control array has its own property settings. Control arrays can consist of elements of the
same type only. For e.g., a Button button and a text box cannot be part of the same control array. A control
array can be created in two ways by assigning the same name to more than one control or copying the
existing control and pasting it on the same form.
Program 22 The Digit Conversion Program

Form

Name
Text
WindowState

FRMDIGITS
The Conversion Program
2-Maximized

Text 1

Name
Text

TXTDIGITS
-

Label 1
Do not change
Enter a Number
Do not change
True

Label 2
LBLDIGITS
1-Fixed Single
False

Name
Text
BorderStyle
AutoSize
Name
Text

Button 1
BTNOK
&OK

Code
Dim DIGITS(9) As String
Private Sub CMBTNCLEAR_Click()
LBLDIGITS.Text = " "
TXTDIGITS.Text = " "
TXTDIGITS.Focus ( )
End Sub
Private Sub BTNEXIT_Click()
End
End Sub
Private Sub BTNOK_Click()

Button 2
BTNCLEAR
&CLEAR

Button 3
BTNX
E &XIT

Private Sub Form_Load()


DIGITS(0) = "ZERO"
DIGITS(1) = "ONE"
DIGITS(2) = "TWO"
DIGITS(3) = "THREE"
DIGITS(4) = "FOUR"
DIGITS(5) = "FIVE"
DIGITS(6) = "SIX"
DIGITS(7) = "SEVEN"
DIGITS(8) = "EIGHT"
DIGITS(9) = "NINE"
End Sub
If Not IsNumeric(TXTDIGITS.Text) Then

39

MsgBox "INVALID NUMBER"


TXTDIGITS.Text = " "
TXTDIGITS.Focus ( )
Else
Dim N, L, CTR
N = TXTDIGITS.Text
L = Len(N)

For CTR = 1 To L
LBLDIGITS.Text = LBLDIGITS.Text & " "
& DIGITS(Mid(N, CTR, 1))
Next
End If
End Sub

Program 23 The Control Array Program

Form

Name
Text
WindowState

FRMMOON
The Moon Program
2-Maximized

Path for Images: C:\Program Files\Microsoft Visual Studio\Common\Graphics\Icons\Elements


ImageList1
Images
Moon01 to Moon08
PictureBox1

Name

IMGMOON

Name
Text

Button 1
BTNSTART
&START

Button 2
BTNX
E&XIT

Name
Interval
Enabled

TMRMOON
250
True

Timer 1

Code
Option Explicit
Dim GMOON, GCM
Private Sub BTNS_Click()
If GMOON = 0 Then
GMOON = 1
BTNSTART.Text = "&STOP"
Else
GMOON = 0
BTNSTART.Text = "&START"
End If
End Sub
Private Sub BTNX_Click()
End
End Sub

Private Sub Form_Load()


GMOON = 0
GCM = 0
End Sub
Private Sub Timer1_Timer()
If GMOON = 1 Then
IMGMOON.Image = ImageList1.Images(GCM)
GCM = GCM + 1
If GCM = 8 Then
GCM = 0
End If
End If
End Sub

40

13. Menus
Program 24 The Menu Program

Form

MenuStrip
Name
MNUFILE
MNUCOLOR
MNURED
MNUGREEN
MNUBLUE
MNUWHITE
MNUCYAN
MNUX
MNUSIZE
MNUNOR
MNUMIN
MNUNOR

Name
Text
WindowState

FRMMENU
The Menu Program
2-Maximized

Text
&FILE
&COLOR
&RED
&GREEN
&BLUE
&WHITE
&CYAN
E&XIT
&SIZE
&NORMAL
&MINIMIZE
MAXIMI&ZE

Shortcut
Ctrl +R
Ctrl +G
Ctrl +B
Ctrl +W
Ctrl +C
Ctrl+X
Ctrl+N
Ctrl+M
Ctrl+Z

Code
Private Sub MNUBlue_Click()
Me.BackColor = Color.Blue
End Sub

Private Sub MNUMIN_Click()


Me.WindowState = Form.WindowState.Minimized
End Sub

Private Sub MNUCyan_Click()


Me.BackColor = Color.Cyan
End Sub

Private Sub MNUNOR_Click()


Me.WindowState = Form.WindowState.Normal
End Sub

Private Sub MNUGreen_Click()


Me.BackColor = Color.Green
End Sub

Private Sub MNURed_Click()


Me.BackColor = Color.Red
End Sub

Private Sub MNUWhite_Click()


Me.BackColor = Color.White
End Sub

Private Sub MNUX_Click()


End
End Sub

Private Sub MNUMAX_Click()


Me.WindowState = Form.WindowState.Maxmized
End Sub

41

Program 25 The Menu Program

Form

Name
Text
WindowState

Menu
Name
MNUFILE
MNUARRAY
MNUS1
MNUDIGITS
MNUS2
MNUDA
MNUS3
MNUMOON
MNUS4
MNUX

FRMMENUARR
The Menu Program
2-Maximized

Text
&FILE
&ARRAY
&DIGITS
&DYNAMIC ARRAY
&MOON
E&XIT

Code
Private Sub MNUARRAY_Click()
Me.Hide
FRMARRAY.Show
End Sub

Private Sub MNUDA_Click()


Me.Hide
FRMDA.Show
End Sub

Private Sub MNUDIGITS_Click()


Me.Hide
FRMDIGIT.Show
End Sub

Private Sub MNUMOON_Click()


Me.Hide
FRMMOON.Show
End Sub

Private Sub MNUX_Click()


End
End Sub
'FOR THE CODE OF BTNX OF THE ABOVE FORMS WRITE THE CODE
'FRMMENUARR.SHOW
'HIDE THE RESPECTIVE FORM
Program 34 The Popup Menu Program
Form

ContextMenuStrip
Name
MNUSAVE
MNUPRINT

(No form design)


Name
Text
WindowState
ContextMenuStrip

FRMPM
The Popup Menu Program
2-Maximized
ContextMenuStrip1

Text
&SAVE
&PRINT

42

Code
Private Sub Form_MouseUp( )
If e.Button = Windows.Forms.MouseButtons.Right Then
Me.ContextMenuStrip1.Show ( )
End If
End Sub
Private Sub MNUPRINT_Click()
MsgBox "You have selected the print option"
End Sub

Private Sub MNUSAVE_Click()


MsgBox "You have selected the save option"
End Sub

Program 26 The Text Editor Program

Form

Menu
Name
MNUFILE
MNUX
MNUEDIT
MNUCUT
MNUCOPY
MNUPASTE
MNUFONT
MNUBOLD
MNUITALIC
MNUUNDERLINE
MNUREGULAR

Name
Text
WindowState
Text
&FILE
E&XIT
&EDIT
CU&T
&COPY
&PASTE
&FONT
&BOLD
&ITALIC
&UNDERLINE
&REGULAR

TextBox1
Multiline
Place it at the top left corner below the menu bar
Code
Dim B, I, U
Private Sub Form_Resize( )
TextBox1.Width = Me.Width
TextBox1.Height = Me.Height
End Sub
Private Sub MNUBold_Click()
If B = True Then
B = False
mnuBold.Checked = False
Else
B = True
mnuBold.Checked = True
End If
FontStyle ( )

FRMTEXT
The Text Editor
2-Maximized

True

Private Sub Form_Load( )


B = False
I = False
U = False
End Sub
End Sub
Private Sub MNUItalic_Click()
If I = True Then
I = False
mnuItalic.Checked = False
Else
I = True
mnuItalic.Checked = True
End If

43

FontStyle ( )

End Sub

Private Sub MNURegular_Click()


B = False
I = False
U = False
mnuBold.Checked = False
mnuItalic.Checked = False
mnuUnderline.Checked = False
FontStyle ( )
End Sub

Private Sub MNUUnderline_Click()


If U = True Then
U = False
mnuUnderline.Checked = False
Else
U = True
mnuUnderline.Checked = True
End If
FontStyle ( )
End Sub

Private Sub MNUCOPY_Click()


Clipboard.Clear ( )
Clipboard.SetText (TextBox1.SelectedText)
End Sub

Private Sub MNUX_Click()


End
End Sub

Private Sub MNUCUT_Click()


Clipboard.Clear ( )
Clipboard.SetText (TextBox1. SelectedText)
TextBox1. SelectedText = ""
End Sub

Private Sub MNUPASTE_Click()


TextBox1. SelectedText = Clipboard.GetText
End Sub

Public Sub FontStyle ( )


If B = True And I = True And U = True Then
TextBox1.Font = New Font (TextBox1.Font.FontFamily, TextBox1.Font.Size, Drawing.FontStyle.Bold Or _
Drawing. FontStyle.Italic Or Drawing. FontStyle.Underline)
End If
If B = True And I = True And U = False Then
TextBox1.Font = New Font (TextBox1.Font.FontFamily, TextBox1.Font.Size, Drawing. FontStyle.Bold Or _
Drawing. FontStyle.Italic)
End If
If B = True And I = False And U = True Then
TextBox1.Font = New Font (TextBox1.Font.FontFamily, TextBox1.Font.Size, Drawing. FontStyle.Bold Or _
Drawing. FontStyle.Underline)
End If
If B = False And I = True And U = True Then
TextBox1.Font = New Font (TextBox1.Font.FontFamily, TextBox1.Font.Size, Drawing. FontStyle.Italic Or _
Drawing. FontStyle.Underline)
End If
If B = True And I = False And U = False Then
TextBox1.Font = New Font (TextBox1.Font.FontFamily, TextBox1.Font.Size, Drawing. FontStyle.Bold)
End If
If B = False And I = True And U = False Then
TextBox1.Font = New Font (TextBox1.Font.FontFamily, TextBox1.Font.Size, Drawing. FontStyle.Italic)
End If
If B = False And I = False And U = True Then
TextBox1.Font = New Font (TextBox1.Font.FontFamily, TextBox1.Font.Size, Drawing. FontStyle.Underline)
End If
If B = False And I = False And U = False Then
TextBox1.Font = New Font (TextBox1.Font.FontFamily, TextBox1.Font.Size, Drawing. FontStyle.Regular)
End If
End Sub

44

Program 27 Menus with Arrays

Form

Button 1
Menu
Name
MNUFILE
MNUITEMS
MNUX

Name
Text
WindowState

FRMITEMS
Loading Items In A Menu At
Runtime
2-Maximized

Name
Text

BTNITEMS
CLICK HERE TO LOAD NEW ITEMS
Text
&FILE
&ITEMS
E&XIT

Code
Private Sub Command1_Click()
Static intItemCount
intItemCount = intItemCount + 1
MNUITEMS.DropDownItems.Add(Item & intItemCount)
End Sub

45

14. MICROSOFT ACCESS


Database
A database is a collection of records in an organized manner. For e.g., telephone diary.
DBMS Database Management System
RDBMS Relational Database Management System
Access is a DBMS as well as an RDBMS, i.e., it allows you to define relationships between different types of data
and use them together.
Elements of an Access Database
There are some important elements usually referred to as Objects in an Access Database. Types of objects:
Tables: Any data that you enter in an Access database gets stored in a table.
Queries: Allow you to ask questions about your data or make changes to the data.
Forms: Used for viewing and editing information.
Reports: Are useful for summarizing data and printing it.
Macros: Perform one or more database actions automatically.
Tables
The most basic component of an Access Database is a Table, a collection of data arranged in rows and columns. The
table consists of rows of information arranged under column headings, called Fields, that describe the type of
information stored in each column. Each item of information is a Field Value and each row of is a Record.
Field Types
A field name can be upto 64 characters long, can contain letters, numbers, spaces and other characters except period
(.), exclamation mark (!), accent grave (`) and brackets ([ ]).
AutoNumber: Access automatically assigns a number to this filed when a record is added to the table.
Currency: This type of field is used for monetary values.
Date/Time: Stores dates, time, or a combination of the two.
Hyperlink: This field holds hyperlink addresses that jump to web sites, database objects or other files.
Lookup Wizard: A lookup field starts a wizard that places lookup constraints on a field. The looked up values
can come from a list you enter, a table or a query.
Memo: Holds unlimited amount of text.
Number: Stores numbers formatted in various ways.
OLE Object (Object Linking & Embedding): It holds objects like pictures, Word Documents, etc.
Text: Holds letters, numbers and other characters.
Yes/No: holds values like True/False, Yes/No, Male/Female, etc. Access automatically displays the field as a
check box.
Input Mask
Input mask provides a couple of different data entry checks like:
Ensure that a field value matches a certain pattern
Automatically fill in constant characters like (-) or (())
Input Mask Characters
Char
Purpose
0
Required number (0 9), no signs (+ / - )
allowed
9
Optional number (0 9), no signs (+ / - ) allowed
#
Optional number or space, signs allowed

Char
a

Purpose
Optional letter or number

A
&

Required letter or number


Required character or space

46

L
?

Required letter (a z)
Optional Letter (a z)

c
\

Optional character or space


Next character in the mask to be displayed
as a constant character

Indexes
Access uses indexes to speed up find operations, where it has to look for data in more than one field. Any table that
is keyed automatically has a primary index created for its keyed field. You can also create your own indexes for
other fields using the properties tab.
Record Navigation Bar
Current
Record No.

First Previous
Record Record

Total No.
of Records

Next Last
Record Record

New
Record

RELATIONSHIP
Access relates tables using fields with common values.
Types of Relationships
One To One: It exists when there is only one record on each side of the relationship for each linking value.
One To Many: It exists where there can be more than one record for a linking value on one side of a
relationship.
Many To Many: It exists where linking values can appear in multiple records on both sides of a relationship.
Referential Integrity
It is a way to protect data in linking fields so you dont end up with unrelated data.
Rules for Referential Integrity
Cascade Update Related Fields: Changes the values in related records when the linking value in a master
record is changed.
Cascade Delete Related Records: Deletes related records when the master record in a relationship is deleted.
Course
CourseCode Duration Fees
CIS

1 yr

15000

DG

2 yrs

200000

MSCIT

3 mths

2210

Oracle

6 mths

27000

Tally

1 mth

3500

Field Name
CourseCode
Duration
Fees

Data Type
Text
Text
Number

Batch
SizeBatchCode Days
Time CourseCode
25
Indexed: Yes (No Duplicates), Primary key
CIS0801 MWF 9.30-11.30 CIS
10
Long Integer
CIS0802 TTS 9.30-11.30 CIS
CIS0803

MWF 4.30-6.30 CIS

CIS0804

TTS 4.30-6.30 CIS

DG0901

MWF 12-2

DG

MSCIT01 MWF 8-10


MSCIT02 TTS 12-2
MSCIT03 MWF 2-4

MSCIT

47

MSCIT
MSCIT

TAL01

MWF 8-10

Tally

ORA01

TTS 8-10

Oracle

Field Name
BatchCode

Data Type
Text

Size
10

Days
Time
CourseCode

Text
Text
LookupWizaed

6
12

Indexed: Yes (No Duplicates),


Primary key

48

FORMS
AutoForm
The quickest way to create a form is using the AutoForm feature. There are 3 types of AutoForms:
Columnar: A Columnar AutoForm shows only one record at a time in the Form view window.
Tabular: A Tabular AutoForm displays multiple records at a time in the Form view window.
Datasheet: In a Datasheet AutoForm, records are displayed in the same manner as they would appear in a
Datasheet window.
Creating a Columnar AutoForm
Go to the Forms tab in the Database Window
Click on New
Select Autoform Columnar
Select the table from the drop-down list
Click on OK
Change the formatting effects if required
Save the form
Creating a Tabular AutoForm
Go to the Forms tab in the Database Window
Click on New
Select Autoform Tabular
Select the table from the drop-down list
Click on OK
Switch to the design view
Change the object type of the Course Code combo box to text box
Right click on the form and select properties from the menu
Change the options Allow Edits, Allow Deletions and Allow Additions to No
Change the formatting effects if required
Save the form
Creating a Form using the Form Wizard
The Form Wizard allows you to:
Select fields for the form from more than one table
Choose the order in which fields appear on the form
Choose the master table for the form (which determines the order of the forms records), when the form includes
fields from more than one table
Choose a layout for the form
Choose a style for the form
Steps for Creating the Form:
Go to the Forms tab in the Database Window
Click on New
Select Form Wizard
Click on OK
Select the table(s) and the required fields
Click on Next
Select the master table
Click on Next
Select the layout
Click on Next
Select a style

49

Click on Next
Change the names if required Finish

FILTERS
It is a kind of search that checks for values in more than one field.
Filter Records Using One Field and One Value
If you want to find records that match a value in just one field, you can use any of these techniques:
Filter By Selection: Allows you to select a value in the datasheet view or form view and click a button to display
any matching records.
Open any table in the datasheet view
Select any value in the table
Click on Filter by Selection on the toolbar
To remove the filter, click on Remove Filter on the toolbar
Filter By Form: Displays a blank record, where you can either enter the value you want to find or choose it from
a drop-down list
Open any table in the datasheet view
Click on Filter by Selection on the toolbar
Select the condition
Click on Apply Filter on the toolbar
To remove the filter, click on Remove Filter on the toolbar
Filter For: Shows up a shortcut menu for any field, where you have to type the value you want to find.
Open any table in the datasheet view
Right click in any field Type the criterion in front of Filter For
Press the Enter key
To remove the filter, click on Remove Filter on the toolbar
Filter Excluding Selection: Looks for values other than what you have entered
Open any table in the datasheet view
Select any field value, you dont want to see
Right click and select Filter Excluding Selection
To remove the filter, click on Remove Filter on the toolbar
Filter Using Multiple Criteria
AND Filters
Filter By Selection Repeatedly
Repeat the steps under Filter By Selection (above) twice (for different fields)
Filter by Form
Open any table in the datasheet view
Click on Filter by Selection on the toolbar Select the condition
Click on Apply Filter on the toolbar
To remove the filter, click on Remove Filter on the toolbar
Filter For
Repeat the steps under Filter For (above) twice (for different fields)
OR Filters
Filter by Form
Filter by Form

50

Open any table in the datasheet view


Click on Filter by Selection on the toolbar
Select the condition (select the second condition in the Or tab)
Click on Apply Filter on the toolbar
To remove the filter, click on Remove Filter on the toolbar

QUERIES
Queries are most often used to ask questions about your data. You can formulate simple queries that look for records
in a single table or design complex queries that involve multiple tables.
Difference Between Filters and Queries
You can do this
Change the records you are currently viewing in Datasheet or form view
Save the view of selected records as a separate Database object
Create a form or report based on a subset of records
Choose the fields you want to see
Include fields from more than one table

With a Filter
Yes
No
No
No
No

With a Query
No
Yes
Yes
Yes
Yes

Types of Queries
Select Query: It finds the records satisfying the specified condition(s) and displays them whenever the query is
executed.
Make-Table Query: When you turn a select query into a make-table query, it writes the result to a completely new
table.
Update Query: You can make global changes to a table or update one table against another using this query.
Append Query: It is used to add information from one table to another.
Delete Query: Instead of deleting records from a table one by one, you can use a Delete Query to quickly delete an
entire group of records.
Examples for Queries

Simple Query
Go to the Queries tab in the Database window
Click on New
Select Design view
Choose the tables to be added (Batch, Course)
Select the fields
Field
Course Code Duration
Fees
Table
Course
Course
Course
Sort
Ascending
Save the query
Click on Run on the toolbar
Look for Blanks
Delete some of the addresses from the Stud_Info table
Go to the Queries tab in the Database window
Click on New
Select Design view
Choose the tables to be added (Stud_Info)
Select the fields
Field
Stud_Info.*
Table
Stud_Info
Show
Select
Criteria
Save the query

Batch Code
Batch
Ascending

Days
Batch

Time
Batch

Address
Stud_Info
Deselect
Is Null

51

Click on Run on the toolbar

52

Use a Yes/No Field


Add a field to the Course table Govt_Rec (Type Yes/no)
Select the Govt_Rec field for some records
Go to the Queries tab in the Database window
Click on New
Select Design view
Choose the tables to be added (Course)
Select the fields
Field
Table
Show
Criteria

Course.*
Course
Select

Govt_Rec
Course
Deselect
Yes

Save the query


Click on Run on the toolbar

Look for a Range of Values


Go to the Queries tab in the Database window
Click on New
Select Design view
Choose the tables to be added (Stud_Info)
Select the fields
Field
Stud_Info.*
Table
Stud_Info
Show
Select
Criteria
Save the query
Click on Run on the toolbar

DOJ
Stud_Info
Deselect
Between #7/1/00# and #7/31/00#

AND Query
Go to the Queries tab in the Database window
Click on New
Select Design view
Choose the tables to be added (Course)
Select the fields
Field
Course.*
Govt_Rec
Table
Course
Course
Show
Select
Deselect
Criteria
No
Save the query
Click on Run on the toolbar
OR Query
Go to the Queries tab in the Database window
Click on New
Select Design view
Choose the tables to be added (Course)
Select the fields
Field
Course.*
Govt_Rec
Table
Course
Course
Show
Select
Deselect
Criteria
Yes

Duration
Course
Deselect
Like 1*

Duration
Course
Deselect

53

Or
Save the query
Click on Run on the toolbar

Like 2*

Make a Table From a Query


Go to the Queries tab in the Database window
Click on New
Select Design view
Choose the tables to be added (All the 3 tables)
Select the fields
Field

Stud_Code

Name

Surname

Batch Time Days


Course
Code
Code
Table Stud_Info
Stud_Info Stud_Info Batch Batch Batch Course
From the Query Menu, select the option Make Table Query
Type the table name as Student Details
Save the query
Click on Run on the toolbar
It will confirm whether you want to paste the records into the new table
Click on Yes

Duration

Fees

Course

Course

Find Duplicates with a Query


Access has a wizard that can help you find duplicate records in a table. It asks you which field to check for
duplicate values and shows the query result in a datasheet view
Go to the Queries tab in the Database window
Click on New
Select Find Duplicates Query Wizard
Select the table (Stud_Info)
Click on Next
Select the field for where you have duplicate records (Batch Code)
Click on Next
Select any additional fields that you want to see (None)
Click on Next
Type a name for the query (Batch Strength)
Click on Finish

Find Unmatched Records with a Query


The Find Unmatched Query Wizard finds records in one table that do not have matching values in one or more
fields in another table.
Go to the Queries tab in the Database window
Click on New
Select Find Unmatched Query Wizard
Select the table (Course)
Click on Next
Select the table having unmatched values (Batch)
Click on Next
Click on Next (In this step, Access, displays the relation between the two tables)
Select the fields that you want to see (All)
Click on Next
Type a name for the query
Click on Finish

54

Append Query
Create a new table Stud with the same fields as Stud_Info
Go to the Queries tab in the Database window
Click on New
Select Design view
Choose the tables to be added (Stud_Info)
From the Query Menu, select the option Append Query
Select the table name as Stud
Select fields from Stud_Info tot be appended to Stud
Field
Stud_Info.*
Table
Stud_Info
Append To Stud.*
Save the query
Click on Run on the toolbar
It will confirm whether you want to paste the records into the new table
Click on Yes
The records will be appended as many times as you execute the query

Update Query (Make changes in table)


Go to the Queries tab in the Database window
Click on New
Select Design view
Choose the tables to be added (Stud)
From the Query Menu, select the option Update Query
Select fields that you want to update
Field
College
Table
Stud
Update To MLDC
Criteria
Dahanukar
Save the query
Click on Run on the toolbar
It will confirm whether you want to update the records
Click on Yes

Update Query (Update one table against another)


Delete the information in the DOJ field of Stud table
Go to the Queries tab in the Database window
Click on New
Select Design view
Choose the tables to be added (Stud & Stud_Info)
Set a relation between the Stud_Code field of the two tables
From the Query Menu, select the option Update Query
Select fields that you want to update
Field
DOJ
Table
Stud
Update To [Stud_Info].[DOJ]
Save the query
Click on Run on the toolbar
It will confirm whether you want to update the records
Click on Yes

55

Delete Query
Go to the Queries tab in the Database window
Click on New
Select Design view
Choose the tables to be added (Stud)
From the Query Menu, select the option Delete Query
Select the condition for deleting the records
Field
Table
Delete
Criteria

Batch Code
Stud
Where
Like ADSE*

Save the query


Click on Run on the toolbar
It will confirm whether you want to delete the records
Click on Yes

Create a Calculated Field with a Query


Go to the Queries tab in the Database window
Click on New
Select Design view
Choose the tables to be added (Course)
Select the fields you want to see
Field
Table

Course.*
Course

Staff Fees:[Fees]*0.5

Save the query


Click on Run on the toolbar

REPORTS
AutoReport
It is the quickest way to create a report for a table or query. There are two types of AutoReports
Columnar AutoReport
Tabular AutoReport
Go to the Reports tab in the Database
Go to the Reports tab in the Database
Window
Window
Click on New
Click on New
Select AutoReport: Columnar
Select AutoReport: Tabular
Select the table
Select the table
Click on OK
Click on OK
Creating a Report with the Report Wizard

Go to the Reports tab in the Database Window


Click on New
Select Report Wizard
Click on OK
Choose the tables and the fields (Course Course Code, Fees, Duration; Batch Batch Code,
Time, Days)
Click on Next Select the master table
Click on Next Select the sort order
Click on Next Choose a layout
Click on Next Choose a style

56

Click on Next Type a name for the report


Click on Finish

15. Database Programming


A Visual Basic program has 3 distinct parts:
User Interface

Database Engine

DataStore

User Interface: It is that part of the program with which the user interacts. The interface is developed
with Visual Basic. It contains forms that display the data and allow the user to modify the data. It also
contains the code that requests the database services to perform different operations on the data.
Database Engine: A database such as Microsoft Access consists of tables that hold information, but it
has no way to actually manipulate the information. That is where a database engine comes in. It is a
software program that actually manages the information in the database. In case of Access, the database
engine used is JET
DataStore: The datastore is the physical file that contains the data.
Program 28 Course Table

Data Show Data Sources Add New Data Source Database New Connection Change Microsoft
Access Database File OK Browse Select CIS.mdb OK Next no Next Tables (Select Course)
Finish
From Data Sources Window Under CISDataSet Drag and place CourseCode, Duration and Fees on to the form.
Delete CourseBindingNavigator
Form

Name
Text
WindowState
Label1

Label 2

FRMCOURSE
Course Details
2-Maximized
Label3

Label 4

57

Text

Course Code

Name

Text 1
TXTCCODE

Duration

Fees

Search for Course

Text 2
TXTDUR

Text 3
TXTFEES

Name
Text

Button 1
BTNADD
&ADD

Button 2
BTNMODIFY
&MODIFY

Name
Text

Button 6
BTNFIRST
&FIRST

Button 7
Button 8
BTNPREVIOUS BTNNEXT
&PREVIOUS
&NEXT

Button 9
BTNLAST
&LAST

Name
Text

CMBCCODE
-

Combo1
Code
Public Sub EnterData( )
txtCCode.ReadOnly = False
txtDur.ReadOnly = False
txtFees.ReadOnly = False
cmbCCode.Enabled = False
BtnSave.Enabled = True
BtnAdd.Enabled = False
BtnModify.Enabled = False
BtnDelete.Enabled = False
BtnCount.Enabled = False
BtnFirst.Enabled = False
BtnPrevious.Enabled = False
BtnNext.Enabled = False
BtnLast.Enabled = False
BtnX.Enabled = False
End Sub
Private Sub BtnX_Click( )
End
End Sub

Button 3
Button 4
BTNSAVE
BTNDELETE
&SAVE &DELETE

Button5
BTNCOUNT
&COUNT
Button 10
BTNX
E&IT

Public Sub ViewData( )


txtCCode.ReadOnly = True
txtDur.ReadOnly = True
txtFees.ReadOnly = True
cmbCCode.Enabled = True
BtnSave.Enabled = False
BtnAdd.Enabled = True
BtnModify.Enabled = True
BtnDelete.Enabled = True
BtnCount.Enabled = True
BtnFirst.Enabled = True
BtnPrevious.Enabled = True
BtnNext.Enabled = True
BtnLast.Enabled = True
BtnX.Enabled = True
If Me.CourseBindingSource.Count > 0 Then
Me.CourseBindingSource.MoveFirst( )
End If
End Sub

Private Sub FrmCourse_Load( )


ViewData( )
Me.CourseTableAdapter.Fill(Me.CISDataSet.Course)
cmbCCode.DataSource = CISDataSet.Tables("Course")
cmbCCode.DisplayMember = "CourseCode"
cmbCCode.SelectedIndex = 0
End Sub
Private Sub BtnFirst_Click( )
Me.CourseBindingSource.MoveFirst( )
End Sub

Private Sub BtnLast_Click( )


Me.CourseBindingSource.MoveLast( )
End Sub

Private Sub BtnPrevious_Click( )


If Me.CourseBindingSource.Position <> 0 Then
Me.CourseBindingSource.MovePrevious( )
Else
Me.CourseBindingSource.MoveFirst( )
End If
End Sub

Private Sub BtnNext_Click( )


If Me.CourseBindingSource.Position <> -1 Then
Me.CourseBindingSource.MoveNext( )
Else
Me.CourseBindingSource.MoveLast( )
End If
End Sub

Private Sub BtnCount_Click( )


MsgBox("Total number of courses = " & Me.CourseBindingSource.Count)
End Sub

58

Private Sub BtnAdd_Click( )


EnterData()
Me.CourseBindingSource.AddNew( )
End Sub
Private Sub BtnSave_Click( )
On Error GoTo SaveError
Dim msg, btn, tit, ans
msg = "Save the record?"
btn = vbQuestion + vbYesNo
tit = "Save"
ans = MsgBox(msg, btn, tit)
If ans = vbYes Then
Me.CourseBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll _
(Me.CISDataSet)
Else
Me.CourseBindingSource.CancelEdit( )
End If
ViewData()
Exit Sub
SaveError:
MsgBox("Error adding details")
Me.CourseBindingSource.CancelEdit( )
ViewData()
End Sub

Private Sub BtnModify_Click( )


EnterData( )
End Sub
Private Sub BtnDelete_Click( )
Dim msg, btn, tit, ans, pos
msg = "Delete this record?"
btn = vbQuestion + vbYesNo
tit = "Delete"
ans = MsgBox(msg, btn, tit)
If ans = vbYes Then
pos = Me.CourseBindingSource.Position
Me.CourseBindingSource.RemoveAt(pos)
Me.TableAdapterManager.UpdateAll(Me.CISDataSet)
Me.CourseBindingSource.MoveFirst( )
End If
End Sub

Private Sub cmbCCode_SelectedIndexChanged( )


Dim c
Dim pos
c = cmbCCode.Text
pos = Me.CourseBindingSource.Find("CourseCode", c)
Me.CourseBindingSource.Position = pos
End Sub

59

16. ActiveX Controls


Program 29 Project Add User Control

Text

Label1
Value1:

Label2
Value2:

Label3
Result:

Name
TextAlignment
ReadOnly

Text1
TxtValue1
Right
False

Text2
TxtValue2
Right
False

Text3
TxtResult
Right
True

Name
Text

Command1
BTNAdd
+

Command2
BTNSub
-

Command3
BTNMul
*

Code
Dim val1, val2 As Boolean
Private Sub BTNAdd_Click()
Chk_num
If val1 = True And val2 = True Then
TxtResult.Text = Val(TxtValue1.Text) + Val(TxtValue2.Text)
End If
End Sub
Private Sub BTNClear_Click()
TxtValue1.Text = ""
TxtValue2.Text = ""
TxtResult.Text = ""
TxtValue1.SetFocus
val1 = False
val2 = False
End Sub
Private Sub BTNDiv_Click()
Chk_num
If val1 = True And val2 = True Then
If Val(TxtValue2.Text) <> 0 Then
TxtResult.Text = Val(TxtValue1.Text) / Val(TxtValue2.Text)
Else
TxtResult.Text = "Error"
End If
End If
End Sub

Command4
BTNDiv
/

Command5
BTNClear
C

Private Sub BTNMul_Click()


Chk_num
If val1 = True And val2 = True Then
TxtResult.Text = Val(TxtValue1.Text) * Val(TxtValue2.Text)
End If
End Sub
Private Sub BTNSub_Click()
Chk_num
If val1 = True And val2 = True Then
TxtResult.Text = Val(TxtValue1.Text) - Val(TxtValue2.Text)
End If
End Sub
Public Sub Chk_num()
If Not IsNumeric(TxtValue2.Text) Then
TxtValue2.Text = ""
TxtValue2.SetFocus
val2 = False
Else
val2 = True
End If
If Not IsNumeric(TxtValue1.Text) Then
TxtValue1.Text = ""
TxtValue1.SetFocus
val1 = False
Else
val1 = True
End If
If val1 = False Or val2 = False Then
MsgBox "Invalid Numbers", vbOKOnly + vbInformation, "Error"
If val1 = False And val2 = False Then
TxtValue1.SetFocus
Else
TxtValue2.SetFocus
End If
End If
End Sub
Private Sub UserControl_Load()
val1 = False
val2 = False
End Sub

Save it as SimpleCalc
Form1 Toolbox WindowsApplication1 Components Drapg and SimpleCalc on the form

17. Web Browser


Program 30

Form

Name
Text
WindowState

FRMBROWSER
Browser Application
2-Maximized

Label

Text

URL

TextBox
Button

Name

TXTURL
Name
Text

WebBrowser
Code:
Private Sub BTNGO_Click ( )
WebBrowser1.Navigate (txtURL.Text)
End Sub

BTNGO
&GO

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