You are on page 1of 52

Introduction to Visual Basic

•Character User Interface (CUI) - user needs to remember commands.


•Graphical User Interface (GUI) - provides user friendly environment.
•Visual Basic (VB) was derived from BASIC.
•VB is an ideal programming language for developing professional applications for
MS Windows.
•It provides facilities like text boxes, command buttons, list boxes, scroll bars,
grids etc.
•The latest version of VB is VB 6.0
•It makes use of GUI for creating robust and powerful applications.
What Visual Basic ?
• Visual Basic is a tool that allows you to develop Windows (Graphic User
Interface - GUI) applications. The applications have a familiar appearance
to the user.
• Visual Basic is event-driven, i.e code remains idle until called upon to
respond to some event (button pressing, menu selection, ...).
• Visual Basic is governed by an event processor. Nothing happens until an
event is detected.
• Once an event is detected, the code corresponding to that event (event
procedure) is executed. Program control is then returned to the event
processor.
Features of Visual Basic:
• Easier comprehension
• User friendlineness
• Faster application development
• Full set of objects - we 'draw' the application
• Lots of icons and pictures for our use
• Response to mouse and keyboard actions
• Clipboard and printer access
• Full array of mathematical, string handling, and graphics functions
• Can handle fixed and dynamic variable and control arrays
• Sequential and random access file support
• Useful debugger and error-handling facilities
• Powerful database access tools
• ActiveX support
• Package & Deployment Wizard makes distributing the applications simple
Visual Basic 6.0 versus Other Versions of Visual Basic
• The original Visual Basic for DOS and Visual Basic for Windows were introduced
in 1991.
• Visual Basic 3.0 was released in 1993.
• Visual Basic 4.0 released in late 1995 .
• Visual Basic 5.0 released in late 1996.
• Visual Basic 6.0 in 1998
• 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
• Additional internet capabilities
Visual Basic start up…

Starting a new project:


When we start VB, it assumes we want to work with new project. In the above figure we need to choose what is the kind of
the program we want to create. For creating a simple Visual Basic program, choose the Standard EXE,and press the Open
Components of Visual Basic IDE
VISUAL BASIC PROGRAMMING
Project

Form 1 Form 2 Form 3

Text box Button Button

Picture Text box


box
Objects Objects
Application (Project) is made up of:
• Forms - Windows that you create for user interface
• Controls - Graphical features drawn on forms to allow user interaction (text boxes,
labels, scroll bars, command buttons, etc.) (Forms and Controls are objects.)
• Properties - Every characteristic of a form or control is specified by a property.
Example properties include names, captions, size, color, position, and contents.
Visual Basic applies default properties. We can change properties at design time or
run time.
• Methods - Built-in procedure that can be invoked to impart some action to a
particular object.
• Event Procedures - Code related to some object. This is the code that is executed
when a certain event occurs.
• General Procedures - Code not related to objects. This code must be invoked by the
application.
• Þ Modules - Collection of general procedures, variable declarations, and
Steps in Developing Application
There are three primary steps involved in building a Visual Basic application:

1. Draw the user interface


2. Assign properties to controls
3. Attach code to controls
Drawing the User Interface and Setting Properties

Visual Basic operates in three modes.


• Design mode - used to build application
• Run mode - used to run the application
• Break mode - application halted and debugger is available
Form Window
• The Form Window is central to developing Visual Basic applications.
• It is where we draw our application.
Main Window
Main Window consists of the title bar, menu bar, and toolbar.
•The title bar indicates the project name, the current Visual Basic operating mode, and
the current form.
•The menu bar has drop-down menus from which you control the operation of the
Visual Basic environment.
•The toolbar has buttons that provide shortcuts to some of the menu options.
The main window also shows the location of the current form relative to the upper left
corner of the screen (measured in twips) and the width and length of the current form.
Toolbox
A ToolBox displays the Pointer Picture Box
standard Visual Basic Label Text Box
controls, ActiveX controls Frame Command Button
and insertable objects that Check Box Option Button
can be added in a form.
Combo Box List Box
Horizontal Scroll Bar Vertical Scroll Bar
Drive List Box
Timer
Directory List Box File List Box
Shapes Lines
Image Box Data Tool
Object Linking Embedding
Properties Window
•The Properties Window is used to
establish initial property values for objects.

•The drop-down box at the top of the


window lists all objects in the current form.

•Two views are available: Alphabetic and


Categorized.
Form Layout Window

The Form Layout Window shows where


(during program execution) our form
will be displayed relative to our
monitor’s screen.
Project Window

•The Project Window displays a list of


all forms and modules making up our
application.
•We can also obtain a view of the
Form or Code windows from the
Project window.
Placing controls on a form
• There are two ways to place controls on a form:
1. Double-click the tool in the toolbox and it is created with a default size on the
form. We can then move it or resize it.
2. Click the tool in the toolbox, then move the mouse pointer to the form
window. The cursor changes to a crosshair. Place the crosshair at the upper left
corner of where you want the control to be, press the left mouse button and
hold it down while dragging the cursor toward the lower right corner. When
you release the mouse button, the control is drawn.
• To move a control you have drawn, click the object in the form window and
drag it to the new location. Release the mouse button.
• To resize a control, click the object so that it is selected and sizing handles
appear. Use these handles to resize the object.
Moving and resizing a control

Use sizing
handles to
resize object
Click here to
move object
Sample Application 1 – Design Mode
Figure 3.3

Sample Application 1 – Run Mode


Source Code Window

Private Sub Command1_Click()


Text3.text = Val(Text1.Text) +Val(Text2.Text)
End Sub
Sample Application 2 - Design
Sample Application 3 - Design
Sample Application 4 - Design
Unit I - Variables
A storage location in memory (RAM)
 Holds data/information while the program is running
 These storage locations can be referred to by their names

Every variable has three properties:


 Name - reference to the location - cannot be changed
 Value - the information that is stored - can be changed during program execution, hence the name
“variable”
 Data Type - the type of information that can be stored - cannot be changed

• Usage of Variables
• Copy and store values entered by the user
• Perform arithmetic manipulation on values
• Temporarily hold and manipulate the value
• Hold data/information so that it can be recalled for use at a later point in the code
Unit I – Data type
Data type - Specifies type of data that a variable can store
• Integer variables: Long, Integer, Short, Byte
• Floating-point variables: Single, Double
• Boolean variables: True, False
• Character variable: Char
• Text variable: String
• Object variable
• Default data type assigned by Visual Basic
• Can store many different types of data
• Less efficient than other data types
Visual Basic Data Types

Data type Prefix Size Values


Byte byt 1 byte positive integer value from 0 to 255
Short shr 2 byte integer from –32,768 to +32,767
Integer int 4 byte integer from +/- 2,147,483,647
Long lng 8 byte integer from +/-
9,223,372,036,854,775,807
Single sng 4 byte single-precision, floating-point number
Double dbl 8 byte double-precision, floating-point number
Decimal dec 16 byte number with up to 28 significant digits
Char chr 2 byte Any single character
Boolean bln 2 byte True or False
String str 4 byte Text - Any number/combination of characters
Date dtm 8 byte 8 character date: #dd/mm/yyyy#
Object obj 4 byte An address that refers to an object
Rules for naming a variable
First character must be a letter or underscore
Must contain only letters, numbers, and underscores (no spaces,
periods, etc.)
Can have up to 255 characters
Cannot be a VB language keyword
Naming Conventions
 Should be meaningful
 Follow 3 char prefix style - 1st 3 letters in lowercase to indicate the data type
 After that, capitalize the first letter of each word
 Example: num1, testresult
Declaring a Variable
• A variable declaration is a statement that creates a variable in memory
• Syntax: Dim VariableName As DataType
• Dim (short for Dimension) - keyword
• VariableName - name used to refer to variable
• As - keyword
• DataType - one of many possible keywords to indicate the type of value the variable
will contain
• Example: Dim intLength as Integer
Declaring and Initializing a Variable
• A starting or initialization value may be specified with the Dim statement
• Good practice to set an initial value unless assigning a value prior to using
the variable
• Syntax:
Dim VariableName As DataType = Value
Just append " = value” to the Dim statement
= 5  assigning a beginning value to the variable
• Example: Dim intLength as Integer = 5
Default Values for Data Types
Data type Default (Initial) value

All numeric types Zero (0)


Boolean False
Char Binary 0
String or Object Empty
Date 12:00 a.m. on January 1, 0001
Tool Box Controls Picture Box
Pointer
Label Text Box
Frame Command Button
Check Box Option Button
Combo Box List Box
Horizontal Scroll Bar Vertical Scroll Bar
Drive List Box
Timer
Directory List Box File List Box
Shapes Lines
Image Box Data Tool
Object Linking Embedding
Command Button
Pointer Picture Box
Label Text Box
Frame Command Button
Check Box
Option Button
Combo Box List Box
Horizontal Scroll Bar Vertical Scroll Bar
Timer Drive List Box
Directory List Box File List Box
Shapes Lines
Image Box Data Tool
Object Linking Embedding
Tool Box Controls- Command Button
• Buttons in Visual Basic are called "Command Buttons".
• It is the most widely used control.
• It is used to begin, interrupt, or end a particular
process.
• To add a button, click on the Command Button icon in
the Toolbox.
Command Button Properties:
Name Name property is the one by which the control is identified and it is referred as

the object name of that control.


Appearance Selects 3-D or flat appearance.
Caption String to be displayed on button.
Default Allows selection of button with Enter key (only one button on a form can have
this property True).
Font Sets font type, style, size.
BackColor Specifies the command button's background color.
Height Used to set the height of the command button .
Width Used to set the width of the command button .
ToolTipText Holds the text that appears as a ToolTip at runtime.
Visible Determines whether the command button appears or is hidden from the user.
Command Button Events:
Click Event triggered when button is selected either by clicking
on it or by pressing the access key.
Sample Application

Private Sub Command1_Click()


Print "This is Command1"
End Sub

Private Sub Command2_Click()


Print "This is Command2"
End Sub
Text Box
Pointer Picture Box
Label Text Box
Frame Command Button
Check Box
Option Button
Combo Box List Box
Horizontal Scroll Bar Vertical Scroll Bar
Timer Drive List Box
Directory List Box File List Box
Shapes Lines
Image Box Data Tool
Object Linking Embedding
Tool Box Control- Text Box Contd….
A text box is used to display information entered at design time, by a user at runtime, or assigned
within code. The displayed text may be edited.
Text Box Properties:
• Appearance Selects 3-D or flat appearance.
• BorderStyle Determines type of border.
• Font Sets font type, style, size.
• MaxLength Limits the length of displayed text (0 value indicates unlimited length).
• MultiLine Specifies whether text box displays single line or multiple lines.
• PasswordChar Hides text with a single character.
• ScrollBars Specifies type of displayed scroll bar(s).
• SelLength Length of selected text (run-time only).
• SelStart Starting position of selected text (run-time only).
• SelText Selected text (run-time only).
• Text Displayed text.
Tool Box Control- Text Box Contd….
Text Box Events:
• Change Triggered every time the Text property changes.
• LostFocus Triggered when the user leaves the text box.
• KeyPress Triggered whenever a key is pressed.

Example
• txtExample.SetFocus ' moves cursor to box named txtExample

Sample Application : To add three numbers and display the result.


Label Box
Pointer Picture Box
Label Text Box
Frame Command Button
Check Box Option Button
Combo Box List Box
Horizontal Scroll Bar Vertical Scroll Bar
Drive List Box
Timer
Directory List Box File List Box
Shapes Lines
Image Box Data Tool
Object Linking Embedding
Tool Box Control- Label Box
A label box is a control used to display text that a user can't edit directly.

Label Properties:
Name Displays the name of the label button
Alignment Aligns caption within border.
Appearance Selects 3-D or flat appearance.
AutoSize If True, the label is resized to fit the text specified by
the caption property. If False, the label will remain the
size defined at design time and the text may be clipped.
BorderStyle Determines type of border.
Caption String to be displayed in box.
Font Sets font type, style, size.
Tool Box Control- Label Box
Label Events:
• Click Event triggered when user clicks on a label.
• DblClick Event triggered when user double-clicks on a label.

Sample Application : To find the total and average of three numbers.


Name Property
•A very important property for each
object is its name.

•The name is used by Visual Basic to


refer to a particular object in code.
Name Property
• It is a convention is to use a three letter prefix (depending on the
object) followed by a name you assign.
• Examples
Object Prefix Example
Form frm frmWatch
Command Button cmd, btn cmdExit, btnStart
Label lbl lblStart, lblEnd
Text Box txt txtTime, txtName
Menu mnu mnuExit, mnuSave
Check box chk chkChoice
Access Keys
• Many windows application allow pressing ALT with a combination of a key as the access key to
quickly activate a control or a menu item.
• Access keys are defined in the standard way using the ampersand (&).
• VB makes it easy to set up an access key for any object that has a caption property.
• Note in the button captions on the form, the access
keys appear with an underscore (_).
Command1:
Caption &Start Timing
Name cmdStart
Command2:
Caption &End Timing
Name cmdEnd
Command3:
Caption E&xit
Name cmdExit
Access Keys
•In the Caption properties of the three command buttons, notice the
ampersand (&).

•The ampersand precedes a button's access key. That is, in addition to clicking on a
button to invoke its event, we can also press its access key (no need for a mouse).

•The access key is pressed in conjunction with the Alt key. Hence, to invoke Start
Timing', we can either click the button or press Alt+S.

•Note in the button captions on the form, the access keys appear with an
underscore (_).
THE TOOLBAR CONTROLS
•The Toolbox contains a set of controls which are used to customize forms.
•Using these controls, an interface between use and the application can be
created.
CONTROL DESCRIPTION
Pointer Used to interact with the controls on the form
Picture Box Used to display images
Textbox Used to accept user input which can display only editable text
Frame Used to group other controls
Command Button Used to initiate an action by pressing on the button
Check box Used to do a choice for user
Option Button Used in groups where one at a time can be true
List Box Used to provide a list of items
THE TOOLBAR CONTROLS
Control Description
Combo Box Used to provide a short list of items
Hscroll Bar A horizontal scrollbar
Vscroll Bar A vertical scrollbar
Timer Used to perform tasks in specified intervals.
DriveList Box Used to access the system drives
DirList Box Used to access the directories on the system
FileList Box Used to access the file in the directory
Shape Used to draw circles , rectangles , squares, ellipses
Line Used to draw lines
Image Used to display images
Data Used to connect a database
OLE Used to interact with other windows applications
Label Used to display texts which cannot be edited

You might also like