Contents: Visual Basic Introduction To Visual Basic
Contents: Visual Basic Introduction To Visual Basic
Visual Basic
Operators
Arithmetic operators
Logical operators
Relational operators
Arrays
Introduction of array
Declaration of array
Procedure
Sub procedures*
Function procedures*
Property procedure
Functions
Visual basic functions
GUI given above shows graphical interaction between user and system. That is
why a GUI is an effective mean of making your application user friendly and is the
key to creating successful applications.
GUI becomes very popular because users can easily identify things with the help of
graphics. The main advantage of using GUI is that user can interact with
application using common sense. Even a laymen user can learn GUI applications
easily.
Introduction to Visual Basic
Getting started with visual basic
This module will tell us , how to open the Visual Basic software, about the
interface of Visual Basic , so that we'll versed with its looks and feel.
For Animated Presentation Click Here
Introduction to Visual Basic
Visual Basic Integrated Development Environment(IDE)
VISUAL BASIC IDE (INTEGRATED DEVELOPMENT ENVIRONMENT ) is
the environment in which its program are written and executed. IDE stands for
Integrated Development Environment. IDE is a term commonly used to describe
the interface and environment for creating your application. It is called IDE
because you can access all of the development tools that you need for developing
an application.
For Animated Presentation Click Here
VISUAL BASIC IDE contains different components. These components are:
Tool Bar
It provides quick access to commonly used commands in the programming
environment. You click a button on the toolbar to carry out the action represented
by that button. The Standard toolbar is displayed when you start Visual Basic. You
can change toolbar settings by selecting Toolbars option form View menu.
Toolbar can be removed from beneath of the menu bar, if you click on the Left
Edge and drag it away from the menu bar.
For Animated Presentation Click Here
Form Designer
Form objects are the basic building blocks of Visual Basic application.It is the
actual window with which a user interacts at the start of application. Forms have
their own properties, events, and methods with which you can control their
appearance and behavior. Properties, events, and methods of a form will be
explained further in tutorial.
The Form Window is central to developing Visual Basic applications.It is the
window where you draw your application
Tool Box
The Toolbox is a long box with many different icons on it. It is the selection menu
for controls (objects) used in your application. To work in Visual Basic we've to
know about its tools so that we can make different forms, projects and how to edit
them. we'll learn all these things in this module.
For Animated Presentation Click Here
Property Window
Properties Window is used to establish initial property values for objects (Like
Form etc.). The drop-down box at the top of the window lists all objects in the
current form.Two views are available: Alphabetic and Categorized. Given box
shows the available properties for currently selected object:
If you are not getting property window on IDE then click on Project Explorer
option from view menu. Or, Use key F4 or Alt+V+W for displaying property
window.
Project Explorer
Project Explorer Window displays a list of all forms used in making up your
application. You can also obtain a view of the Form or Code windows (window
containing the actual Basic coding) from Project Explorer window.
If you are not viewing Project Explorer on IDE then click on Project Explorer
option from the view menu. OR, Use Ctrl+R for displaying Project Explorer
Window.
Menu Bar
It is a horizontal strip that appears across the top of the screen and contains the
names of menus.Menu Bar lists the menus that you can use in the active window.
You can modify the menu bar using the Commands tab of the Customize dialog
box. For that go to the View menu ,then select Toolbars. Now Click on the
customize option. OR, You can use key combination Alt+V+T+C for that.
A window will appear like the figure given below:
A list of options will be displayed .A user can make a selection in order to perform
a selected action. Suppose if you want to animate menu options then click on the
options in above figure. OR, Use key combination Alt+V+T+C+O for animation.
Form Layout Window
Form Layout Window shows where (upon program execution) your form will be
displayed relative to your monitor's screen:
Click on to the Form Layout window option from view menu for displaying above
window. OR, Use Key Combination Alt+V+F for that. It allows you to visually
position your forms .
All forms will be displayed whenyou place your cursor over a form. Press the
mouse button,and drag it where you want the position of your form.
Introduction to Visual Basic
Application Of Visual Basic
Visual Basic is the most sophisticated tool for developing commercial
applications .Various information system are implementing in VISUAL BASIC
today,these are as follows:
Various information system are implementing in VISUAL BASIC today,these are
as follows:
MIS(Management Information System),
EIS(employee Information System),
Inventory control,
ERP(Enterprise Resource Planning),
Web application,
Library Management System Etc.
VISUAL BASIC is mostly used in application programming. VISUAL BASIC
provides easy to use connectivity with database that is why most of database
related software are being developed in VISUAL BASIC today.
A simple VISUAL BASIC application works like given in fig:
Data Types and Modules
Data Types
Visual Basic supports different types of data types according to the needs of
program or application
You can say that attribute of a variable that determines what kind of data it can
hold is known as Datatype.
By Default Visual Basic supports the variant data type.Declaring a variable variant
indicates that it can support all types of data types.Mainly Visual Basic supports
the following datatypes:
Table of Data Types
Data Types Storage (in bytes) Prefix Example
Byte 8 Byt bytVar
Boolean 1 Bln blnNum
Integer 2 int intCount
Long; 4 lng lngNumbers
Single 4 sng sngAverage
Double 8 dbl dblMarks
Date 8 dte dteNext
Object 4 obj ObjMywork Avgs
String According to the length of string str strNames
Variant 16 vnt vntTotal
Data Types and Modules
Constants
Constants as the name suggests , never change during the execution of
program.They remain same throughout the program execution.
When the user wants a value that never changes, a constant can be declared and
created.
The syntax for declaring a constant is:
(Public|Private) Const constantname (As type) = expression
The const statement can be declared as:
Public const pie as single=3.14
Data Types and Modules
Modules
A module is a set of functions and a set of data members.Code in Visual Basic is
stored in the form of Modules. Collection of general procedures, variable
declarations, and constant definitions used by application is known as module.
Mainly Visual Basic supports 3 types of modules:
(1) Form module
(2) Standard Module
(3) Class Module
Form module
Form modules provide the user interface to the application. They contain controls
and properties of the forms. They have the extension .FRM.
Their declaration is private by default, therefore each form has a single form
module associated with it.
Standard Module
As we go further in developing the application than there may be common code for
execution of several form.
For avoiding the duplication of code, a separate module containing the code is
implemented.
This is called as standard module. A standard module (.BAS) contains only code. It
contains extension .BAS.
Class Module
A class module (.CLS) is used to create objects (forms etc.). It can be called from
procedures within your application.
Class modules (.CLS filename Extension) are writing code in class modules can
create the building blocks of object oriented programming in Visual Basic.New
objects.
Each module contains different elements, these are:
Declaration
It includes constant and procedures.
Procedures
Sub function or property procedures that contain pieces of code that can be
executed as a unit. It avoids code repetition.
Operators
Arithmetic Operators
Arithmetic operators are used for mathematical expressions.
The given table shows various arithmetic operators and their description:
Operators Symbol Description of Symbol
Subtraction - Subtracts two operands (val1-val2)
Addition + Adds two operands (val1-val2)
Multiplication * Multiply two operands (val1*val2)
Division / Divides 2 operands (val1/val2)
Negation ~ Negates the operand
Gives the remainder after division (Val1
Modulo Mod
mod Val2)
String
& Concatenates two strings (val1 & val2)
Concatenation
Raises the first operands to the power of
Exponentiation ^
second operand (val1^val2)
Operators
Logical Operators
These are also known as Boolean operators.Boolean operators are used in the
conditions where condition can be true or false case.
Basically logical operators are used to form logical expressions that represent true
or false conditions.
For Example:
The 'Or' operator returns the result when only one operands is true.
The given table summarizes various logical operators and their description:
Operators Description of Symbol
Not Return the negative of two expressions.
And Returns true only when both conditions are true.
Or Returns true when only one condition is true.
Imp Returns false only when 1st operand is true and 2nd is false.
Eqv Returns true only when both conditions are true.
Xor Return true only if both operands are of opposite sign.
Operators
Relational Operators
There are six relational/Comparison operators used in testing expressions.
They are >= (greater than or equal to), <= (Less than or equal to), < (less than), >
(greater than), <> (Not equal to).
Comparison operators are used to compare two expressions.They are also known
as relational operators.
The table below contains a list of operators used in Visual Basic:
Operators Function
< First expression is less than second.
<= First expression is less than or equal to second.
> First expression is greater than second.
>= First expression is greater than or equal to second.
<> First expression is not equal to second.
= First expression is equal to second.
Arrays
Introduction of Array
An array is the collection of similar data types.The individual elements of an array
is identified by using an index.
Each index number in an array is allocated individual memory space. Hence users
declare arrays of larger size than required.
Array helps in creating smaller and simpler code in many situation.You can setup
loops that deal efficiently with any number of cases by using the index number.
A loop is used to execute a group of statements repeatedly, based on a condition.
Arrays
Declaration Of Array
Syntax:
Dim arrayname(number) as Datatype
Example:
Dim total(10) as integer
Here total is name of array ,10 is no of elements in the array & integer is the data
type.Number 10 included in the parenthesis is the upper limit of the array.
The above declaration creates an array with index numbers ranging from 0 to 9.
If you want to specify lower limit ,then the parenthesis should include both the
lower and upper limit along with the 'To' keyword.
An example is shown below
Dim num(1 To 5) As integer
In above statement, an array of 5 element is declared but with the index numbers
ranging from 1 to 5.
Mainly Visual Basic supports 2 types of Array:
Fixed-Size array:
The size of array always remains the same.
Dynamic array:
The size of array can be changed at run time.
Conditional statements and Loop structure
If...Then..Statement
The If...Then statement is used to evaluate whether a condition is True or False.
You can use If…Then block to execute one or more statements conditionally.
Syntax:
If <condition> Then
[statements]
Else
[else statements]
End If
Example:
if a>5 Then a=a+10
Here condition is that 'a' should be greater than 5 and if it is true then 'a' should be
incremented by 10.
<condition>:-The condition is usually a comparison, but it can be any expression
that evaluates to a numeric value.
[Statements] :- One or more statements separated by colons; executed if condition
is True.
Note that:
1.A single line of If…Then does not use End If statement.
Syntax:-
If condition Then statement.
But if you use this in more than one line ,then syntax will be If…Then…End If.
2.If anything other than a comment appears after Then on the same line, the
statement is treated as a single line If statement.
3.A block If statement must be the first statement on a line. The block If must end
with an End If statement.
4.When a If condition is tested ,then If condition is True, the statements following
Then are executed,otherwise not.
Conditional statements and Loop structure
If...Then..Else Statement
It conditionally executes a group of statements depending upon value of the
expression.
If...Then…Else block is used to define several blocks of statements ,in order to
execute one block.
Syntax:
If <condition>then
[statements]
Else if <condition>Then
[else if statement] . . .
Else
[elsestatement]
End If
Example:
If a<10 then
a=a+10
elseif a>15 then
a=a-10
else
a=100
end if
Note that:
1.Both Else and ElseIf statements are optional. You can have any number of ElseIf
statements as you want in an If block. But no ElseIf statement can appear after the
Else.
2.Block If statements can be nested. Nested means a block contained within one
another.
3.In fact If…Then is just a special case of If…then…Else.
4.If none of ElseIf statement is True ,then the statement following Else will
execute.
Conditional statements and Loop structure
Select Case Statement
It is just as the alternative of If…Then…Else statement.It executes one statement
in several groups of statements.
A Select Case provides the same functionality as the If…then…Else statement but
it makes the code more efficient and readable
A Select Case works with a single test expression.
Value of the statements will be dependent on test expression.
Syntax:
Select Case testexpression
[Case expression1
[statements-n]] . . .
[Case expression2
[statements-n]]
.
.
Case Else
Statement..n
End Select
<Testexpression>
Any numeric or string expression.
<statement>
Statement executes if Testexpression matches any part of expressionlist.
Example:
The following example describes the use of the Select Case statement-
Dim num as integer
Dim a(10) as integer
'Calculations containing num
Note "'" Indicates the Comment Line
Select Case num
Case 1 a(1)=num
Case 2 a(2)=num
Case 3 a(3)=num
Case else a(1)=num
End Select
Num is declared as integer variable here and a(10) is declared as an array of ten
elements.
Select Case checks values of num, according to that it executes the corresponding
case statement.
Note that:
1.Value of the statement will be dependent on expression.
2.The Case Else clause is used to indicate the elsestatements to be executed if no
match is found between the testexpression and an expressionlist
3.Select Case statements can be nested.
4.Each nested Select Case statement must have a matching End Select statement.
Conditional statements and Loop structure
Do...Loop Structure
Do…loop is used to execute a block of statements for indefinite number of times.
There are several variations of Do...Loop statement.
Each variation evaluates a numeric condition to determine whether to continue
execution or not.
Syntax:
Do While <condition>
statements…
Loop
Note that:
1.When Visual Basic executes Do While loop, it first tests condition.
2.If condition is False (zero), it skips past all the statements.
3.If it's True (nonzero), Visual Basic executes the statements and then goes back to
the Do While statement and tests the condition again.
Example:
Do While count<=5
count = count + 1
Loop
Here loop increments the value of count until it becomes equal or less than 5.
Another variation of Do...Loop statement executes the statement first and then tests
condition after each execution. This variation guarantees at least one execution of
statements.
Syntax:
Do
<statement>
Loop While <condition>
Conditional statements and Loop structure
For...Next Structure
For...Next loop is used when you know how many times you want to execute
loop.But in case of Do While it is not the case.
Do While is used when you do not know how many times you want to execute that
particular loop/Condition.
Syntax:
For counter = start To end [Step increment]
statements
Next [counter]
The arguments counter, start, end, and increment are all numeric.
In executing the For loop, Visual Basic:
1. Sets counter equal to start.
2. Tests to see if counter is greater than end. If so, Visual Basic exits the loop.
3. Executes the statements.
4. Increments counter by 1 or as it's specified.
5. Repeats steps 2 through 4.
Example:
Dim A(40) as Integer
For i = 0 To 40 step 1
A(i)=i
Next
Print A(9)
Here index values are stored in array a(40).Then it prints the value of a(9).
Procedure
Sub Procedures
A Sub procedure is a block of code that is executed in response to an event.
By breaking the code in a module into Sub procedures, it becomes much easier to
find or modify the code in your application.
Syntax:
[Private|Public][Static]Sub procedurename (arguments)
statements
End Sub
Each time when procedure is called, the statements between Sub and End Sub are
executed. Sub procedures can be placed in standard modules, class modules, and
form modules.
Sub procedures are by default Public in all modules, that means they can be called
from anywhere in application.
Note that:
Sub Procedures are the procedures that do not return a value.
The arguments for a procedure are like a variable declaration.
Event Procedures
When an object in Visual Basic recognizes that an event has occurred then it
automatically invokes event procedure
That event procedure will use procedure name corresponding to that event.
Syntax:
Private Sub Form_eventname (arguments)
statements
End Sub
CmdSave_Click():-Here Click is an event and CmdSave_Click() is the procedure
associated with it.
Syntax for a Control Event:
Private Sub Control_Eventname(arguments)
Statements Block
End sub
Syntax for a Form Event:
Private Sub Form_eventname(arguments)
Statements Block
End sub
Example:
Private Sub Form_Load().
This is the main event procedure for a form .When a form is loaded in application
then this procedure is called first.
General Procedures
A general procedure tells the application how to perform a specific task. Once a
general procedure is defined, it must be specifically invoked by the application.
General procedure remains idle until called upon to respond to events caused by
the user or by system.
For Animated Presentation Click Here
Why create general procedures?
One reason is that several different event procedures might need the same task
repeatedly.
A good programming strategy is to put common statements in a separate procedure
(a general procedure). An event procedure calls that general procedure.
This eliminates the need to duplicate code and also makes the application easier to
maintain.
Example:
Suppose you display some message after each event code execution then you will
use event procedure.
For adding procedure to your application follow the steps given below:
(1) Go to Tools menu and select Add Procedure form. Or, Use key combination
Alt+T+P.
The window will be shown like this:
(2) Write name of procedure Display in the name Box and select type Sub
according to figure given above.
(3) Write code for display() after Clicking OK in the previous Step.The code
Window will display like this:
(4) Now call procedure in any event associated your application.
( Calling Procedure display() )
Procedure
Function Procedures
Function Procedures return values. you can use Function statement to write your
own Function procedures.
Like a Sub procedure, a Function procedure is a separate procedure that can take
arguments, perform a series of statements, and change the value of its arguments.
Syntax:
[Private|Public][Static]Function procedurename (arguments) [As type]
statements
End Function
Note that:
1.You call a function by including the function procedure name and arguments on
the right side of a larger statement or expression (returnvalue = function()).
2.Function procedures have data types, just as variables. This determines the type
of the return value.
3.You return a value by assigning it to the procedurename itself.
Example:
Public function Addition(a,b)
Addition=a+b
End Function
Here Function addition is declared .It takes two arguments and then add these two
values. It returns sum of two values.
For Animated Presentation Click Here
Procedure
Property Procedures
Property procedures are the procedures that return values and also assign values to
the property of objects.
Visual Basic provides three kinds of property procedures, as described in the
following table.
Procedure Procedure
Property Get Returns the value of a property.
Property Let ets the value of a property.
Property Set Sets the value of an object property.
Property procedures are defined in class modules.
Note that:
If you need to perform a task each time then you need to use a property procedure.
Once it is defined, it executes automatically without needing an explicit call each
time.
Functions
Visual Basic Functions
A function is a preprogrammed calculation .It can be carried out on request from
any point in a Visual Basic program.
A function takes one or more arguments and returns a single value and it can be
included in an expression.
Argument:
It is a value on which a function or procedure operates.
For example, in the Visual Basic statement Str(10),
number 10 is the argument.
Visual Basic includes built-in functions like Sqr, Cos or Chr etc.We are discussing
some of them here:
(1) Sqr()
Returns a Double specifying the square root of a number.
Syntax
Sqr(number)
(2) ABS()
Returns the absolute, positive value of the given numeric expression.
Syntax
ABS(numeric_expression)
Arguments
numeric_expression
Is an expression of the exact numeric or approximate numeric data type category.
Return Types
Returns same type as numeric_expression.
(3) POWER()
Returns value of given expression to the specified power.
Syntax
POWER(numeric_expression, y)
Arguments
numeric_expression
Is an expression of the exact numeric or approximate numeric data type category.
y Is the power to which to raise numeric_expression. y can be an expression of the
exact numeric or approximate numeric data type category.
(4) FLOOR ()
Returns largest integer less than or equal to the given numeric expression.
Syntax
FLOOR(numeric_expression)
Arguments
numeric_expression
Is an expression of exact numeric or approximate numeric data type category.
Return Types
Returns the same type as numeric_expression.
For Example:
FLOOR(122.45), Return value=122
FLOOR(-123.45) ,Return value=124
(5) Round()
Returns a numeric expression, rounded to the specified length or precision.
Syntax
ROUND (numeric_expression, length)
Arguments
numeric_expression
Is an expression of the exact numeric or approximate numeric data type category.
length Is the precision to which numeric_expression is to be rounded. length must
be int.
When length is a positive number, numeric_expression is rounded to the number of
decimal places specified by length.
When length is a negative number, numeric_expression is rounded on the left side
of the decimal point, as specified by length.
Return Types
Returns the same type as numeric_expression.
For Example:
Round(123.4545,2) ,Return Value=123.4500
(6) SQUARE()
Returns the square of given expression.
Syntax
SQUARE(float_expression)
Arguments
float_expression
Is an expression of type float.
Return Types
float
(7) PI ()
Returns the constant value of PI.
Syntax
PI()
Return Types
float
(8) SIGN ()
Returns the positive (+1), zero (0), or negative (-1) sign of the given expression.
Syntax
SIGN(numeric_expression)
Arguments
numeric_expression
Is an expression of the exact numeric or approximate numeric data type category.
Return Types
Float
(9) LOG10 ()
Returns the base-10 logarithm of the given float expression.
Syntax
LOG10(float_expression)
Arguments
float_expression
Is an expression of the float data type.
Return Types
Float
(10) RAND ()
Returns a random float value between 0 and 1.
Syntax
RAND([seed])
Arguments
seed
Is an integer expression (int) giving the starting value.
Return Types
float
Methodes and Events
Methods
Methods are associated with objects, and define the actions they carryout for their
object.
For Example:
The methods of your radio are on, off, volume control etc, Which give you control
on your radio.Each Method performs a particular action. Method is an action that
an object is capable of performing.
For example:
list boxes have methods called AddItem, RemoveItem and Clear, for maintaining
list contents.
Methodes and Events
Syntax for Calling Method
Objectname-Method
Here objectname specifies the name of an object, and Method specifies the name of
a method.
Example:
Form1.Print "Hello World"
Here Form1 is form name , and method Print is called to print the String "Hello
World" to form.
There are different methods associated with different controls.Methods are useful
because they hide the details of how an action is performed.
The programmer just needs to call the method ,how the action is performed it is not
his or her headache.
Note That:
Put a dot after the name of control then various options will look like in figure.
Methods associated with some commonly used controls:
List Box
It is control that provides a list of items.
Methods of List Box:
1) Additem: This method adds the specified item to the list
2) Removeitem: This method is used to delete an item from the list.
3) SetFocus: Used to make the list box the Current active element.
Combo Box:
A combo box has all the properties exhibited by the text box and list box.
Methods of combo box:
1.Additem: This method will add the specified item to the combo box.
2.Remove Item: This method will delete an item from the combo box.
Option Button:
Option button are used when the user can select one and only one of the multiple
options.
Typically,there are no special methods associated with option buttons.A method
associated with option
button is:
Move: Moves a control on the form.
Command Button:
The easiest way to allow the user to interact with an application is to provide a
button to click.
Visual Basic provides this in form of Command Button.
One method is used with the command button:
Move: Moves a control on the form
Methodes and Events
Events
A major part of interaction between people in every day life is in the form of
events and response.
For Example
When some one knocks at the door, then you open the door.Knocking at door is
event and opening the door is response to the event.
In technical words an event is an user action directed at the application.
Methodes and Events
Example Of An Event In An Application
1.Clicking the mouse.
2.Pressing a key on the keyboard.
When you click on a button it is recognized as an event by the button.
A calculator (Provided in your Windows) shown in figure is the perfect example of
events and their quick responses.
For Example
Clicking on a number Button will display a particular number in the text Box.Some
of events like methods require additional information in the form of arguments.
For Example,
Click event does not requires arguments whereas DragDrop event requires
arguments as shown in example:
Public Sub Command1_Click()
Statements
End Sub
Public Sub Commnand1_DragDrop(Source As Control,X as Single,Y As Single)
Statements
End Sub
Working with Forms
Form Basics
A form is a window that contains application code and other objects placed on it to
create the user interface. Forms may fill the entire screen or have other forms
contained with in it.
Note that:
Visual basic initially includes a default form Form1 file in each project.You can
change the name and caption of the form to identify the purpose of the form.
Every form has its own properties ,events and methods associated with it.
Here a sample form is shown, VISUAL BASIC gives default name and caption to
a form as form1. It is shown in above figure.
Adjusting of height and width is shown in figure below:
Form objects are the basic building blocks of a Visual Basic application. It is actual
window with which a user interacts when they run the application.
Forms have their own properties, events and methods with which you can control
their appearance and behavior.
Working with Forms
Form Properties
Many properties of a form affect its physical appearance. The Caption property
determines the text that is shown in the form's title bar, the Icon property sets the
icon that is displayed when a form is minimized.
The MaxButton and MinButton properties determine whether the form can be
maximized or minimized. By changing the BorderStyle property, you can control
the resizing behavior of the form.
There are some specific properties of the form and a brief description of some
selected properties is given here.
Property window of a form is shown below:
Border Style:
Form can have different types of borders.
The borders are as follows:
Caption:
The title of the window is stored in Caption property.It is shown at top of the form.
Icon:
This property specifies the icon for the window in the upper-left corner of the
window.
Mouse Pointer:
This displays the value that indicates the type of mouse pointer.
Max Button:
This property indicates whether the maximize Button should be shown and
Maximize choice available in the control box menu.
Min Button:
This property indicates whether the minimize Button should be shown and
minimize choice available in the control box menu.
MDI Child:
This property specifies if this window must be shown within a multiple document
interface (MDI) window. You will discuss them in detail in further section of
tutorial.
Back Color:
Back Color is used to fill the back ground color of the form.
Autoredraw:
Setting AutoRedraw to True always produces normal layering. While using
AutoRedraw is the easiest way to layer graphics, applications with large forms may
suffer from reduced performance due to the memory demands of Autoredraw.
For Example:
By setting Autoredraw property of form to true ,You print any text at the form.
Working with Forms
The Form Events
As objects, forms can perform methods and respond to events.The Resize event of
a form is occured whenever a form is resized, either by user interaction or through
code. This allows you to perform actions such as moving or resizing controls on a
form.
The Activate event occurs whenever a form becomes active form, the Deactivate
event occurs when another form or application becomes active. These events are
convenient for initializing or finalizing the form'sbehaviour.
OR For writing the code for any from use key combination Alt+V+C.
A form's events are shown below in the figure:
For Writing code of a particular event just click on a particular event ,then the
following code window will appear:
Here for example you have clicked the MouseUp event.
Using the unload Event:
The unload event procedure is used to verify that the form should be unloaded.The
unload event is occurred when:
1.The Form is unloaded using the Unload statement.
2.The form is closed by either clicking the Close command on the application
menu or clicking the close button on application title bar.
Commonly used Form Events:
Form_Activate event is triggered when form becomes the active
Activate
window.
Click Form_Click event is triggered when user clicks on form.
Form_DblClick event is triggered when user double-clicks on
DblClick
form.
Form_Load event occurs when form is loaded.This is a good place
Load
to initialize variables and sets any run-time property.
Working with Forms
The Form Methods
Different methods are used in forms. When you put a dot after name of the form
then a popup menu is displayed.
There are different methods for forms .Some of them are describing here.
Show method
Show method is used to display the form object.
For Example to display the form frmStudents,
following code is written:
frmStudents.Show
Hide Method
The Hide method is used to hide a form.
For example to hide a form, following code is written:
frmStudents.Hide
The Cls Method
All text and graphics on the form that were created with Print and graphics
methods can be deleted with the Cls method.
Example: frmStudents.Cls
The Refresh Method
Forces a complete repaint of a form.
For example:
form1.Refresh
Use the Refresh method when you want to Completely display one form, while
another form loads.
Point Method
Returns the red-green-blue (RGB) color of the specified point on a Form. It returns
color as a long integer.
form1.Point(x, y)
Working with Forms
Setting Runtime & Design Time Properties
Visual Basic operates in three modes.
1. Design mode - used to build application.
2. Run mode - used to run the application.
3. Break mode - used for debugging application.
Many properties can be set at either design time or run time. At design time
controls are added to the form, their properties are set and code is written. During
runtime you examine your program in action, just as the end user will see it.
To set a property at design time , following steps are followed:
1. Select the form or object whose characteristics are to be changed.
2. Activate the properties window.
3. Scroll the property you want to set and select its name.
4. Enter a new setting.
At runtime, property can be changed by a program code.
This is done like this:
For Animated Presentation Click Here
when you run the above application then the form1's backcolor, mouse pointer and
Caption will look like figure.
Working with Forms
Setting Start Up Form
The first form in your application is designated as the startup form. When your
application starts running, this form is displayed. User will see Startup form when
application starts.
If you want a different form to display when your application starts, you must
change the startup form.
To change the startup form
1. From the Project menu, choose Project Properties.
For Animated Presentation Click Here
2. Choose General tab.
3. In the Startup Object list box, select the form you want as the new startup form.
4. Choose OK.
The following figure will describe the above procedure:
In above figure you can choose the start up form from1 or form2. If you opt for
form2 then after executing the application form2 will be shown.
Creating Simple Application in Visual Basic
Structure Of A Visual Basic Application
A VISUAL BASIC Application (Project) will be of .VBP extension and related
forms are saved with .frm extension. A Simple VISUAL BASIC Project (.VBP).
A Visual Basic Application (Project - saved as a file with .VBP extension) is made
up of:
1. Forms
Windows that you create for user interface (saved as a file with a .FRM extension)
2.Controls
Graphical features drawn on forms to allow user interaction (text boxes, labels,
scroll bars, command buttons, etc.) (Forms and Controls are also called objects.)
3.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. You can change properties at design time
or run time.
4.Methods
Built-in procedure that can be invoked to give some action to a particular object.
5.Event Procedures
Code related to some object. This is the code that is executed when a certain event
occurs.
6.General Procedures
Code not related to objects. This code must be invoked by the application.
Creating Simple Application in Visual Basic
Designing The Visual Interface Form
The first step in Visual Basic application is to create the forms that will be the basis
for your application' s interface .It comprises of two Steps:
1. Placing Controls on the form.
2. Setting Properties of Controls at Design Time.
Placing Controls on the form:
The following method will guide you about placing controls on the form.
A window will appear when you start Visual Basic.Main window will look like
that:
Select the Standard EXE from the above figure.Now you will see the following
figure:
As you have read earlier above window is the main VISUAL BASIC IDE ,all
application are created in the IDE.The above IDE will contain six windows:
I. Main Window
II. Form Window
III. Tool Box
IV. Property Window
V. Form Layout Window
VI. Project Explorer Window
Note That:
If any of the above is not present in the IDE then you can invoke them by selecting
from view menu.
The user interface is 'drawn' in the form window.
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. You can then move it or resize it.
2. Click the tool in the toolbox, and then move the Mouse pointer to the form
window. The cursor changes to a crosshair.
Place the crosshair where you want the control at form by pressing the left mouse
button and hold it down while dragging the cursor.
When you release the mouse button the control is drawn. This approach must be
used to place controls in a frame or picture box control.
For example you have to place a textbox control to the form, follow these steps:
Select the text box control from the tool box by clicking on it. when selected it will
appear like figure:
3.Click and drag within 'Form1' to place the TextBox at the form. 'Text box'
control has a default text 'Text1'.
Note that:
Drag the mouse while keeping the left mouse button pressed.
Refer to figure:
So like 'Text Box' control, all other controls can be placed on the form. All have
default names.
To resize a control, click the object so that it is select and sizing handles appear.
Use these handles to resize the object.
Setting Properties of Controls at Design Time
Each control has properties assigned to it by default when you start a new project.
There are two ways to display the properties of a control.
Þ The first way is to click on the control in the form window. Then click on the
Properties Window.
Þ The second way is to first click on the Properties Window. Then select the object
from the Object box in the Properties Window.
Following figure Shows the Properties Window for a new application:
A very important property for each objects is its name. The name is used by Visual
Basic to refer to a particular object in code:
A convention has been established for naming Visual Basic objects. This
convention is to use a three-letter prefix (depending on the object) followed by a
name you assign.
A few of the prefixes are (you will see more as you progress in course):
Object Prefix Example
Form Form frmWatch
Command cmd cmdExit
Button btn btnStart
Label lbl lblStart
Text Box txt txtTime
Menu mnu mnuExit
Check box chk chkChoice
Data control dat datExample
Creating Simple Application in Visual Basic
Adding Code For The Program
The crucial step in building a Visual Basic application is to write code using the
BASIC language. This is the most time consuming task in any Visual Basic
application.
Code is placed in code window. At the top of code window two boxes will
apllear ,the object (or control) list and the procedure list.Select an object and the
corresponding event procedure. A blank procedure will appear in window where
you write BASIC code.
After designing interface the next step is to associate the code with the controls.
Suppose you have to write code for commandButton.Then Ensure that you have
selected the commandButton.
Double click on the commandButton.This will bring up the command window as
shown in the figure below:
The 'Code Window' is where you write code for your VISUAL BASIC
application.It is used to write code for various events supported by the controls. In
code Window you have to select the control and event for which the code is to be
written.
Suppose you have clicked command button .Then code window displays the
following lines:
Private Sub Command1_Click( ) End Sub
Any code written between these lines will be executed when the control by the
name of 'Command1' is clicked upon.
VISUAL BASIC makes the writing code easier with the features that can
automatically fill in properties and syntax.
For example, When you enter name of a control followed by a period in your
code,the 'Auto List Members' feature presents a drop-down list of properties
available for that control.
Add the following Code between above lines as shown in figure:
Text1.Text = "Hello Visual Basic"
VISUAL BASIC automatically verifies the correct syntax after you enter a line of
code.It also capitalizes the first letter of command words and often adds extra
spaces for readability.
The above written line of code simply changes the Text property of the control
named Text1 to 'Hello VISUAL BASIC'.
Syntax: object. Property
At runtime above code simply displays a textbox containing Text "Hello Visual
Basic", just like below:
Creating Simple Application in Visual Basic
Compiling The Project
Compiling is a very important process for any program. By Compiling we can
check only grammatical errors (Basically syntax errors), not logical errors (concept
of application).
For compiling a visual basic project follow Steps given below:
1.Go to Run Menu.
2.Select the option Start with full Compile. It will start your application with full
compile,Otherwise you can start your application directly. OR You can use Key
combination Ctrl+F5.
The figure below shows the process:
Creating Simple Application in Visual Basic
Creating An Exe
EXE stands for Executable. It means that run an ExE and use the application
without knowing the code and other details. When you start your project like above
step, it does not create an EXE.
Creating an EXE:
1. Go to File Menu.
2. Select the option projectname.exe option.
Note that:
An EXE is always created with the project name. Suppose you have given name
myproject to your project, then it will create EXE named myproject.exe.
The following figure shows the above process:
Creating Simple Application in Visual Basic
Running The Project
After compiling and making EXE, now it is finally turn to run a visual Basic
Application.
1. Go to Run menu.
2. Select the option Run.
3. Click the Start button on the title Bar OR Simply Press F5 to run your VISUAL
BASIC project.
Following figure illustrates that:
If you have created EXE ,then simply double click on the EXE icon, like that:
A sample EXE icon in VISUAL BASIC:
By double clicking on the above icon you can invoke your VISUAL BASIC
application.
Creating Simple Application in Visual Basic
Making Different Applications
Creating an application in Visual Basic is simple. You have already learnt a lot
about creating a VISUAL BASIC application. Now it will take just a minute to
create your first VISUAL BASIC application.
First of all let us make a Simple 'Hello' application, As we do in other
programming language:
Hello Visual Basic Application:
For Animated Presentation Click Here
The first step in building a Visual Basic application is to create the forms that will
be the basis for your application's interface. Then you draw the objects that make
up the interface on your forms. For this first application, you will use two controls
from the Toolbox.
1. Click tool Box for the control you choose to draw - In this case, the text box.
Move the pointer onto your form. The pointer becomes a cross hair.
2. Place the cross hair where you want the the control.
3. Drag the cross hair until the control is the size you want.
4. Release the mouse button.
Form will look like the figure:
For the "Hello, VB!" example, you will need to change three property settings. Use
the default settings for all other properties:
Object Property Setting
Form Caption Hello VB
Command Button Caption OK
Textbox Text (Empty)
After property setting form will look like:
Writing Code:
1. For this example, choose the command button, Command1.
2. In the Procedure list box, select the name of an event for the selected object:
Here, the Click procedure is already selected, because it's the default procedure for
a command button.
Type the following code between the Sub and End Sub statements:
Text1.Text = "Hello, VB!"
The event procedure will look like this:
Private Sub Command1_Click ()
Text1.Text = "Hello, VB!"
End Sub
Running the Application
To run the application, choose Start from the Run menu, or click the Start button
on the toolbar, or press F5. Click command button you have created on the form
and you will see "Hello,VB!" displayed in text box.
An application using Mathematical Operations
For Animated Presentation Click Here
Now you will create an application which performs two operations:
1. ADD
2. MULTIPLY
Designing the interface
1. Select a New project from file menu,then select standard EXE.
2. Place controls in the form to create the user interface according to the figure:
3. Now for above example, you will need to change different property settings.
Change the properties according to the figure:
Use the default settings for all other properties.
Property Table:
Object Property Setting
Mathematical
Form Caption
Calculations
Command
Caption ADD
Button1
Command
Caption MULTIPLY
Button2
Command
Caption EXIT
Button3
Textbox1 Text (Empty)
Textbox2 Text (Empty)
Textbox3 Text (Empty)
Label1 Caption 1st Number
Label2 Caption 2nd Number
Label3 Caption Result
After setting the properties for different controls the form will look like figure:
Coding:
1. Double click on the command button ADD.
Private Sub Command1_click( )
Dim No1 As Integer
Dim No2 As Integer
No1=Text1.Text
No2=Text2.Text
Text3.Text=No1+No2
End Sub
Dim' statement in VISUAL BASIC is used to declare variables.
The 1st two lines of code declare two variables named No1 and No2 , as integer.
Then further lines of code are used to store the values entered by user in the two
text boxes into the variables just declared
The last line of code adds up the two values and displays them in textbox3.
2. For multiplication of two numbers, write following code by the Clicking on
Multiply button.
Private Sub Command1_click( )
Dim No1 As Integer
Dim No2 As Integer
No1=Text1.Text
No2=Text2.Text
Text3.Text=No1*No2
End Sub
3. For exiting ,type the following code to the Click event of 'Command3'.
Private Sub Command3_click( )
End
End Sub
Now the Code Window will look like the figure:
Running the Application:
1. Press F5 or Select Run from menu.
2. Now the project will run and the form will appear. Click in the text box1 and
enter 10.
3. Click in the text box2 and enter 5.
4. Click on the button ADD,the result will be displayed in the result textbox.
5. Click on the button MULTIPLY, the result will be displayed in the result
textbox.
Following figure is showing addition of two numbers:
6. Click on the button EXIT to close the application.
Working with Files
Saving Project or Files
Now you have created application, so you have to save the application.
Steps:
1. Go to File Menu.
2. Select Save project option .
3. Select Save project As. , if you want to save the project under a different name.
VISUAL BASIC project will be saved with the extension .vbp.
4. Now select Save Formname option.
A form will be saved with the extension .frm.
5. Click on Save button on the title bar OR
You can use Key Combination Ctrl+S for Saving Project and forms.
The window look like below:
For saving a form file, window will look like:
Note that:
If you want to change the name of your project then:
1. Go to project menu.
2. Select Project Properties.
The window will appear like below:
Now change the name of the project and click OK.
Important:
It is important to be noted here that project name and project file name are
different.
Same is true in case of forms. Form name and form file names are different.
Working with Files
Opening Existing Project
Suppose you have to open a existing project, then follow the steps below:
1. Go to the File Menu.
2. Click on to the open project project.
3. Click on the Open button on the title Bar OR You can use Ctrl+O for opening a
existing project.
The window looks like below:
Working with Files
Removing File From The Project
If you want to remove a form file from an existing project than:
1. Go to project Explorer Window.
2. Select form which you want to remove.
3. Right click on that. A pop menu will appear like that:
Working with Files
Removing Project
For removing the entire project two methods can be used:
1. Go to the file menu than select Remove Project.
2. Go to the project Explorer Window.
3. Select the project which you want to remove.
4. Right click on that. A pop menu willappear like that:
You can also use Atl+F+R for removing the entire project.
Working with Files
Exiting From Visual Basic
For existing Visual Basic IDE, you Simply Go to file Menu and Click Exit. Menu
will look like below:
You can also use Alt+Q for Exit.