0% found this document useful (0 votes)
25 views

Introduction to Visual Programming - NPR Arts and Science College

Uploaded by

rooba vathi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Introduction to Visual Programming - NPR Arts and Science College

Uploaded by

rooba vathi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

SECOND YEAR IV SEMESTER

INTRODUCTION TO VISUAL PROGRAMMING SUBCODE:CCA8C41

UNIT-I:
Introduction-starting & exiting visual basic-using project explorer- working
with forms- using toolbox- working with projects- printing projects- building &
running applications.
Adding code &using events- using code window- using naming conventions-
using variable- scope- subroutines & functions.

UNIT-II:
Using intrinsic visual basic controls- label & textbox controls- using command
button control- using frame, checkbox, option button controls- list box and combo box
controls- formatting controls- using control arrays- using tab order.
Working with strings - using strings, converting string, concatenating strings,
formatting strings, manipulating strings, comparing strings.

UNIT-III:
Working with numbers - using numeric values- using numeric operators- math
functions- random numbers.
Using control statement- IF &IIF- select case- do-for- exit statements.

UNIT-IV:
Using dialogue boxes- Msg box- input box- common dialogue control- open &
save as dialogue box- font dialogue box- print dialogue box- show help method.
Using menus- creating menus- assign code to menu- creating shortcut menu –
using picture box- rich text box.

UNIT-V:
Using files & databases- opening, closing & deleting files, and reading writing
to files.

BOOKS FOR STUDY:


1. Scott warner- Teach yourself vb.6- Tata mc graw hill, new Delhi, 1999
(chapters:1 – 8, 10.1,10.2).
2. gray Cornell- visual basic 6 from the ground up – TMH , new Delhi, 1999
(chapters:6 (page 206 – 214)).
VISUAL BASIC

UNIT-I

INTRODUCTION TO V.B:

The “visual” part refers to the method used to create the graphical user
interface (GUI). Rather than writing numerous lines code to describe the appearance
and location and location of interface elements, you simply add prebuilt objects into
place on screen. If you‟ve ever used a drawing program such as paint, you al ready
have most of the skills necessary to create an effective user interface.

The “basic” part refers to the basic (beginner‟s all-purpose symbolic


instruction code) language, a language used by more programmers than any other
language in the history of computing.

Development of visual basic

The original Visual Basic for DOS and Visual Basic for Windows
were introduced in 1991.

Visual Basic 3.0 (a vast improvement over previous versions) was released in 1993.

Visual Basic 4.0 released in late 1995 (added 32 bit application support).

Visual Basic 5.0 released in late 1996. New environment, supported creation of
ActiveX controls, deleted 16 bit application support.

Visual Basic 6.0 - released in mid 1998s - some identified new features of Visual
Basic 6.0:

Faster compiler

New ActiveX data control object


Allows database integration with wide variety of applications
New data report designer
New Package & Deployment Wizard
Additional internet capabilities.

Features of visual basic

The following are the features of visual basic

1. Include a GUI development environment for development for


developing windows application
2. Provides the ability to develop and test application using an run
function
3. Object based development is possible using class modules
4. Rapid application development
5. Allows for the creation of com components such as ActiveX controls
DLLS and EXES
6. It has many internet development possibilities including the following

ActiveX document.
DHTML Application that helps to test browser
applications.
IIS application that helps to build server based
applications.
Web browser control.
FTP/HTTO supports through a custom control.
Winsock control.
Has an excellent integrated help facility and books
online
Includes good debugging facilities.
Has many wizards that help automate repetitive tasks
Use many database access methods to get different
types of data

Advantages of visual basic

Removes the complexity of windows API(application


programming interface)
Allows for rapid application development
Excellent for business applications.
Allows to create ActiveX controls
Object oriented in nature.
Can integrate with the internet on both the server side and the
client side.
Can create ActiveX automation server.
Integrate with Microsoft transaction server.
Can run servers either on the same machine or remotely on
another computer.
Visual basic supports for new development since it has large
community of development.

Disadvantage of visual basic

Runtime distribution requirements are larger than those for C


and C++
Not as much functionality as C and C++ in getting to features
of the operating system

Starting a new project

To start a new project we have to follow the steps below


 Click the start menu in the desktop.
 From that menu, select program
 Select Microsoft studio, then select Microsoft visual basic.

Start -> program-> Microsoft studio->Microsoft visual basic 6.0.

 Then it open new project dialog box. It contains three types of


buttons .they are

a. New
b. Existing
c. Recent

New -> used to create new project

Existing -> used to open the project which was already created.

Recent -> used to open the recently created project.

 New project box contains different types of project like

Standard EXE
Active EXE
ActiveX DLL(dynamic link library)
ActiveX Control
VB application wizard
VB Wizard manager
ActiveX document DLL
Data project
Add in
ActiveX Document EXE

 Select standard executable project ,by double clicking on it or


by clicking right in mouse open button ,VB application will be
opened.
 Suppose we want to open new project while working with
another project ,we have to go to file menu and click „new
project‟ or by using Ctrl +N
 VB application was open , it contains following components

Menu bar
The menu bar contains the command required to build a visual basic
application. It lies across the top of the screen .Menu bar have submenu item. Menu
bar contains 13 submenu items they are as

Tool bar
The tool bar contains shortcut of some popular menu items. It provides
quick access to commonly use command.
Project explore window
The project explorer server as a quick reference to the form, classes
and modules in current project. It
is arranged in a tree order . It has three tabs

a. view code
b. view object
c. toggle folder
Properties window
It has two sides, left side showing the name of the property where as
right side showing the value of that property. This window can be viewed as
alphabetical
or categorized manner

Form layout window


This shows the initial position of the current form. This sets the
position of the object in the form where the form is displayed on the screen

Tool box
Tools or object are called as controls. There are 21 standard controls
other controls can be add through
 Project -> components -> controls

Form designer
It enables to add controls, graphics, pictures to a form to define the
interface in the desired look .we can see only one form or code window at a time.

Code window
It is used to write the code we want to attach to an object. Two
dropdown list boxes on the top. Left is for object where as right for events.

Immediate window
It is used to debug the errors during runtime. It is also known as debug
window

Object browser
It allows us to browse the various properties, events and methods. We
can access it by pressing F2 (or)
 View->object browser

Using project explorer:

The project explorer displays a hierarchical list of the projects and all
the items contained in a project. The elements of your project explorer window are as
follows:
View code displays the code window where code is written and edited

View object displays the object window for the selected item. An existing
form, module. ActiveX object
Toggle folders that hides and show the object folders while still showing
the individual items contained with them.
Shortcut key : CTRL + R

Moving the project explorer window:

Visual basic allows the project explorer window to be moved so that it can be
placed where it works best for you. The following are the methods that can be used to
move the project explorer window.

 Click the title bar and drag the window to a new location.
 Double click the title bar to move the window to its last undocked location.
The window can still be docked to any side of it‟s parent window, which is the
visual basic window.
 Right-click on the window and choose dockable from the shortcut menu to
move the window to its last undocked location. This makes the window no
longer dockable.

Double click the title bar a second time returns the project explorer to its
previous docked location.

Resize the project explorer window:

Move the mouse pointer over one of the borders until it takes the shape of the
double headed arrow. Then click and drag the border to the size that you desire. Don‟t
forget that an undock able project explorer window can be minimized and maximized.
Maximizing the window allows you to quickly view the largest possible number of
objects.

Opening files in the project explorer window:

Now you know how to navigate the project explorer. You also know how to
move it around, change its size, and even Alter its behavior. Now, it‟s time to learn
how to use it.
Using the project explorer to view objects:

Visual basic allows programmers to visually built application by placing


control onto forms. To view this forms or any other visual object, project explorer and
click the view object button.

Using the project explorer window to view code:

Visual basic is a popular programming tool because it cuts down on the


amount of code that must be written to make a windows application, to view the code
contained in a module or the code of any other projects, select the object and click the
view code button.

WORKING WITH FORM:

The form layout window allows you to visually position your forms at
design time. All forms that are visible in the environment are displayed. W hen you
place your cursor over a form. If you press the mouse button you can position the
form where you want it to appear at runtime

Altering a form
The size and position of the form can be changed during design time
and runtime during
Design time the size of the form can be changed by the following ways
1. By clicking the maximize, minimize, close controls on the form
or by double clicking the title bar of the form.
2. By using the sizing handler and with the help of mouse, the size
of form can be changed
3. By using shortcut keys shift + arrow keys
4. By using width and height properties of the properties window
Working with form layout window:

During runtime, the size and position of the form can be changed by the following
ways
1. Move the cursor to the form layout window(the cursor will change to a
four-headed arrow)
2. Drag the form to the position in which we want it to appear when the
user starts our program.
3. To change the size of the form during runtime, window state property
is used.
It contains three options
 Normal -> The form is displayed as the user designed during design
time.
 Maximize -> The form is maximized during runtime
 Minimize -> The form is minimized during runtime
The size of form is changed during runtime using maximize, minimize and close
control

If a form is maximized when it first appears, it is not necessary to specify a


location for the window to appear. It simply takes up the whole screen. However,
many times a form is not maximized when it first appears. Visual basic allows you to
specify the location that the windows first appear by using the form layout window,
which is shown in figure.
Using tool box:

The visual basic tool box contains the tools you use to draw controls on your
forms. The tools are for working with the form is found on the menus.
The toolbox itself contains the icons representing the controls we can add to
our forms. The Tools are object are called as controls. Among these there are 21
standard controls we can add any if required through

The above the tool box contains the following controls:


Pointer control
Picture box control
Label control
Textbox control
Frame control
Command button control
Check box control
Option button control
List box control
Combo box control
Horizontal/vertical scroll bars
Time control
Drive list box control
Directory list box control
File list box control
Shape control
Line control
Image control
Data control
Ole control

Pointer control
The first item on the toolbox is not a control but is used to manipulate controls
after we create them click the pointer when we want to select, resize, or move existing
controls

The pointer box control looks like

Picture box controls

 This control used hold picture &graphics.


 It is used load a picture at a design places by clicking on a picture item
 In a property window select the picture
 When we load a picture run time using a load picture method.

 The picture box controls looks like


Example
Picture1.picture=load picture (“c:\my document zedra.gif”);

Label control
Label box display only read only text.
The caption of the label box can be changed during runtime through
code.
It is always used to give message to the user.
It is used to provide information.
Label box control looks like .

Text box control


It is sometimes called as edit fields.
Textbox is used to display text or to accept user input.
Text boxes can word wrap automatically (or) display multiple
lines of text.
It is standard control.
It is received input from the user as to display the output.
It handles string in a numeric data.
The text box controls look like .
Frame box control
It is used to group the other control.
Once a control has been placed in a frame it can`t be module &
form.

The frame box control looks like .

Command button control


It is also called as push button.
The control is that when the user moves the mouse to the
command button and clicks something inserting will happen.
The command button looks like .

Check box control


Check box has a choice as true or false (or) yes/no.
At a time any number of check box can be selected.
It is used to select the unselected option. It is like a switch.
When the check box is uncheck the property value is set to “0”.
The check box button looks like
Option button control
Option button are used to select only one option at a time from a
group of choice.
These are called as radio button.
When the option button is selected the property value is set true.
When the option button is not selected the property value is set
false.
List box control
The control is used to display list of items
The user can click and select items from the list.
If the number of items exceeded to fit in the box. The vertical
scroll bars automatically add at run time.
The list box control looks like
To add a new item in a list we can use add item method
Example: List1.Add item (“Apple”)
Combo box control
It combines the features of text box & list box.
It is used allow the user to select the item from the list & enter
some text.

The combo box controls looks like


We can use add item method to add a item in a combo box
Example: Combo1.Add item (“Baby”)
Horizontal/vertical scroll bars
It provides any navigation through long list of information.
The Horizontal/vertical scroll bars looks like

Timer control
It can execute code and regular intervals .fixed size control.
It is invisible at run time.

The timer control looks like


Drive list box control
It enables the user select the valued disk derived at runtime.
The drive list box control looks like
Directory list box control
It is used to display a list of directories of selected drive at run
time.
It is used to create dialog boxes
The Directory list box control looks like
File list box control
File disk box display the file which contain the directory on the
current drive.
The drive list box the directory list box and file list box can be
open to give standard windows file management facilities
When the program runs it display in current drive & directory
The file list box control looks like
Shape control
It is a graphical control.
It is used for designing purpose the standard shape bar
rectangle, square, circle etc

The shape control looks like


Line control
It is used for shape the control
It I used to draw lines

The line controls box looks like


Image control
It is another control that handles images & picture
It is same as picture box control box but there is only one major
different is on image box it can be resize.

The image box control looks like


Data control
Data control is used to read record from data base.
It provide access to data stored in data base using record set
object.
It is used to move a record, display a record, edit a record.
Important property are record set type record store & data base
name.
The database control box looks like

Ole control
Ole stands for object linking embedded.
It is used to connect other application.
This control in a window you can place your form to host
document from application such as MS word, MS excel.

The Ole control looks like

Creating controls
To get a control on a form by double clicking on its icon in the toolbox. The
control appears in the middle of the form with its default size and shape.

Example
To draw an item from the toolbox on a form at a specific location with a
specified size
1. Move the mouse pointer to the tool we want to use and click
2. Move the mouse pointer to the form. The mouse pointer has changed
from an arrow to a shape like a crosshair
3. Hold the mouse button down and drag the mouse to create the object.
Then the control appears on the form.
Sizing handles
When we release the mouse button, the control has eight little boxes

Adding controls to the toolbox:

Visual basic comes with many controls that are not automatically
included in the toolbox. Follow these steps to add controls to the toolbox:

1. Choose components from the project menu.


2. Select the controls that you want to select from the components dialog box.
3. Click the ok button to add the selected controls on the toolbox.
Working with control already on the form
Create a control and place it anywhere we like on a form. In VB, we
are never follow to keep a control as its original size or at its original location, and the
techniques needed for moving or resizing controls are the same for all VB control.

Resizing an existing controls


To change the size of an existing control (example: command button)
at design time, we can either use the properties window to adjust the width and height
properties (or) working with the size handles.
To resizing a controls width the sizing handles by the following these
steps
1. Move the mouse pointer to a sizing handles and click and hold
down the left mouse button
2. Draw the mouse until the control is the size we want
Moving an existing control
To move an existing control
1. Move the pointer anywhere inside the control click the left
mouse button, and hold it down
2. Drag the mouse until the control is at the location we want it to
be and then release the left button.
The movements of controls are as follows
1. Select the control
2. Use ctrl + an arrow key to move the control one grid mark at a
time.
3. Or we can directly adjust the left and top properties in the
properties window.
Working with a multiple control
The steps for the dragging method to select multiple controls
1. Imagine a rectangle that surrounds only these control we want
to select move to one corner of this imagined rectangle and
click left mouse button
2. Hold the left mouse button down and drag the dotted rectangle
until it covers all the controls we want to select then release the
mouse button.
If the controls are widely scattered on the form, means
Select ach controls by moving the mouse pointer to it and holding
down the left mouse button.

While pressing ctrl


We can resize and reshape a group of controls through tools->format menu.
Then format->align submenu allow us to align the controls, left, right, centre etc.
similarly, format-> make same size menu, make a group of controls all the same
width ,height o both.

Locking controls
By choosing format->lock controls or lock controls tool from the tool bar use
can lock the control in the form (i.e) we can‟t move if we lock. Choosing, it again
presses up the controls so that we can move them again.

Deleting controls
To delete a controls
 Move the mouse pointer until it is inside the control, and click
the left mouse button to select it.
 Press delete or open the edit menu and choose the delete option
by pressing Alt + E, D.

The name (control name) property


The name gives the control its own identity. His property determines the name
VB uses for the event procedure we want to make the controls respond to the user.
Example: me. Height = 5000
Then VB will change the height of the current form. To change the height of a
command button whose name property is command1; then
Command1. Height = 5000
Rules
1. The name must begin with a letter
2. After that, we can use any combination of letters, digits and
underscores.
3. The name cannot be longer than 40 characters.

Project window:

The project explorer displays a hierarchical list of the projects and all
the items contained in a project. The elements of your project explorer window are as
follows:
View code displays the code window where code is written and edited
View object displays the object window for the selected item. An existing
form, module. ActiveX object
Toggle folders that hide and show the object folders while still showing
the individual items contained with them.
Shortcut key : CTRL + R

Working with projects:

All visual basic applications are based upon a project. A project file
(VBP) doesn‟t contain many forms, controls, or code. It contains the list of all objects
and files that are used in the projects.

Creating projects:

New projects can be created when you first start visual basic. You can
also create projects after starting visual basic. To create a new project, follow these
steps:

1. Choose new project from the file name.


2. If you already had a project open, you may be asked if you want to save any
changes. Click the yes or no button continue.
3. Select the type of project that you want to create in the new project dialog box.
4. Click the ok button or double-click your selection.

Now that you have created your project, you


Should save it. When saving a project, you are saving the project file and the files if
the objects used in the projects. Follow these steps to save a project.

1. Choose save project from the file menu.


2. Select a name and location for the files in the project, such as form files. See
chapter 2 for more information on naming objects and files.
3. Repeat step 2 as many times as necessary.
4. Select a name and location for the project file.
Adding and removing objects in projects:

The default project is created with a single form. Most projects require the use
of more than one form and sometimes the use of other types of objects. To add an
object to a project, choose the type of object you want from the project menu. The
choices are as follows:
 form
 MDI form
 Module
 Class module
 User control
 Property page
 User document
 ActiveX designer
 file
Printing projects:

Projects can be printed to help you review or distribute hard copies to


others. This printed material can also be used for documentation purpose. Printing
visual basic projects involves more than simply issuing a print command. You must
specifically tell visual basic what to print. As with other windows applications, you
can also specify which printer to use.

Setting printer properties:


Most windows applications that allow you to print also allow you to
specify which printer you would like to use and make changes to the settings for that
printer.
There are two ways to access printer:

 Click the setup button in the printer dialog box.


 Choose print setup from the file menu.

Saving your work (i.e) saving project


Visual basic will not allow exiting the program or starting a new
project without asking whether we want to save our works. Visual basic will to set its
option so that it will automatically save our work before a project runs. This
minimizes the dire efforts of system crashes, because we can‟t save a project while it
is running or when we are in break mode.
To activate this features;
1. Choose tools\option and go to the environments page.
2. In the “when a program starts” box, change the „don‟t save
changes‟ to either one of the two other options.

Saving form from the file menu


There are four save methods in the file name they are
Save form
Save form as
Save project
Save project as

Save form
Save form item I used to save the form that is currently working on.
Shortcut keys to save the forms are Ctrl + S or Alt + F, S. The default extension for
form files is form. Visual basic save form dialog box as shown below
The file name is changed and click the save button, the file name will
be saved with the user defined file name.

Save form as
Save form as is used to rename the file name of form. The default
extension of form is frm. The copy of form is also stored in another place with the file
name unless the save form as option. Shortcut key is Ctrl + A
(Or) Alt + F, A

Save project
Save project is used to save the entire project. To select this option,
press Alt + F, V or use the save project tool. Visual basic opens a dialog box as shown
above
The default extension is .vbp.
When we save a project using save project option, visual basic does not
keep a backup copy of the previous version. To save a backup copy of a project does
the following
1. Save each of the files on the project with a new name
2. Choose the save project as option and give the project file
(.vbp) a new name.

Save project as
Save project as is used to rename the project name. The copy of project
is also stored in some other location with their project name under save project as
option

Building and running application:

Building and running an application compiles the code into a format


that windows can understand. Compiled application are the distributed to users-who
can run the compiled application, syntax errors, which are incorrect words in the code
or in the wrong order

Explanation for building application:

To prepare an application to be distributed to users, it must be built or


compiled. Building an application generates an executable file that is used to start the
application. To compile a project follow these steps:

1. Open the project that you want to compile.


2. Choose make project name from the file menu, where projects name is
the name of the project that you are compiling.
3. Choose a name for the compiled application and where to save it.
4. Click the ok button.

Running an application:

Making a project allows it to be run outside of a visual basic session.


However, this is inconvenient when developing and testing an application. It is easier
to make changes to your to your project and immediately run them to see the effect of
the changes. Then you can make more changes and continue this process until you are
happy with the result.

You can run your applications using any of the following methods:

 press f5
 click the run button on the toolbar
 choose start from the run menu

EVENTS:

Events are procedures that are executed in response to actions performed by


the user, operating system, or other objects in an application. Code is written for the
events to provide functionality.

Example: click event for a command button gets triggered when you click on the
button.

 Load:

Occurs when a form is loaded. For a startup form,


occurs when an application starts as the result of a load statement or as
the result of a reference to an unloaded form‟s properties or controls.

Syntax:
Private sub form _load() or
Private sub mdiform _load()

 Unload:

Occurs when a form is about to be removed from the screen. When that
form is reloaded, the contents of all its controls are reinitialized. This
event is triggered by a user closing the form using close command on
the control menu or an unload statement.

Syntax:
Private sub form _ unload (cancel as integer)

 Query unload:

Occurs before a form or application closes. When a mdi form object


closes, the query unload event occurs first for the MDI form and then
in all MDI child forms. If no form cancles the query unload event, the
unload event occurs first in all other forms and then in an MDI form,
when a child form or a form object closes, the query unload event in
that form occurs before the form‟s unload event.

Syntax:
Private sub form _ query unload (cancel as integer, unload mode as integer)
Private sub MDI Form _ query unload (cancel as integer, unload mode as
integer)

Using event procedures:

When windows informs visual basic that an event has taken place for
one of it‟s object, visual basic automatically calls the event procedure that has the
name corresponding to the event.
The event‟s name established an association between the object and the
code.
An event procedure for a control combines the control‟s actual name
(specified in the name property), an underscore (_), and the event name. For instance,
if you want a command button name cmd command1 to invoke an event procedure
when it is clicked, you would use the procedure command1_click ()

All event procedures use the same general syntax

For controls:

Private sub control name_event name (arguments)


Statement
End sub
For forms:

Private sub formname_eventname (arguments)


Statement
End sub

Visual basic automatically creates procedures for forms and controls. You can
view and edit the code for an event procedure in the code editor window.

Note: when writing procedures for new controls, it‟s good idea to set the name
property immediately after creating the control. Because code procedures are attached
to the controls, changing the name of the control after a procedure is written breaks
the association between the code and the control.
`

USING CODE WINDOW:

The code window is used to write, display, and edit visual basic
code. The different code window elements are as follows:

Object box- displays the name of the selected objects


Procedures/ events box- list all the events recognized by visual basic
for a form or control displayed in the object box. When you selected an
event, the event procedure associated with that event name is displayed
in the code window.
Code setting and window setting are control on the editor tab.
Shortcut Key:F7

Using naming convention:

You should utilize a method of naming conventions when assigning


names to objects and variables in a project. This makes reading and understanding
your code easier for you and others, because control types and data types are describe
from the names they identify, while naming conventions should provide a guideline
for naming objects and variables, they should not restrict the ability to appropriately
name items.

Variable naming convention:

While naming variables it‟s a good practice to give them meaningful,


descriptive names. Variables names:

Must begin with an alphabetic character.


Cannot contain an embedded period or type- declaration character
(%,&,!,#,@,$).
Must be unique within the same scope.

Declaring variables:
The manner by which variables are declared and where they are
declared and where they are declared determines how they can be used by your
application.

This section includes the following topics:

Using the dim statement


Using the option explicit statement
Scope
Declaring local variables
Declaring static variables
Declaring module, form, and public variables

Using conversion functions:


Visual basic offers an extensive list of conversion functions.

Type of conversion function

Boolean Cbool
Byte Cbyte
Currency Ccur
Date Cdate
Decimals Cdec
Double Cdbl
Integer Cint
Long CLng
Single CSng
String Cstr
Variant Cvar
Error CVErr

To use conversion function, you place it on right hand side of a calculation statement
as follows:

Variable= CFunction (formula)

For example:

Dblarea=CDbl (txtlength.text * txtwidth.text)


USING VARIABLES:

A variable is a name given to a location in random access memory


(RAM) where a data value is stored. Assigning a name to the location makes it much
easier to work with.

Some possible uses for variables include:

A counter that stores the number of items a procedure or code block executes.
To save a value returned forms a method or function.
To store directory names and filenames.

Visual basic data types:

Visual basic can store strings of text, numbers, object or even data
where the types is unknown. Visual basic provides the following data types.

Data types that store text are:

String(variable length)
String(fixed length)

Data types that store numbers are:

Length
Long integer
Single
Double
Currency
Date
Boolean

Other data types are:

Variant
Object

String
The string data type holds character. It takes 2bytes per character to store
string variable can hold about 2billion characters. The identifier for this variable is $
Example; String variable$

Integer
Integer variable hold small integer values (between-32768 and -32,767). Its
storage size is 2 bytes. Variable will only, be capable of holding integers is to use the
percent sign (%)At the end of the variable name
Example; integer variable%=3

Byte`
Its storage size is 1byte. The range between (0 to 255). It can hold integers.

Long integer
It storage size is 4bytes and the range (between -2,147,483,648 to
2,147,483,647) the identifier for this variables is the ampersand (&)
Example; long integer variable&=123456789

Single precision
The least accurate is called single precision. They have a decimal point, but
we can be sure of the accuracy of only seven digits. It storage size is 4bytes. The
identifier for this variable is the(!)
Example; single precision variable! = 12.345

Double precision
The double precision data type is used when we need numbers with up to 16
places of accuracy calculation are also approximate for these variables. Double
precision variable are mainly used in scientific calculation in VB. The identifier used
is pound sign (#), storage size is 8bytes
Example; double precision variable# =12.345#

Currency
The storage size is 8bytes. The identifier for this variable is @. Its range from
-922,337,203,685,477.5808 to 922,337,203,685,477.5807
Example; currency variable@ = 12.345@

Date
The date data type is used to store both date and time information. Its storage
size is 8bytes. Its range is january1,100 to december31,9999 AM/PM for time or a 24-
hour clock.
Example; date1 = #january1,2000 11:59 PM#
Date1 =# january1,2000 23:59#

Boolean
The data to be either true or false. The storage size, is 2byte.
Variant
A variant can be any of the preceding data types plus null and empty.

Note: visual basic doesn‟t require that you explicitly select a variable type when you
declared variables. By default visual basic assigns variables the variant data type. It
can store any type of data. But this reduces the speed and requires a large amount of
data when compared to other data types.
Declaring variables:

The manner by which variables are declared and where they are
declared and where they are declared determines how they can be used by your
application.

This section includes the following topics:

Using the sim statement


Using the option explicit statement
Scope
Declaring local variables
Declaring static variables
Declaring module, form, and public variables

Requiring declaration of variable


To declare variable implicitly it can lead to errors. To prevent errors,
we require all variables be declared before they are used. Place the caption explicit
statement in the general declaration section of the editor window. The option explicit
statement instructs VB to check the module for any variables that are not explicitly
declared. If an undeclared variable is used, an error message appears, prompting us to
correct the error. To put the option explicit statement in the (general) section of the
code window steps are as follows.
1. Open the code window
2. Select the (general) object form the list of objects in the object
list box.
3. Select (declarations) from the procedure list box.
4. Type option explicit
After VB processes an option explicit command it will no longer allow us to
use a variable unless we declare it first. To automatically place option explicit at the
top of each new code module
1. On the tools menu, click options
2. Click the editor tab
3. Click required variables declaration, and then click ok.

Working with variables


Suppose we have two variables x and y, and we try the following code
to swap variables with in an event procedure.
X=Y
Y=X
The first assignment gives the current value of y to the variable x, but
it wipes out the previous value of x. the result is that the second statement copies the
original value of y. the solution is to use a temporary variable.

Temp =X copy old value X to temp


X=Y X now has old value of Y.
Y = Temp retrieve original value of X, give to Y
SCOPE

The scope of a variable, procedure, or object determines which parts of


the code in your application are aware of the variable‟s existence. For example, when
you declare a variable within a procedure, only code within that procedure can access
or change the variable‟s value. The variable‟s scope is limited to the procedure
containing the variable.

The scope of a variable, procedure or object is determined by where it‟s


declared and how you declared it. This table describes the scoping levels in visual
basic.

Scope level visibility


Local A variable defined at the procedure level that is visible
only to the procedure where it is declared.

Module/form A variable defined at the module or form level that is


visible to all procedures within module or form where it is
declared.

Public A variable at the module or form level that is visible to


all proceeds within the project.

Declaring local variable


To declare a variable as local, we use the dim statement with the following
syntax
Dim variable [as type]
Example
Dim strname as string
Strname = text1.text.
Msgbox “hello”&strname
End sub
When a procedure is finished executing, the values of its local variable are not
preserved and the memory used by the local variable is reclaimed. The next time a
procedure is executed, all its local variable are reinitialized to zero (0) or empty.

Declaring static variables


To preserve or retain the value of a local variable between calls to a
procedure, declare it as a static variable with static keyword.

Syntax
Static varname [as type]

Static variable are useful for maintaining counters that are used only
within a procedure.

Example Following procedure declares the variable icount by using the static
keyword. Each time the procedure runs, 1 is added to the value stored in icount.
Static icount as integer
Icount = icount +1
Msgbox”The count is now”& icount

Constant
VB prevents the value of a constant from being changed during
program execution. (i.e) value that never change during execution of a program. To
create a constant, we use the const statement with the following syntax
[Public /private] const constname [as type] = expression

Example
Public const PI as double = 3.1415

Using subroutines and functions:

Subroutines and functions are the heart of


Coding in visual basic. Procedures perform tasks and
Possibly manipulate values stored in variables or in a
Database. Function is similar to procedures, but they
return a value-which means that functions can be used to
Place values into variables. Both subroutines and
Function can accept values as part of their procedure call.
These values are called parameters or arguments and can
be used to change the behavior of a procedure according
To the values that are passed to it.

Using sub procedures:

A sub procedures is a block of code that


Performs a discrete task. After the sub procedure
Executes its code, it returns program execution to the line
of code the following called the sub procedure.
A sub procedures is referred to as a unit of
Code because each sub procedure has a distinct
Beginning, body and end. Each sub procedure starts with
the sub statement and ends with the end statement as
Follows:

Sub sub name ()


[Statement block]
End sub

Note: The procedures name is always followed by parentheses, even if there


are no arguments.

For example:

Sub get data ()


[……….]
End sub
To call a sub procedure, you type its name on a itself in your code. This
example calls the sub procedure get data:

Sub cmdcommand1_click ()
Getdata
End sub

FUNCTIONS

Introduction to string:

Strings are variables and constants that hold alphanumeric values.


These are values that you want to display but will not usually use for mathematical
calculation.

In visual basic, a sequence of alphanumeric characters treated as a


single value. Literal strings are assigned by enclosing the value in quotation marks, as
seen below:

Lblmessage.caption=”answer is incorrect”

Working with text strings:


Visual basic string function can manipulate strings in applications.
These functions are sued to return information about a string, extract only a certain
portion of a string or display information in a certain format.

Function Action
Strcomp compare two strings.
Lcase, Ucase convert to lowercase or
uppercase.
Space, string create string of repeating
character.
Len find length of a string
Lset, Rset justify a string
Instr, left, ltrim, mid, right, trim manipulate strings
Strconv convert strings
Asc, chr returns numeric or character
values

UNIT-II

USING INTRINSIC VISUAL BASIC CONTROLS:


Intrinsic controls, such as the command button and frame controls. These
controls are contained inside the visual basic.exe file. Intrinsic controls are always
included in the toolbox, unlike ActiveX controls and insert able object, which can be
removed from or added to the toolbox.

Standard controls:

There are 21 standard controls in VB6.0 which are seen in the standard
toolbox. This section deals with the descriptions, properties and methods of these
controls.

Label control:
A label control displays text that the user cannot edit. You can use labels to
identify controls, such as text boxes and scroll bars that do not have their own caption
property. Labels can be transparent, so that the text appears to be placed directly on
the form.

Adding labels to the form


Adding labels to the form is just like adding any other controls to the form
Setting property to the for the labels
At this oint, the above box has three lables. Let‟s start with the one at
the top of the window. Select it and change the properties to match the following

Property value
Name ibititle
Caption controls tutor

Next, you should open the font property page and make the font as large as possible,
with bold styling. After doing this, you may have to resize the label so that all of the
text is visible. There are two ways to resize a control
Select the control and drag one of its sides with a sizing handle.
Change the width or height property of the control.
The Auto size property causes controls to automatically increase their size so that
anything being displayed within them is fully visible.
Select the label in the middle of the form and change the following properties

Property value
Name ibi About
Auto size true
caption written by scott L warner for teach yourself visual basic.
Change the following properties for the lable at the bottom of the form:

Property value
Alignment 2-center
Appearance 0-flat
Back color button face
Name ibi close
caption ok
in addition to changing the preceding properties, increase the font size to 14.
Now, all of the properties are set the labels of the about box, which should look
similar to the below figure

Adding codes for labels


Generally, labels do not have any code associated with them. They are mainly
used to describe other controls, but it is possible to add code to labels. Our project is
going to have code for ibi close that closes the about box opens the main form. To add
the code, complete the following steps

1. Select frm about in the project explorer.


2. Click the view code button

Enter the following code


Private sub ibi close _ click ()
Frm Main. Show
Unload me
End sub

Textbox control:
Text boxes are versatile controls that can be used to get input from the user or
to displayed text. The icon in the toolbox for a text box show the letters ab, . It is
used to display an it allows to accept text from the user.

Properties
Gives the textbox its own identity alwsys starts with text.

Text
To text that appears on the text box whether user given data or result.

Alignment
This property controls how text is displayed
0-left alignment (default)
1-right alignment
2-center alignment

Multiline

Command button control:


Command button allows the user to simply click
them to perform actions. It is also called as push button.
When the user chooses the button, it not only carries out
the appropriate action, it also looks as if it‟s being
pushed in and released.
Whenever the user clicks a button, the click event
procedure is invoked. You place code in the click event
procedure to perform any action you choose.

Properties
The properties of the command button are as follow

The caption
This property determines what the user sees on the face of the button. To
change the caption of the command button, move to the properties by using the mouse
or the UPARROW and DOWNARROW key (shift + ctrl + c).

Visible
It determines whether the command button is visible or not it can only be set
to true or false.

Enabled
It sets to true/false set this property to false to make the command button
unusable. ([i.e] it will not respond to any event concerning that button)

Font
It controls which font is used for the caption of the button. The font
characteristics – bold, italic, font name an so on.

Height, width
These properties define the height and width of the command button. The
height of the button. The width property changes the width of the button.

Left, top
It determiner the distance between the command button and the left edge and
top of the form.

Mouse pointer
By setting this property the mouse pointer is something different than the
usual arrow.

Disabled picture, down picture, picture, style.


To giving a command button a picture in its normal state, we can set a special
picture when the control is disabled or when it is clicked. it style property to display a
picture in command button.

Events for command buttons


The command button supports the following events. Change, click, double
click, key press, key up ,key down, mouse down, mouse move, lost focus, get focus.
Example
Private sub command button-lost focus ()
End sub

Access keys
VB makes it easy to set upon access key. For any object that has a caption, all
we have to do is place an ampersand (&) in front of the letter we want to be the access
key.

Property window when application is running, we can activate this


button either by pressing the ALT + C. combination or by clicking on the
button.
Frame control:
In most cases, you will use the frame control
Passively-to group other controls.

Image box control


Image controls hold pictures. The tool box icon for
an image control is the sun over a mountain . it can be used to display icons or
pictures. They can also holds window metafiles or JPEGS or GIFS. Jpegs format I
also the common format used by most digital cameras.

Properties of image controls

Border style-> it has only two possible settings


0 settings-> have no border.
1 settings-> fixed single border.
Stretch-> it determines whether the image control adjusts to fit the picture or the
picture adjusts to fit the control. It sets true /false
False-> control resizes itself to fit the pictures
True->picture resizes to fit the control

Label box control


A label displays only read only text. But the caption of the label box can be
changed during runtime through code. It is always used to give messages to the user.
Example, if a text box is simply placed a user doesn‟t know what to enter in such
case a label box may be placed before explaining what to be entered in the ext box.

Properties

Name-> gives the control its own identity always start with label.

Caption->text that appears on the control

Auto size-> by setting this property to true, the width and height of the label is
changed automatically according to the text typed.

Word wrap-> set this property to true to enable word wrapping. This is automatically
set when we create a control array.

Example

If we copy a label box and then use VB prompt ask us whether to create a
control array or not, if yes then control array is created
Borer style
Font
Fore color

Back color ->use to give the control background color for this back style should be
selected us back style – 2 option
0-transparend- This does not set the selected .back color for the control.

1-opaque- sets the selected backcolor for the control

Message boxes
Message box s displayed which displayed a message to the user and waits for
the user to respond t is a model box

Syntax
Msgbox message inbox, type of box, title of box.

Example
Msgbox ”welcome”
Message box can hold maximum of 1024 characters.
The following table shows the constant value and their meaning

Constant value meanings


VB ok, only 0 display ok button only
VB ok, cancel 1 display ok and cancel button
VB abort retry, 2 display abort, retry and
Ignore ignore button.
VB yes, no cancel. 3 display yes, no and cancel
Button
VB yes, no 4 display yes no button
VB retry, cancel 5 display retry and cancel button
VB critical 16 display critical message icon

VB question 32 display warning questions

VB exclamation 48 display warning message


icon

VB information 64 display information

Message icon.

The grid
It is important for accurately positioning controls. In order to control the grid,
choose tools->options (ALT + T ,O) and then go to the general page on the options
dialog box there are 4propertes.

Show grid
Turn the grid on or off by changing the show grid setting the default setting is
on.

Grid width, grid height boxes


The width and height text boxes allow us to set the distance between grid
marks. The default is 10 twips.

Align controls to grid


This checkbox determines whether controls automatically move to the next
grid mark or whether they can be placed between grid marks.

Format -> align -> grid

Checkbox control:
A checkbox indicates whether a particular
Condition is on or off. You use check boxes in an
Application to give users true/false or yes/no options.
Because check boxes work independently of each other,
a user can select any number of check boxes at the
same.

Combo box control:


A combo box control combines the features of a
text box and a list box. This control allows the user to
Select an item either by typing text into the combo box, or
By selecting it from the list.
This control can actually take one of three
different form‟s, which is controlled by its style property.

 Dropdown combo
 Simple combo
 Dropdown list box
Properties

Name – gives the controls its own identity always starts with combo
Sel length – return the number of the selected text.
Sel start – returns the starting position of the selected text
Sel text – returns the selected text in some of their controls.
Style – it has 3 options
1. 0-droupdown – it looks like a textbox and no arrow is at
the end.
2. 1-simple combo - The user can select this choice using
up arrow or down arrow.
3. 2-droup down – it looks like a list box. In this we can
select the item from the existing list and user cannot
give his own choice as input

List and combo boxes


It consist of set of choices that are displayed vertically. A user can
select one or more items format. If the set or number of items is more than the size of
the lit item is more than the size of its box then a scrollbar is included in it. The user
cannot edit the data in a list box directly.

Properties

1. Name – it gives the control its own identity. Always starts with list.
2. Sel count – displays the number of selected items in the list box.
3. Style – it has 2 options
 0-standared – it is default style in which a check box
is not included before an item
 1-chicked – it displays or include a checkbox before the
item. It is possible only when the multiselect property is
set as none

Using control arrays:


A control array is a group of controls that
share the same name and type. They also share the same
event procedures. A control array has at least one
element and can grow to as many elements as your
system resources and memory permit; its size also
depends on how much memory and windows resources
each control requires. The maximum index you can use
in a control array is 32767. Elements of the same control
arrays have their own property settings.

Advantages of using control arrays:


Adding controls with control arrays uses
Fewer resources than simply adding multiple controls of
the same type of a form design time. Control arrays are
also useful if you want several controls to share code. For
Example, if three option buttons are created as a control
array, the same code is executed regardless of which
button was clicked.

Creating a control array at design time:


There are three ways to created a control
array at design time;

Assign the same name to more than one control.


Copy on existing control and then paste it onto the form.
Set the control‟s index property to a value that is not null

Adding to a control array at run time:

You can add and remove controls in a control array at run time using the load
and unload statements. However, the control to be added must be an element of an
existing control array. You must have created a control at design time with the index
property set to „0‟. Then, at run time, use this syntax to load and unload the controls.

Load object (index %)


Unload object (index %)

Where:

Object is the name of the control to add to or delete from the control
array.
Index is the control‟s index value in the array.

Using tab order:

When using windows applications, you can use the tab key to move the focus
to one control to another. This is a feature that many users have come to depend upon.
Well-planned forms can be worked with using only the keyboard. By using the tab
key to move from one control to the next. For example, when filling out a from that
asks for a name and birthday, such as, you can use the tab key to move the focus from
one control to another. The focus should original be on the text box for the first name,
then middle initial ,last name, and birthday.

WORKING WITH STRINGS:

Introduction to string:

Strings are variables and constants that hold alphanumeric values.


These are values that you want to display but will not usually use for mathematical
calculation.
In visual basic, a sequence of alphanumeric characters treated as a
single value. Literal strings are assigned by enclosing the value in quotation marks, as
seen below:

Lblmessage.caption=”answer is incorrect”

Working with text strings:


Visual basic string function can manipulate strings in applications.
These functions are sued to return information about a string, extract only a certain
portion of a string or display information in a certain format.

Function Action
Strcomp compare two strings.
Lcase, Ucase convert to lowercase or
uppercase.
Space, string create string of repeating
character.
Len find length of a string
Lset, Rset justify a string
Instr, left, ltrim, mid, right, trim manipulate strings
Strconv convert strings
Asc, chr returns numeric or character
value

Function to find length string:

Len;
The Len function counts the characters in a string
and returns the length as an integer.

Syntax:

Length= Len (string)

Example:

Debug. Print Len (“mango”)

Result:5

Function to manipulate string:

Instr

The instr function returns the first position of a string.


If the substring isn‟t found. Instr returns a 0.

Syntax:

Instr ([start position,] string, substring)

Where:

1. Start position is a numeric expression that sets the start position for the
start position for the search of substring in string. If start position is
omitted, instr begins searching at the first position.
2. String is the string being searched.
3. Substring is the string you are looking for in string.

Left
The left function returns characters from the left
hand side.
Syntax:

Left (String, length)

Where:

1. String is the string from which you are return characters.


2. Length is the number of characters to return.

Right
The right function returns characters from right
hand side of string.

Syntax:

Right (string, length)

Where:

1. String is the string from which you are return characters.


2. Length is the number of characters to return.

Mid
The mid function returns characters from any part
of a string.

Syntax:

Mid (string, start[,length])

Where:

1. String is the string from which you are return characters.


2. Length is the number of characters to return. If this is omitted then all
the characters from the start position to the end of the string are
returned.

Ltrim
The ltrim function strips leading spaces from a
String.

Syntax:

Ltrim (string)

Where:

1. String is the string that should be stripped off the leading spaces.
Rtrim
The trim function strips triling spaces from a
string.

Syntax:

Rtrim (string)

Where:

2. String is the string that should be stripped off the trailing spaces.

Example:
Debug.print rtrim (“hello world”)&”!”
Debug.print”hello world “&”!”

Result:
Hello world!
Hello world !

Trim
The trim functions strips leading and triling spaces from a string.

Syntax:
Trim (String)

Example:
Debug.print trim (“ hello world “)& Len (trim(“hello world”))

Result:
Hello world11
Hello world 22

Using comparing string:

Strcomp
In case-sensitive comparisons, capital letters have a
Different value than lowercase letters. Remember that the ASCII value of a lowercase
letter is greater than the capital letter by32;asc (“a”)=65and that the ASC(“a”)=97.
in case-sensitive comparisons, “A”=”a” returns false.

The strcomp function returns a value indicating the


result of string comparison.

Syntax:
Strcomp (string1,string2[,compare])
Where:

1) String1 and string2 are any valid string comparision-0 for case sensitive
comparisions.

The true values for strcomp:

Return value comparion


-1 string1<string2
0 string1=string2
1 string1>string2
null string1 or string2 is null

The following code returns the value when two strings are compared in the
binary(case sensitive) or textual(non case-sensitive) format.

FORMATTING STRING:

The format function is used to format dates, numbers and string with
ease. You can choose from format‟s predefined named formats, such as currency or
fixed, or insist on finer control by creating your own user-defined format.

The format function returns a string, which you can use for either screen or
pointer output.

Syntax:
Format (expression [,format[,first day of week[,firstweekofyear]]])

Named numeric formatting:

Format name description


General number display the number without any thousands separator

Currency displays the number depending on the


Setting for currency configure in the control panel.

Fixed displays a minimum of one digit to the left and two to


the right of the decimal point.

Standard the same as fixed, except that the number is also


formatted with thousand separators.

Percent displays the number as a percentage by


Multiplying it by 100 first. The number
Always displayed with two digits to the right of the
decimal point and with the trailing percent sign.

Scientific uses standard scientific notation.


Yes/no displays no if the number is zero; otherwise displays
yes.

True/false displays false if the number is zero;


Otherwise displays true.

On/off displays off if the number is zero; otherwise displays


on.
______________________________________________

Example:

Dim myint as integer


Dim mysingle as single
Myint=1234
Mysingle=0.01234
Debug.print format (myint, “general number”)
Debug.print format(myint, “currency”)
Debug.print format(myint, “fixed”)
Debug.print format(myint, “standard”)
Debug.print format(mysingle, “percentage”)
Debug.print format(mysingle, “scientific”)
Debug.print format(false, “yes/no”)
Debug.print format(50, “true/false”)
Debug.print format(true, “on/off”)

Result:

1234
$1,234.00
1234.00
1,234.00
1.23%
1.2se-02
no
true
on
Manipulating strings:

String can be manipulated in many ways. Parts of the string can be trimmed
off to eliminate unwanted characters. Functions can extract portions of a string or add
a series of characters to a string. The following sections address each of these
possibilities.

Comparing string:

Searching for a letter, phrase, or pattern in a string can be difficult. However,


visual basic has several functions and operators that make this task a little easier. Use
these when you need to find a particular string or a particular word within a string.

User defined numeric formats:

There are occasions, when these named formats will not be enough and
you will require more control over your number formats. In these situation, you may
use a combination of a series of special formatting characters to control exactly how
the formats your numbers.

Example:
Dim mysingle as single
Dim myinteger as integer
Dim mycurrency as currency
Mysingle=0.23
Myinteger=123
Mycurrency=12234324.9
Debug.print format(myinteger, “00000”)
Debug.print format(myinteger, “#####”)
Debug.print format(mysingle, “###%”)
Debug.print format(mycurrency, “###,###,##0.00”)
Debug.print format(0,”###,###,##0.00”)
Debug.print format(mycurrency, “\$###,###,##0.00”)

Result:
00123
123
23%
12,234,324.90
0.00
$12,234,324.90

More on strings
Strings are variables and constant that hold alphanumeric values. To
concatenate two strings, use the ampersand (&)

Example
Title$ = “queen”
Name$ = “Elizabeth”
Numerals$ = “I”
First Elizabeth = title$&name$&numeral$
Current queen = title$&name$&numerals$&numerals$.

Output
Queen Elizabeth I
Queen Elizabeth II

ANSI/ASCII codes

ASCII – American standard code for information interchange.


ANSI – American national standard institute.
The value of the function chr (n) is the string consisting of the
character of ASCII value of n. the statement,
Print chr (34)

Example
Print chr (2270->prints the letter pi(п)

Example
Print chr(34);
Print “Welcome”
Print chr(34);

Output
“Welcome”
The value 34 display quotation marks.

Built-in string constants


The new lines are made up of two parts.
Carriage return – bring the cursor to the first column
Line feed – move it t next line.
In terms of the chr function, the newline code is
Vbcrlf = chr(13) & chr(10)
Character symbolic constant
Null character VB Nullchar = chr$(0)
Carriage return VB cr = chr$(13)
Line feed VB lf = chr$(10)
Back space VB Back = chr$(8)
Tab VB Tab = chr$(9)
Vertical tab VB vertical tab = chr$(11)
Form feed VB form feed = chr$(12)

Fixed length string


A fixed length string is a special type of string

Example
Dim shortstring as string * string*10
Dim strshort as string *10

This variable will always hold strings of length 10.


Short string = “welcometoourcollege”
We will get
Short string=”welcometoo”

More on numbers
When we write the code to assign a value to a numeric variable in VB, w can‟t
use comma to delineate thousand, VB will not let we enter code like;

Dim I as integer
I = 1,234

We can use a decimal point, but if we assign such a number to an integer


variable, it will automatically be rounded to an integer value. If we assign a number
larger than the limits for the given variable, VB will give us an error message at run
time.

Declaring variables:

Before going going into the details of declaring variables for storing numeric
values, let‟s review the different numeric data types. The following are the numeric
data types in visual basic:

 Byte
 Integer
 Long
 Single
 Double
 Currency

Assigning values to numeric variables:


Values are assigned to numeric variables in essential the same way that values
are assigned to strings, using the = operator.

Example for numeric value:

Intexample=1
Intexample=returntwo
Intexample=”3”

Numbering system:

There are three different numbering systems that are commonly used in visual
basic:

 Decimal
 Hexadecimal
 Octal

Using numeric operators:

The values of numeric variables are often manipulated to derive new values.
These variables are manipulated using operators, such as + and- this allows
applications to dynamically determine numeric values. For example, the amount
someone should be paid for a week‟s work can be determined by multiplying(*) the
number of hours worked by the amount paid for each hour of work. Further
operations could be performed to determined the amount of taxes to be taken out of a
paycheck..

Numeric operator
The five fundamentals arithmetic operations

Operator operations
+ Addition
- Subtraction (denotes
Negative number)

/ division
* Multiplication
^ Exponentiation
\ Integer division
(Back slash)

Arithmetic operators:
The following sections discuss the arithmetic operators available in visual
basic. Trigonometric functions are discussed later in this chapter in the section “using
trigonometric functions”.

Math functions:

The math functions are visual basic help perform common mathematical tasks
to determine values that night otherwise be difficult to determine. As you build
applications. For example, if you don‟t create applications that perform complex
drawing and graphing you may never use the trigonometric functions.

Using ABS function:

The abs function returns the absolute value of a number. An absolute value is
not positive or negative. It is the value of a number without regard to being negative
in value. For example, both of the following statements set in example equal to 10:

Intexample=abs(10)
Intexample=abs(-10)

Using the exp and log functions:

The exp function returns the value of (approximately 2,718282)raised to the


power of the number that is passed as an argument.

Syntax:

Exp(number)

And also the fix and int functions are essentially the same:

Syntax:

Fix(number)
Int(number)

Using random numbers:

Random numbers can serve many purposes in an application. They can be


used int computer games to randomly affect behavior and give a new experience each
time the game is played. Engineering application might use them to build statistical
models. Many applications can use these numbers to test their own operation. The
testing is made more powerful by the fact that the same sequence of random numbers
can be generated over and over again, which provides the ability to make changes to
the application and then monitor the effects of those changes.

Using the rnd function:

The rnd function generates a random number that is less than 1 and greater
than 0. it returns the value as a single data type, using the following syntax:

Rnd[(number)]

Using the randomizing statement:

The randomize statement initializes the random-number generator. The syntax


for the randomize statement is as follows:

Randomize [number]

UNIT-III

Using dialog boxes:

A dialog box is a special window displayed by the system or application to


request a response from provide information to the user.

Control structures:

Decision making statements:

Conditional structures allow applications written in visual basic to respond to


different situations depending upon the result of condition. The condition can be a
comparisons or any expression that evaluates to a numeric value.

The available conditional structures are:

o If…….then statements

o If……..then …..else statements

o If……..then……elseif statements
o Select case statements

In general, you use an if…..then statement when an „either/or‟ decision must


be made. When your program must select mare than one alternative. Use one of the
other structures, choosing among them based upon the structure that is most efficient
for your needs.

The relational operators and the logical operators are used in the condition
portion of the if…..then block.

If more than one of the conditions in a conditional structure is true, only the
code statements enclosed by the first true condition are executed.

If……then statements:

If……then statements evaluate whether a condition is true or false and direct


the program‟s flow accordingly, if…..then statements can use either single-line or
multiple-line syntax.

Single-line:

If condition then clause

Example:

If intCPUtemp>125 then msgbox”CPU is overheating”


Multiple line:

If condition then
Statements
End if

If......then….else statements:

if…..then ….else statements are an elaboration on the if…..then concept. An if


…..then….else block allow you to define two blocks of code and have your program
execute one based upon the result of a condition.

If condition then
[statements]
else
[statement]
end if

Example:

if intvar1> intvar2 then


msgbox”the greater no. is”& intvar1
else
msgbox”the greater no. is”& intvar2
end if

If……then…elseif statements

If……then….elseif statements are like if……then…..else statements except


that they allow for your program to choose from more than two alternatives. Then
if…..then……elseif statements uses the following

syntax:

If condition1 then
[statements]
elseif condition2 then
[statements]
else
[statements]
else if

select case statements:

select case structures are similar to if….then….elseif structures in that they


allow your program to choose from more than two alternatives. However, the select
case structure can be more efficient because it evaluates the test expression only once.

This example shows the syntax for the select case structure:

Select case test expression


[case expressionlist1]
[statements]
[case expressionlist2]
[statements]
[case else]
[else statements]

end select

select case structure is deal for testing the value of an expression against
ranges possible values. This example shows how to use the select case structure to
evaluate a number against four different ranges and determine a bonus based on an
individual range of values.

Select case int test number


Case 1 „if equal to 1
Bonus=0 „bonus is 0
Case 2,,3 „if either 2 or 3
Bonus=.05 „bonus is 5%
Case 4 to 6 „is between 4 and 6
Bonus=.10 „bonus is 10%
Case else „if anything else
Bonus=.2 „bonus is 20%
End select

Looping structures:

Looping structures allow you to specify the conditions under which you would
like your program to execute a set of instructions repetitively. To determine which
looping structure to use, consider two questions:

Visual basic supports these looping structures:

 Do….loop
 For….next

Do…..loop structures:

Do…..loop structures give your program the ability to execute a block of code
an indeterminate number of times. While there are several variations of the do loops,
they fall into two major categories: loops where an expression is evaluated at the end
of the loop, and loops where the expression is evaluated at the beginning.

The loop structures that evaluate the expression at the end are:

Do….loop while. Repeats the code block until the test expression evaluates as
false.
Do….loop until. Repeats the code block until the test expression evaluates as
false.

Do….loop while

Do……loop while structures check the condition after executing the code and
repeat a code block untile the test expression evaluates as false. Do……loop while
structures use the following syntax:

Do
[statement]
loop while[condition]
for example, this code will loop untilled the correct password is entered:

do
passwd =inputtext(“enter your password”)
loop while passwd<>”Rajesh”

Do……loop until

Do…….loop until structures check the condition the code and repeat a code
block until the test expression evaluates as true. Do…..loop until structures use the
following syntax:

Do
[statements]
loop until[condition]

for example, this code do loop until the no button is clicked in a message box.

Do
Loop count=loopcount+1
Loop until Msgbox(“loop….?,vb yes no)=vbno

Do while……loop

Do while…….loop structures check the condition before exe3cuting the code.


The code in the loop is executed only if the condition evaluates to true, and repeats
until the test expression evaluates as false.
Do while…..loop structures use the following syntax:

Do while condition
[statements]
loop

This example test for the end file condition and reads lines until the end of the file is
reached:

Do while endoflife=true
[read and process next line in file]
[set endoffile to true if end of file is encountered]
loop

Do until….loop
Do until….loop structures check the condition before executing the code. The
code in the loop is executed only if the condition evaluates as false, and repeats until
the test expression evaluates as true.
Syntax:

Do until condition
[Statements]
Loop

Example:

Do until endoffile=true
[read and process next line in file]
[set endoffile to true if end of file is encountered]
loop

For…..next statement

When you know how many times a code block will execute, it is easier to write and
maintained. The for…..next statement executes a code block a specific number of
times.
Syntax:

For counter=start to end[step increment]


[statements]
next [counter]

Example:

Intnumstud=inputbox (prompt:= “how many students?”)

For intcounter=1 to inttumstud


Sglscore=CSng(inputbox(prompt:=”enter score”))
Sgltotalscore=sgltotalscore+sglscore
Next intcounter

Sglaverage=sqltotalscore/instnumstud

Exiting a loop

The exit statement allows you to exit directly from a for…..loop, do loop, sub
procedure, or function procedure. Syntax:

Do until[condition]
[statements]
if[condition]then
exit do
end if
loop

for counter= start to end[step increment]


[statements]
if[condition] then
exit for
end if
next[counter]

UNIT-IV

Dialog boxes:

A dialog box is a special window displayed by the system or application to request a


response from or provide information to the user.

Types:

Predefined dialog boxes- created using inputbox() and


Msgbox()function.
Customized dialog boxes-created using a standard form or by
customizing am existing dialog boxes.
Standard dialog box- file open dialog box, print dialog box created
using the common dialog control.

Modal and modeless dialog boxes:

Dialog boxes are either modal or modeless. A model dialog box must be
closed(hidden or unloaded) before you can continue working with the rest of the
application. For example, a dialog box is modal if it requires you to click ok or cancel
before you can switch to another form or dialog box.

Example:

Form1.show vbmodal

The above code displays the form as a modal dialog box.

Modules dialog boxes let you shift the focus between the dialog box and another form
without having to close the dialog box. You can continue to work elsewhere in the
current application while the dialog box is displayed.modless dialog boxes are rare.
From the edit menu. The find dialog box in visual basic is an example of a modules
dialog box.

Predefined dialog boxes:

Predefined dialog boxes can be added to the application easily by using the
inputbox function and the Msgbox function. The predefined dialog boxes are always
modal.

Creating dialog boxes using inputbox():

The inputbox()displays a prompt in a dialog box, waits for the user to input
text or click a button, and returns a string containing the contents of the text box.
Syntax:

Inputbox(prompt[,title][,default][,xpos][,ypos])

Creating dialog boxes using the Msgbox ()

The Msgbox() displays a message in a dialog box, waits for the user to click a
button, and returns an-integer indicating which button the user clicked.

Syntax:
Msgbox(prompt[,buttons][,title]

Using the Msgbox function:

The Msgbox function displays the dialog box that is created using the
arguments supplied to the function. This is a simple dialog box that displays a
message and accepts feedback from user only through the form ofd closing the dialog
box-no text can be entered by the users.
Many times this function is used to supply information to users without
expecting any feedback for example the following dialog box is used to notify the
user that it has completed its search and the item was found.
The user has no choice but to press the ok button to close this dialog box.

Displaying information using the Msgbox function:

Displaying information is the most basic task for the Msgbox function.

The following syntax is use for this function:

Msgbox(prompt[,buttons][, title][, help file][, context]

The prompt is the only argument that is required for the Msgbox function.

Interacting using the Msgbox function:

An application can interact with a user by changing the optional buttons


parameters of the Msgbox function. The buttons parameter is a numeric-expression
that determines the following items:

 Number and type of buttons


 Icon displayed
 Default button
 Modality
Each possibility for the items in the equates to a numeric value.

Using the inputbox function:


The Msgbox function creates dialog boxes that convey information to users
and can even interact with the users. However, this interaction is restricted to limit‟s
numbers of predetermined possibilities. To give the user the ability any value they
with use the inputbox function.

Syntax:

Inputbox(prompt[, title][, default][, xpos][, ypos][, help file, context]

The prompt and title arguments have the same effect on dialog box created
with inputbox as they did using Msgbox- as do the help file and context arguments. In
addition, only the prompt argument is required.
The inputbox returns a string value. If the user click oj\k button or presses the
enter key, the string contained in the text box is returned. But if the user clicks the
cancel button or presses the esc key, an empty string is returned, regardless of what
the text box contains.

Using the common dialog control:

The windows operating system contains a set of dialog boxes that are used to
complete frequently used tasks, such as the following:

 Open a file
 Save a file
 Select a color
 Select a font
 Print or change print options
 Show help
These dialog boxes are defined in COMDLG32,OCX, which must be present
in the windows system directory. Visual basic‟s common dialog control contains and
provides access to the dialog boxes defined in this file.
The common dialog box control is a non-visual object, meaning that it is
never visible at run time. Because of this, it can be placed any where on a form
without regard to the way it looks or how it interacts with users; it si never seen and
has no direct interaction with users.

Open and save as dialog boxes:

Any application that deals with opening and saving files needs a mechanism
for doing so. The common dialog control offers a solution for both: the open and save
as dialog box. These dialog boxes are discussed together because they are so similar.
The only different between them is the default dialog title and the caption on the
action button.
The following dialog box ix opened using the shown open method of the
common dialog control.
Setting the properties of the open and save as dialog boxes:

The open and save as dialog boxes are affected by the same properties of the
common dialog control. At design time, these properties are set either in the
properties window or in the property page of the common dialog box, which is shown
in below.
Using the color dialog control box:

Application dealing with formatted text or graphics normally give users the
ability to change colors. A text editor might allow the color of the text to be changed
to emphasize a word or phrase, and varying colors are nearly a requirement for
graphical presentations. Although very specialized programs might required very
specialized input to make these types of adjustments in color, most applications
benefit from using the common dialog control color dialog box.

The RGB function also returns an RGB color code.


RGB(red,green, blue)
Using font dialog box:

The font dialog box allows to make choices about how text is displayed. This
dialog box offers choices based upon the fonts that are installed on the user‟s
machine. These fonts are divided into two categories: screen fonts and printer fonts.
Screen fonts determine how text is displayed on your monitor, and printer fonts
control the appearance of printed text.
The flags property of the common dialog control must be set to a value
specifying the fonts to be used before the shown font method is called to display the
font dialog box.

Example program

Print dialog box:


Display the print dialog box by calling the show printer method of the
common dialog control. This dialog box allows users to make changes to the way
output should be printing in visual basic.

Show help method:

As application become more complex, they need to be explained in more


detail. This translates into mre training and more documentation. Windows help files
are a very effective tool that allows users to quickly locate answers to their questions
from within the application.

Menu:

A menu in visual basic terms is a type of control. Menus like controls have
properties and events but do not have any methods. Also each menu8 item is a
separate menu control. You can set some of the properties of a menu when you add
the menu item using menu editor.

A menu control displays a custom menu for your application. A menu can include
commands, submenus and separate bars. Each menu you create can have up to four
levels of submenus.

Learning to use menu editor:


The menu editor is displayed with the help of the menu editor command
present in the tools menu. Use it to create custom menus for your application. You
can use the menu editor to create now menus and menu bars, add new commands to
existing menus, replace existing menu commands with your own commands. And
change and delete existing menus and menu bars.

SHORTCUT KEY: CTRL+E

From the tools menu, choose menu editor.


Or
Click the menu editor shown below.

The menu editor shown below:

Creating menus:

Menus are created using the menu editor, which is a dialog box. Submenus
and separator bars are also created with the menu editor. Most properties of menus
can be set in the properties window.

Creating menu in the menu editor:

To open the menu editor, open a form in the form window. Then ,choose
menu editor from the tools menu or press ctrl+e shows the menu editor with no
entries.
Adding menu commands:

The first level of a menu provides only the titles to be displayed in the menu
bar. At this stage, nothing would happen if you ran the application and clicked on one
of the menus. Menu items must be added to the next level of the menu structure.
These items appear as commands in the menu of the title in the level immediately
above them.

To add commands to the file menu, complete the following steps:

i. Open the form from the previous section in the form window.
ii. Open the menu editor.
iii. Select the edit menu from the list box at the bottom of the dialog box.
Adding submenus:

Visual basic allows you to create up to five levels of submenus for each menu
title.

Adding separator bars:

I. Open the form from the previous section in the form window.
II. Open the menu editor.
III. Select the save menu from the list box at the bottom of the
dialog box.
IV. Click the insert button.

Adding code to menus:

The menu editor creates a menu structure; menu titles, menu commands,
submenu, separator bars, access keys, and shortcut keys. These menu items work
together to present users with a series of these menu items work together to present
users with a series of commands in a logical manner. However, the menu editor only
creates the structure of the menu. The commands that the menu items.

Creating shortcut menus:

Many windows application provide shortcut menus to make users more


productive. These menu appear when users click the right mouse button for example,
right-click on a. Text box should open a shortcut menu that deals with text, but the
same menu doesn‟t make sense to appear to appear. If right-click on a graphics
display.

Picture box control:

The picture box control is used to display graphic image from a


bitmap, icon or a metafile. It can display icons, gifs, jpegs, and jpg. It clips the
graphic if the control isn‟t large enough to display the entire image. It also acts a
container for other controls. It allow us to place graphics information to the form.
The icon in the tool box for picture boxes looks like a desert scene. It looks

like . The main difference between picture boxes and forms is that we use the
height and width properties of the picture box rather than the scale height and
scale width properties of the form. There are two ways to display an image inside
a picture box at design time. The first is to load a picture by setting the picture
property via the properties window. Another is to paste a picture directly into the
picture box choose edit/paste (ALT + E, P (or) CTRL + V).
To add a picture while a VB project is running. Suppose we
have two picture boxes, picture1, picture2, and picture1 has an image and pictue2
does not have image. Then a line of code like

Picture2.picture = picture1.picture.

Copies the image from the first picture box to the second picture box.

Syntax
Picture box name. Picture = load picture ([file name])
Or, for forms
[Form name].picture = load picture ([file name])
Properties

Auto size - If true, automatically resizes the controls to display its entire
contents otherwise false.

Picture - Returns or sets a graphic to be displayed in a control.

Current x - Return or set the horizontal (current)

Current y – It is a vertical coordinates for the next printing or drawing method.

Events
The events are click, double click event or key events.

Methods

Cls- clear graphical and text generation at run time from a picture box.

Syntax
Object.cls

Move – move the picture box around at runtime.


Circle – draws a circle, ellipse, or arc on an object
Line – draws a line and rectangles on an obect.
Example –program (form design window)

Coding window

Output
Textbox:

Text boxes are versatile controls that can be used to get input from the user or
to display text.

Rich text box

It allows the user to enter and edit text while also providing more advanced

formatting features than the conventional text box control. The icon looks like
Toolbox controls is a custom controls, we will add it to the toolbox if it is not
already there to do this
choose project-> components ->components dialog box opens.
Choose Microsoft rich text box control 6.0
The properties of rich text box are as follows.

Sel length – returns or sets the number of characters selected.


Sel start – returns or sets the starting point of the selected text.

Sel text – returns or sets a string equal to the currently selected text.
Sel bold – change the currently selected text to bold.
Example
rich text box1.sel bold = true

Sel italic - change the currently selected text to italic.


Example
rich text box1.sel italic = true

Sel strike thru – change the currently selected text to strike thru.

Sel underline – change the currently selected text to underline.

Sel color – set the color to the currently selected text.


Example rich text box1.selcolor = vb red.

Sel font name – it allow us to change the font.


ExampleRich text box.sel font name = “Arial”

Sel font size – it lets us to change the size of the currently selected text.
Syntax
Object Sel font size = size
Maximum value of Sel font size is 2,160 points

UNIT-V

Files:
A file consists of a series of related bytes located on a disk. When your
application accesses a file, it must assume what the bytes are supposed to represent (
characters, data records, integers, string, and so on).
Depending upon what kind of data the file contains, you use the appropriate file
access type. In visual basic.
There are three types of file access:

Sequential
Random
Binary

Functions and statements used with all three types of file access:

Dir()
Syntax:
Dir[(pathname[,attributes])]

Filelen()
Syntax:
Filelen(pathname)

Lof()
Syntax:
Lof(filenumber)

Eof()
Syntax:
Eof(filename)

Freefile()
Syntax:
Freefile[(Rangenumber)]

Fso
Fso is a part of Microsoft scripting runtime. which is referred to as scripting.
Fso is a class with in the scripting application

Syntax
Set fso = create object(“scripting .fso”)
To create an object that provides access to the computer file system.

Example
Dim fso as object
Set fso = create object(“scripting .fso”)

Output
Set fso = nothing
Opening files
Fso is used to create a text file. It is method used to open a text file.

Example
Dim fso as object
Set fso = create object(“scripting.fso”)
Set ts = fso.open text file (“c:\a.text,8,true,-2).
Step 1: you can create fso object.
Step2: open text file methods create a text scream object and assigning to
variable.
Step3:the text is read form file ad return to the file using the text scream object.
step4: c:\a.text = it is a file name.
-2 it is open to a file using default
-1 it is open to a file using default Unicode.

Syntax
Set ts c=fso. Open text file, filename, iomode, create, format)

Database:

Visual basic is a convenient way to create front end


programs for database access.

Database terms:

There are many types of data base terms in visual basic (i.e),

 Sql
 Table
 Primary key
 Foreign key
 Indexes
 Queries
 Record set

Menus of visual basic data manger:

File menu
Utility menu
Window menu
Forms and dialog boxes
Visdata as a sample

Opening, closing and deleting files:

Visual basic provides several methods for working with files. This book
demonstrates the manipulation of text files using the file system object. The fso object
is an activeX object and provide all of the versatility and ease-of-use that you find in
most activeX object.

Opening file:

Before you can work with any text file, you need a reference to the file.
Obtaining this reference is commonly known as opening the file. The fso object uses
the opentextfile method to do this, as in the following:

Set fso=create object(“scripting.file system object”)


Set ts =fso.opentextfile(“c:\tyvb,txt”,b,true,-2)

Closing file:

after opening a file, you most likely perform several actions on the file. For
example, you might write several new lines of text to the file. When finished with the
file, you should close the file, which is done using the close method of the text stream
object.

Set fso=create object(“scripting. file system object”)


Set ts =fso.opentextfile(“c:\tyvb,txt”,b,true,-2)ts.close

Deleting files:

Certain files have a limited time span in which they are useful. For whatever
reason a file is no longer needed, the file is usually deleted to free up storage space.
Fso.deletefile filespec [,force]

Reading and writing to files:

After you are familiar with creating the fso object and using its open text file
method to return a text stream object, you can begin to manipulate the files that the
text stream object is associate with the following sections.

Reading from files:

Text could be retrieved from a file for a number of reasoned. The methods
used to retrieve the text can be just as varied. This section discusses the different
methods used to retrieve text from a file.

Dim fso as object


Dim ts as object

Reading characters:

Syntax:
Text stream7.read(characters)

Reading lines:

Syntax:

Textstream.readline

Writing to files:

Writing text to a file is a little simpler than reading it. Either you want to add
characters to the current line of text or you want to create a new line of text, in some
case, you might want to do both.

You might also like