0% found this document useful (0 votes)
37 views47 pages

Unit 1

Uploaded by

Rajashree B
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views47 pages

Unit 1

Uploaded by

Rajashree B
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

VISUAL PROGRAMMING

UNIT-I

Getting started with visual basic 6.0


Introduction to Visual Basic:

 Visual Basic is a third-generation event-driven programming language first released by


Microsoft in 1991. It evolved from the earlier DOS version called BASIC.
 BASIC means Beginners' All-purpose Symbolic Instruction Code. Since then Microsoft has
released many versions of Visual Basic, from Visual Basic 1.0 to the final version Visual
Basic 6.0.
 Visual Basic is a user-friendly programming language designed for beginners, and it enables
anyone to develop GUI window applications easily.

Visual Basic 6.0 Programming Environment:

Visual Basic is initiated by using the Programs option > Microsoft Visual Basic 6.0 > Visual
Basic 6.0.

 Installation first,to run setup as administrator.


 Next, choose custom installation.
 Clear the checkbox for Data Access.
 Finally, click next and wait for the installation to complete.

After installing the vb6 compiler, the icon will appear on your desktop or in yourprograms
menu. Click on the icon to launch the VB6 compiler. Visual Basic 6.0 will display the
following.(figure 1.1)

The Integrated Development Environment:


One of the most significant changes in Visual Basic 6.0 is the Integrated Development
Environment (IDE). IDE is a term commonly used in the programming world to describe the
interface and environment that we use to create our applications.
1
It is called integrated because we can access virtually all of the development tools that we
need from one screen called an interface. The IDE is also commonly referred to as the design
environment, or the program.

The Visual Basic IDE is made up of a number of components

 Menu Bar
 Tool Bar
 Project Explorer
 Properties window
 Form Layout Window
 Toolbox
 Form Designer
 Object Browser

First finalize the project eithercommercial, educational or recreational value. Next, click on
the Standard EXE icon to go into the actual Visual Basic 6 programming environment.The Visual
Basic 6 Integrated Programming Environment is shown in Figure 1.2. It consists of the toolbox, the
form, the project explorer and the properties window.

Figure 1.2: VB6 Programming Environment

The earlier visual basic version IDE was designed as a Single Document Interface (SDI). In a
Single Document Interface, each window is a free-floating window that is contained within a main
window and can move anywhere on the screen as long as Visual Basic is the current application.

2
But, in Visual Basic 6.0, the IDE is in a Multiple Document Interface (MDI) format. In this
format, the windows associated with the project will stay within a single container known as the
parent. Code and form-based windows will stay within the main container form.

Menu Bar

 This Menu Bar displays the commands that are required to build an application.
 The main menu items have sub menu items that can be chosen when needed.
 The toolbars in the menu bar provide quick access to the commonly used commands and a
button in the toolbar is clicked once to carry out the action represented by it.

Toolbox

 The Toolbox contains a set of controls that are used to place on a Form at design time thereby
creating the user interface area.
 Additional controls can be included in the toolbox by using the Components menu item on the
Project menu.

Figure 1.3 Toolbox window with its controls available commonly.

3
Control Description

Pointer Provides a way to move and resize the controls form

Displays icons/bitmaps and metafiles. It displays text or acts as a visual


PictureBox
container for other controls.

TextBox Used to display message and enter text.

Frame Serves as a visual and functional container for controls

CommandButton Used to carry out the specified action when the user chooses it.

CheckBox Displays a True/False or Yes/No option.

OptionButton control which is a part of an option group allows the user to


OptionButton
select only one option even it displays mulitiple choices.

ListBox Displays a list of items from which a user can select one.

Contains a TextBox and a ListBox. This allows the user to select an ietm from
ComboBox
the dropdown ListBox, or to type in a selection in the TextBox.

HScrollBar and These controls allow the user to select a value within the specified range of
VScrollBar values

Timer Executes the timer events at specified intervals of time

DriveListBox Displays the valid disk drives and allows the user to select one of them.

DirListBox Allows the user to select the directories and paths, which are displayed.

FileListBox Displays a set of files from which a user can select the desired one.

Shape Used to add shape (rectangle, square or circle) to a Form

4
Line Used to draw straight line to the Form

Used to display images such as icons, bitmaps and metafiles. But less
Image
capability than the PictureBox

Enables the use to connect to an existing database and display information


Data
from it.

Used to link or embed an object, display and manipulate data from other
OLE
windows based applications.

Label Displays a text that the user cannot modify or interact with.

Project Explorer

 Docked on the right side of the screen, just under the tollbar, is the Project Explorer window.
 It provide a quick reference to the various elements of a project namely form, classes and
modules.
 A simple project will typically contain one form. It is possible to develop any number of
forms for use in a program, although a program may consist of a single form.
 In addition to forms, the Project Explorer window also lists code modules and classes.

Figure 1.4 Project Explorer

Properties Window

 The Properties Window is docked under the Project Explorer window.


 The Properties Window exposes the various characteristics of selected objects.
 Each and every form in an application is considered an object.
 Each object in Visual Basic has characteristics such as color and size. Other characteristics
affect not just the appearance of the object but the way it behaves too.

5
 A form has properties and any controls placed on it will have propeties too. All of these
properties are displayed in the Properties Window.

Object Browser

 The Object Browser allows us to browse through the various properties, events and methods
that are made available to us.
 It is accessed by selecting Object Browser from the View menu or pressing the key F2. The
left column of the Object Browser lists the objects and classes that are available in the
projects that are opened and the controls that have been referenced in them.
 After an object is picked up from the Classes list, we can see its members (properties,
methods and events) in the right column.
 A property is represented by a small icon that has a hand holding a piece of paper. Methods
are denoted by little green blocks, while events are denoted by yellow lightning bolt icon.

Object naming conversions of controls (prefix)

Form - frm
Label - lbl
TextBox - txt
CommandButton - cmd
CheckBox - chk
OptionButton - opt
ComboBox - cbo
ListBox - lst
Frame - fme
PictureBox - pic
Image - img

6
Shape - shp
Line -lin
HScrollBar - hsb
VScrollBar - vsb

Visual Basic 6.0 - Properties, Methods and Events


 All the controls in the ToolBox except the Pointer are objects in Visual Basic. These objects have
associated properties, methods and events.
 A property is a named attribute of a programming object. Properties define the characteristics of
an object such as Size, Color etc. or sometimes the way in which it behaves.
 For example, a TextBox accepts properties such as Enabled, Font, MultiLine, Text, Visible,
Width, etc.

 Enables property allows the TextBox to be enabled or disabled at run time depending on the
condition set to True or False.
 Font property sets a particular font in the TextBox.
 MultiLine property allows the TextBox to accept and display multiple lines at run time.
 Text property of the TextBox control sets a particular text in the control.
 Visible property is used to hide the object at run time.
 Width property sets the TextBox to the desired width at design time.

These properties are design-time properties that can be set at the design time by selecting the
Properties Window. But certain properties cannot be set at desgn time.

Example: The CurrentX and CurrentY properties of a Form cannot be set at the design time.

A method is an action that can be performed on objects. For example, a cat is an object. Its
properties might include long white hair, blue eyes, 3 pounds weight etc.

In object-oriented programming, a method is a connected or built-in procedure, a block of code


that can be invoked to impart some action on a particular object.

A method requires an object to provide them with a context. For example, the word Move has no
meaning in Visual Basic, but the statement,

Text1.Move 700, 400performs a very precise action. The TextBox control has other associated
methods such as Refresh, SetFocus, etc.

 The Refresh method enforces a complete repaint of the control or a Form. For example,
Text1.Refresh refreshes the TextBox.
 The Setfocus method moves the focus on the control. For Example Text1.SetFocus sets the
focus to TextBox control Text1.

7
Event Driven Programming

 Visual Basic programs are built around events. Events are various things that can happen in a
program.
 This will become clearer when studied in contrast to procedural programming.
 In procedural languages, an application is written is executed by checking for the program
logically through the program statements.
 While in an event driven application, the program statements are executed only when a
particular event calls a specific part of the code that is assigned to the event.

Example:The TextBox control supports various events such as Change, Click, MouseMove and
many more that will be listed in the Properties dropdown list in the code window for the TextBox
control.

 The code entered in the Change event fires when there is a change in the contents of theTextBox
 The Click event fires when the TextBox control is clicked.
 The MouseMove event fires when the mouse is moved over the TextBox

Working with Forms in Visual Basic 6

The Appearance of Forms


The main characteristic of a Form is the title bar on which the Form's caption is displayed. On
the left end of the title bar is the Control Menu icon. Clicking this icon opens the Control Menu.
Maximize, Minimize and Close buttons can be found on the right side of the Form. Clicking on these
buttons performs the associated function.

The following figure illustrates the appearance of a Form

The control menu contains the following commands :

 Restore : Restores a maximized Form to the size it was before it was maximized; available only if
the Form has been maximized.

8
 Move : Lets the user moves the Form around with the mouse
 Size : Lets the user resizes the control with the mouse
 Minimize: Minimizes the Form
 Maximize : Maximizes the Form
 Close : Closes the Form

Setting the Start-Up Form

A typical application has more than a single Form. When an application runs the main Form is
loaded. By setting the Project properties you can control which Form is to be displayed in the Start-
Up of the application. Following figure illustrates the Project property window.

By default, Visual Basic suggests the name of the first Form created when the project started.

Loading and Unloading Forms

In order to load and unload the forms, Load and Unload statements are used.

Syntax :Load FormNameSyntax:Unload FormName

The FormName variable is the name of the Form to be loaded or unloaded. Unlike the Show
method which cares of both loading and displaying the Form, the load statement doesn't show the
Form, just call the Form's Show method to display it on the desktop.

Showing and Hiding FormsShow method is used to Show a Form. If the Form is loaded but
invisible, the Show method is used to bring the Form on Top every other window. If the Form is not
loaded, the Show method loads it and then displays it.

Syntax :FormName.Show mode

The FormName variable is the Form's name, and the optional argument mode determines whether the
Form will be Modal or not. It can have one of the following syntax:

* 0-Modeless (defaultNormal forms, forms interact with the user and the user allowed to switch to
any other Form of the application. Default the mode is set to modeless.

9
* 1-ModalModal Forms takes the total control of the application where user cannot switch to any
other Forms in the application unless the Form is closed.

Hiding FormsThe Hide method is used to hide a Form. Syntax:FormName.Hide

To hide a Form from within its own code, the following code can be used.

Me.Hide

Forms that are hidden are not unloaded; they remains in the memory and can be displayed instantly
with the Show Method. When a Form is hidden, possible to access its properties and code. Also can
change the settings of its Control Properties or call any Public functions in the Form.

The following is an example illustrates the Show method and Mode statement

* Open a new Project and save the Project

Design the application as shown below

Object Property Setting

Caption Form1
Form
Name frm1
Caption Form2
Form
Name frm2
Caption Form3
Form
Name frm3
Click on a button
Caption
Label to display a Form
Name
Label1

10
The following code is typed in the Click event of the command buttons

Finding out the difference between Unload and Hide method

The difference between Unload and Hide methods .Example: Open a new project and save
the project. Draw two buttons on the form and name those as shown above.

In the click event of the Hide button Following code is entered.

Me.Hide

In the click event of the Unload button following code is entered.

Unload Me

Save the project and run the application. To click on Hide button that the Form is invisible but
the application is still running. But when click on Unload button that the application is terminated.

11
Developing an application:

Two steps are there,

1.Visual programming stepinvolves designing an application with various tools that come along
with the VB project.
2.Code programming step

Variables in Visual Basic 6


Variables are the memory locations which are used to store values temporarily. A defined
naming strategy has to be followed while naming a variable.

These are the rules to follow when naming elements in VB - variables, constants, controls,
procedures, and so on:

 A name must begin with a letter.


 May be as much as 255 characters long (but don't forget that somebody has to type the stuff!).
 Must not contain a space or an embedded period or type-declaration characters used to specify
a data type; these are ! # % $ & @
 Must not be a reserved word (that is part of the code, like Option, for example)
 The dash, although legal, should be avoided because it may be confused with the minus sign.
Instead of First-name use First_name or FirstName.

There are many ways of declaring variables in Visual Basic. Depending on where the variables
are declared and how they are declared. The different ways of declaring variables in Visual Basic are,

 Explicit Declaration
 Using Option Explicit statement
 Scope of Variables

Explicit Declaration

Declaring a variable tells Visual Basic to reserve space in memory. It is not must that a
variable should be declared before using it. Automatically whenever Visual Basic encounters a new
variable, it assigns the default variable type and value. This is called implicit declaration.

Though this type of declaration is easier for the user, to have more control over the variables,
it is advisable to declare them explicitly. The variables are declared with a Dim statement to name the
variable and its type. The As type clause in the Dim statement allows to define the data type or object
type of the variable. This is called explicit declaration.

Syntax: Dim variable [As Type]

For example,Dim strName As String


Dim intCounter As Integer

12
Using Option Explicit statement

It may be convenient to declare variables implicitly, but it can lead to errors that may not be
recognized at run time. Example a variable by name intcount is used implicitly and is assigned to a
value. In the next step, this field is incremented by 1 by the following statement

Intcount = Intcount + 1

This calculation will result in intcount yielding a value of 1 as intcount would have been
initialized to zero. This is because the intcount variable has been mityped as incont in the right hand
side of the second variable.

But Visual Basic does not see this as a mistake and considers it to be new variable and
therefore gives a wrong result.

In Visual Basic, to prevent errors of this nature, declare a variable by adding the following
statement to the general declaration section of the Form.

Option Explicit

This forces the user to declare all the variables. The Option Explicit statement checks in the
module for usage of any undeclared variables and reports an error to the user. The user can thus
rectify the error on seeing this error message.

The Option Explicit statement can be explicitly placed in the general declaration section of
each module using the following steps.

 Click Options item in the Tools menu


 Click the Editor tab in the Options dialog box
 Check Require Variable Declaration option and then click the OK button

Scope of variables: A variable is scoped to a procedure-level (local) or module-level variable


depending on how it is declared. The scope of a variable, procedure or object determines which part
of the code in our application are aware of the variable's existence.

A variable is declared in general declaration section of the Form, and hence is available to all the
procedures. Local variables are recognized only in the procedure in which they are declared.

They can be declared with Dim and Static keywords. If we want a variable to be available to all of the
procedures within the same module, or to all the procedures in an application, a variable is declared
with broader scope.
Local Variables: A local variable is one that is declared inside a procedure. This variable is only
available to the code inside the procedure and can be declared using the Dim statements as given
below.

13
Dim sum As Integer

The local variables exist as long as the procedure in which they are declared, is executing.
Once a procedure is executed, the values of its local variables are lost and the memory used by these
variables is freed and can be reclaimed. Variables that are declared with keyword Dim exist only as
long as the procedure is being executed.

Static Variables: Static variables are not reinitialized each time Visual Invokes a procedure and
therefore retains or preserves value even when a procedure ends.
To keep track of the number of times a command button in an application is clicked, a static
counter variable has to be declared. These static variables are also ideal for making controls
alternately visible or invisible.

Static intPermanent As Integer

Variables have a lifetime in addition to scope. The values in a module-level and public
variables are preserved for the lifetime of an application whereas local variables declared with Dim
exist only while the procedure in which they are declared is still being executed. The value of a local
variable can be preserved using the Static keyword. The follwoing procedure calculates the running
total by adding new values to the previous values stored in the static variable value.

Function RunningTotal ( )
Static Accumulate
Accumulate = Accumulate + num
RunningTotal = Accumulate
End Function

If the variable Accumulate was declared with Dim instead of static, the previously
accumulated values would not be preserved accross calls to the procedure, and the procedure would
return the same value with which it was called. To make all variables in a procedure static, the Static
keyword is placed at the beginning of the procedure heading as given in the below statement.

Static Function RunningTotal ( )

Example: An event procedure for a CommandButton that counts and displays the number of clicks
made.

Private Sub Command1_Click ( )


Static Counter As Integer
Counter = Counter + 1
Print Counter
End Sub

The first time we click the CommandButton, the Counter starts with its default value of zero.
Visual Basic then adds 1 to it and prints the result.

14
Module Level Variables: A module level variable is available to all the procedures in the module.
They are declared using the Public or the Private keyword.
Puplic intPermanent As Integer
Private intTemp As Integer
Declaring a variable using the public keyword makes it available throughout the application
even for the other modules.
At the module-level there is no difference between Dim and Private, but is preferred because
it makes the code easier to read.
Public variables should not be declared within a procedure. It is in different modules can share
the same name and they can be differentiated in code.
Example: If the public integer variable intY is declared in both Form1 and Module1of a project
it can be referred as Form1.intY and Module1.intY
Public vs Local Variables :A variable can have the same name and different scope. Example, a
public variable named R and within a procedure we can declare a local variable R. References to the
name R within the procedure would access the local variable and references to R outside the
procedure would access the public variable.

Modules:

Code in Visual Basic is stored in the form of modules. The three kind of modules are Form
Modules, Standard Modules and Class Modules. A simple application may contain a single Form, and
the code resides in that Form module itself.

As the application grows, additional Forms are added and there may be a common code to be
executed in several Forms. To avoid the duplication of code, a separate module containing a
procedure is created that implements the common code. This is a standard Module.

Class module (.CLS filename extension) are the foundation of the object oriented
programming in Visual Basic. New objects can be created by writing code in class modules. Each
module can contain:

Declarations : May include constant, type, variable and DLL procedure declarations.

Procedures : A sub function, or property procedure that contain pieces of code that can be executed
as a unit.

Data types in Visual Basic 6

By default Visual Basic variables are of variant data types. The variant data type can store
numeric, date/time or string data. When a variable is declared, a data type is supplied for it that
determines the kind of data they can store.

15
The fundamental data types in Visual Basic including variant are integer, long, single, double,
string, currency, byte and boolean. Visual Basic supports a vast array of data types. Each data type
has limits to the kind of information and the minimum and maximum values it can hold.

1. Numeric:

Byte Store integer values in the range of 0 - 255

Integer Store integer values in the range of (-32,768) - (+ 32,767)

Long Store integer values in the range of (- 2,147,483,468) - (+ 2,147,483,468)

Single Store floating point value in the range of (-3.4x10-38) - (+ 3.4x1038)

Double Store large floating value which exceeding the single data type value

store monetary values. It supports 4 digits to the right of decimal point and
Currency
15 digits to the left

2. String : Use to store alphanumeric values. A variable length string can store approximately 4
billion characters

3. Date: Use to store date and time values. A variable declared as date type can store both date and
time values and it can store date values 01/01/0100 up to 12/31/9999

4. Boolean: Boolean data types hold either a true or false value. These are not stored as numeric
values and cannot be used as such. Values are internally stored as -1 (True) and 0 (False) and any
non-zero value is considered as true.

5. Variant:Stores any type of data and is the default Visual Basic data type. In Visual Basic if we
declare a variable without any data type by default the data type is assigned as default.

Operators in Visual Basic

Arithmetical Operators

Operators Description Example Result

+ Add 5+5 10

16
- Substract 10-5 5

/ Divide 25/5 5

\ Integer Division 20\3 6

* Multiply 5*4 20

^ Exponent (power of) 3^3 27

Mod Remainder of division 20 Mod 6 2

"George"&"
& String concatenation "George Bush"
"&"Bush"

Relational Operators

Operators Description Example Result

> Greater than 10>8 True

< Less than 10<8 False

>= Greater than or equal to 20>=10 True

<= Less than or equal to 10<=20 True

<> Not Equal to 5<>4 True

= Equal to 5=7 False

Logical Operators

17
Operators Description

OR Operation will be true if either of the operands is true

AND Operation will be true only if both the operands are true

Procedures in Visual Basic 6


Visual Basic offers different types of procedures to execute small sections of coding in
applications. Visual Basic programs can be broken into smaller logical components called
Procedures.

Procedures are useful for condensing repeated operations such as the frequently used
calculations, text and control manipulation etc. The benefits of using procedures in programming
are:

 It is easier to debug a program a program with procedures, which breaks a program into
discrete logical limits.
 Procedures used in one program can act as building blocks for other programs with
slight modifications.

A Procedure can be Sub, Function or Property Procedure.

Sub Procedures : A sub procedure can be placed in standard, class and form modules. Each time the
procedure is called, the statements between Sub and End Sub are executed. The syntax for a sub
procedure is as follows:

[Private | Public] [Static] Sub Procedurename [( arglist)]


[ statements]
End Sub

arglist is a list of argument names separated by commas. Each argument acts like a variable in the
procedure. There are two types of Sub Procedures namely general procedures and event procedures.

Event Procedures: An event procedure is a procedure block that contains the control's actual name,
an underscore(_), and the event name. The following syntax represents the event procedure for a
Form_Load event.

Private Sub Form_Load()


....statement block..
End Sub

18
Event Procedures acquire the declarations as Private by default.

General Procedures: A general procedure is declared when several event procedures perform the
same actions. It is a good programming practice to write common statements in a separate procedure
(general procedure) and then call them in the event procedure.

In order to add General procedure:

 The Code window is opened for the module to which the procedure is to be added.
 The Add Procedure option is chosen from the Tools menu, which opens an Add Procedure
dialog box as shown in the figure given below.
 The name of the procedure is typed in the Name textbox
 Under Type, Sub is selected to create a Sub procedure, Function to create a Function
procedure or Property to create a Property procedure.
 Under Scope, Public is selected to create a procedure that can be invoked outside the module,
or Private to create a procedure that can be invoked only from within the module.

We can also create a new procedure in the current module by typing Sub ProcedureName,
Function ProcedureName, or Property ProcedureName in the Code window. A Function procedure
returns a value and a Sub Procedure does not return a value.

Function Procedures

Functions are like sub procedures, except they return a value to the calling procedure. They
are especially useful for taking one or more pieces of data, called arguments and performing some
tasks with them. Then the functions returns a value that indicates the results of the tasks complete
within the function.

The following function procedure calculates the third side or hypotenuse of a right triangle,
where A and B are the other two sides. It takes two arguments A and B (of data type Double) and
finally returns the results.

19
Function Hypotenuse (A As Double, B As Double) As Double
Hypotenuse = sqr (A^2 + B^2)
End Function

The above function procedure is written in the general declarations section of the Code
window. A function can also be written by selecting the Add Procedure dialog box from the Tools
menu and by choosing the required scope and type.

Property Procedures: A property procedure is used to create and manipulate custom properties. It is
used to create read only properties for Forms, Standard modules and Class modules.

Visual Basic provides three kind of property procedures-Property,

 Let procedure that sets the value of a property,

 Property Get procedure that returns the value of a property,

 Property Set procedure that sets the references to an object.

Control Structures in Visual Basic 6.0


Control Statements are used to control the flow of program's execution. Visual Basic supports
control structures such as,

 if... Then,
 if...Then ...Else,
 Select...Case, and Loop structures such as
 Do While...Loop,
 While...Wend,
 For...Next etc method.

If...Then selection structure

The If...Then selection structure performs an indicated action only when the condition is True;
otherwise the action is skipped.

Syntax of the If...Then selection

If <condition> Then
statement
End If

e.g.: If average>75 Then


txtGrade.Text = "A"
End If

20
If...Then...Else selection structure

The If...Then...Else selection structure allows the programmer to specify that a different action
is to be performed when the condition is True than when the condition is False.

Syntax of the If...Then...Else selection

If <condition > Then


statements
Else
statements
End If

e.g.: If average>50 Then


txtGrade.Text = "Pass"
Else
txtGrade.Text = "Fail"
End If

Nested If...Then...Else selection structure

Nested If...Then...Else selection structures test for multiple cases by placing If...Then...Else
selection structures inside If...Then...Else structures.

Syntax of the Nested If...Then...Else selection structure

You can use Nested If either of the methods as shown above

Method 1

If < condition 1 > Then


statements
ElseIf < condition 2 > Then
statements
ElseIf < condition 3 > Then
statements
Else
Statements
End If

Method 2

If < condition 1 > Then


statements
Else
If < condition 2 > Then

21
statements
Else
If < condition 3 > Then
statements
Else
Statements
End If
End If
EndIf

e.g.: Assume you have to find the grade using nested if and display in a text box

If average > 75 Then


txtGrade.Text = "A"
ElseIf average > 65 Then
txtGrade.Text = "B"
ElseIf average > 55 Then
txtGrade.text = "C"
ElseIf average > 45 Then
txtGrade.Text = "S"
Else
txtGrade.Text = "F"
End If

Select...Case selection structure

Select...Case structure is an alternative to If...Then...ElseIf for selectively executing a single


block of statements from among multiple block of statements. Select...case is more convenient to use
than the If...Else...End If. The following program block illustrate the working of Select...Case.

Syntax of the Select...Case selection structure

Select Case Index


Case 0
Statements
Case 1
Statements
End Select

e.g.: Assume you have to find the grade using select...case and display in the text box

Dim average as Integer

average = txtAverage.Text
Select Case average
Case 100 To 75

22
txtGrade.Text ="A"
Case 74 To 65
txtGrade.Text ="B"
Case 64 To 55
txtGrade.Text ="C"
Case 54 To 45
txtGrade.Text ="S"
Case 44 To 0
txtGrade.Text ="F"
Case Else

MsgBox "Invalid average marks"


End Select

VB Array - Arrays in Visual Basic 6

 An array is a consecutive group of memory locations that all have the same name and the
same type. To refer to a particular location or element in the array, need to specify the array
name and the array element position number.
 The Individual elements of an array are identified using an index. Arrays have upper and
lower bounds and the elements have to lie within those bounds.
 Each index number in an array is allocated individual memory space and therefore users must
evade declaring arrays of larger size than required.
 Possible to declare an array of any of the basic data types including variant, user-defined types
and object variables. The individual elements of an array are all of the same data type.

Declaring arrays

Arrays occupy space in memory. The programmer specifies the array type and the number of
elements required by the array so that the compiler may reserve the appropriate amount of memory.

Arrays may be declared as Public (in a code module), module or local. Module arrays are
declared in the general declarations using keyword Dim or Private. Local arrays are declared in a
procedure using Dim or Static. Array must be declared explicitly with keyword "As".

There are two types of arrays in Visual Basic namely:

Fixed-size array : The size of array always remains the same-size doesn't change during the
program execution.

Dynamic array : The size of the array can be changed at the run time- size changes during the
program execution.

23
Fixed-sized Arrays: When an upper bound is specified in the declaration, a Fixed-array is created.
The upper limit should always be within the range of long data type.

Declaring a fixed-array : Dim numbers(5) As Integer

In the above illustration, numbers is the name of the array, and the number 6 included in the
parentheses is the upper limit of the array. The above declaration creates an array with 6 elements,
with index numbers running from 0 to 5.

If we want to specify the lower limit, then the parentheses should include both the lower and
upper limit along with the To keyword. An example for this is given below.

Dim numbers (1 To 6 ) As Integer

In the above statement, an array of 10 elements is declared but with indexes running from 1 to 6.

A public array can be declared using the keyword Public instead of Dim as shown below.

Public numbers(5) As Integer

Multidimensional Arrays

 Arrays can have multiple dimensions. A common use of multidimensional arrays is to represent
tables of values consisting of information arranged in rows and columns.
 To identify a particular table element, we must specify two indexes: The first (by convention)
identifies the element's row and the second (by convention) identifies the element's column.
 Tables or arrays that require two indexes to identify a particular element are called two
dimensional arrays.
 Multidimensional arrays can have more than two dimensions. Visual Basic supports at least 60
array dimensions, but most people will need to use more than two or three dimensional-arrays.

The following statement declares a two-dimensional array 50 by 50 array within a procedure.

Dim AvgMarks ( 50, 50)

It is also possible to define the lower limits for one or both the dimensions as for fixed size arrays. An
example for this is given here.

Dim Marks ( 101 To 200, 1 To 100)

An example for three dimensional-array with defined lower limits is given below.

Dim Details( 101 To 200, 1 To 100, 1 To 100)

24
Static and dynamic arrays

Static arrays must include a fixed number of items, and this number must be known at
compile time so that the compiler can set aside the necessary amount of memory. You create a static
array using a Dim statement with a constant argument:

' This is a static array.


Dim Names(100) As String

Visual Basic starts indexing the array with 0. Therefore, the preceding array actually holds 101 items.

Most programs don't use static arrays because programmers rarely know at compile time how
many items you need and also because static arrays can't be resized during execution.

Both these issues are solved by dynamic arrays. Declaring and creating dynamic arrays in two
distinct steps.

 In general, declaring the array to account for its visibility (for example, at the beginning of
a module if you want to make it visible by all the procedures of the module) using a Dim
command with an empty pair of brackets.
 Then you create the array when you actually need it, using a ReDim statement:

' An array defined in a BAS module (with Private scope)


Dim Customers() As String
...
Sub Main()
' Here you create the array.
ReDim Customer(1000) As String
End Sub

If you're creating an array that's local to a procedure, you can do everything with a single ReDim
statement:

Sub PrintReport()
' This array is visible only to the procedure.
ReDim Customers(1000) As String
' ...
End Sub

If you don't specify the lower index of an array, Visual Basic assumes it to be 0, unless an
Option Base 1 statement is placed at the beginning of the module. If you want to explicitly use a
lower index different from 0, use this syntax instead:

ReDim Customers(1 To 1000) As String

25
Dynamic arrays can be re-created at will, each time with a different number of items. When
re-create a dynamic array, its contents are reset to 0 (or to an empty string) and lose the data it
contains. To resize an array without losing its contents, use the ReDim Preserve command:

ReDim Preserve Customers(2000) As String

When resizing an array, need not change the number of its dimensions nor the type of the
values it contains. Moreover, using ReDim Preserve on a multidimensional array, can resize only its
last dimension:

ReDim Cells(1 To 100, 10) As Integer


...
ReDim Preserve Cells(1 To 100, 20) As Integer ' This works.
ReDim Preserve Cells(1 To 200, 20) As Integer ' This doesn't.

Finally, you can destroy an array using the Erase statement. If the array is dynamic, Visual
Basic releases the memory allocated for its elements (and you can't read or write them any longer); if
the array is static, its elements are set to 0 or to empty strings.

Use the LBound and UBound functions to retrieve the lower and upper indices. If the array
has two or more dimensions, need to pass a second argument to these functions to specify the
dimension you need:

Print LBound(Cells, 1) ' Displays 1, lower index of 1st dimension


Print LBound(Cells) ' Same as above
Print UBound(Cells, 2) ' Displays 20, upper index of 2nd dimension
' Evaluate total number of elements.
NumEls = (UBound(Cells) _ LBound(Cells) + 1) * _
(UBound(Cells, 2) _ LBound(Cells, 2) + 1)

Working with controls in Visual Basic 6

Controls are used to receive user input and display output and has its own set of properties,
methods and events.

Creating and Using Controls


 A control is an object that can be drawn on a Form object to enable or enhance user
interaction with an application.
 Controls have properties that define aspects their appearance, such as position, size and
colour, and aspects of their behavior, such as their response to the user input.
 They can respond to events initiated by the user or set off by the system. For instance, a code
could be written in a CommandButton control's click event procedure that would load a file
or display a result.

26
 In addition to properties and events, methods can also be used to manipulate controls from
code. For instance, the move method can be used with some controls to change their location
and size.
 Most of the controls provide choices to users that can be in the form of OptionButton or
CheckBox controls, ListBox entries or ScrollBars to select a value.

Classification of Controls

Visual Basic cojntrols are broadly classified as standard controls, ActiveX controls and
insertable objects. Standard controls such as CommandButton, Label and Frame controls are
contained inside .EXE file and are always included in the ToolBox which cannot be removed.
ActiveX controls exist as separate files with either .VBX or .OCX extension. They include
specialized controls such as;

 MSChart control
 The Communications control
 The Animation control
 The ListView control
 An ImageList control
 The Multimedia control
 The Internet Transfer control
 The WinSock control
 The TreeView control
 The SysInfo control
 The Picture Clip control

TabIndex property of Controls

Visual Basic uses the TabIndex property to determine the control that would receive the focus
next when a tab key is pressed. Every time a tab key is pressed, Visual Basic looks at the value of the
TabIndex for the control that has focus and then it scans through the controls searching for the next
highest TabIndex number. When there are no more controls with higher TabIndex value, Visual Basic
starts all over again with 0 and looks for the first control with TabIndex of 0 or higher that can accept
keyboard input.

By default, Visual Basic assigns a tab order to control as we draw the controls on the Form,
except for Menu, Timer, Data, Image, Line and Shape controls, which are not included in tab order.
At run time, invisible or disabled controls also cannot receive the focus although a TabIndex value is
given. Setting the TabIndex property of controls is compulsory in development environment.

Using TextBox Control In Visual Basic 6

TextBox controls offer a natural way for users to enter a value in your program. For this
reason, they tend to be the most frequently used controls in the majority of Windows applications.

27
TextBox controls, which have a great many properties and events, are also among the most complex
intrinsic controls.

Setting properties to a TextBox

 Text can be entered into the text box by assigning the necessary string to the text property of the
control
 If the user needs to display multiple lines of text in a TextBox, set the MultiLine property to True
 To customize the scroll bar combination on a TextBox, set the ScrollBars property.
 Scroll bars will always appear on the TextBox when it's MultiLine property is set to True and its
ScrollBars property is set to anything except None(0)
 If you set the MultilIne property to True, you can set the alignment using the Alignment property.
The test is left-justified by default. If the MultiLine property is et to False, then setting the Alignment
property has no effect.

Run-Time Properties of a TextBox control

 The SelStart property sets or returns the position of the blinking caret (the insertion point where
the text you type appears).
 The SelLength property returns the number of characters in the portion of text that has been
highlighted by the user, or it returns 0 if there's no highlighted text.
 The SelText property sets or returns the portion of the text that's currently selected, or it returns an
empty string if no text is highlighted.

When you want to append text to a TextBox control, you should use the following code (instead of
using the concatenation operator) to reduce flickering and improve performance:

Text1.SelStart = Len(Text1.Text)
Text1.SelText = StringToBeAdded

One of the typical operations you could find yourself performing with these properties is selecting the
entire contents of a TextBox control. You often do it when the caret enters the field so that the user
can quickly override the existing value with a new one, or start editing it by pressing any arrow key:

Private Sub Text1_GotFocus()


Text1.SelStart = 0
' A very high value always does the trick.
Text1.SelLength = 9999
End Sub

Always set the SelStart property first and then the SelLength or SelText properties. When you assign
a new value to the SelStart property, the other two are automatically reset to 0 and an empty string
respectively, thus overriding your previous settings.

The selected text can be copied to the Clipboard by using SelText:

28
Clipboard.SelText text, [format]

In the above syntax, text is the text that has to be placed into the Clipboard, and format has three
possible values.

1. VbCFLink - conversation information


2. VbCFRTF - Rich Text Format
3. VbCFText - Text

To get text from the clipboard using the GetText() function this way:

Clipboard.GetText ([format])

The following Figure summarizes the common TextBox control's properties and methods.

Property/ Method Description

Properties
Enabled specifies whether user can interact with this control or not

Index Specifies the control array index

If this control is set to True user can use it else if this control is set to
Locked
false the control cannot be used

Specifies the maximum number of characters to be input. Default value


MaxLength
is set to 0 that means user can input any number of characters

Using this we can set the shape of the mouse pointer when over a
MousePointer
TextBox

By setting this property to True user can have more than one line in the
Multiline
TextBox

PasswordChar This is to specify mask character to be displayed in the TextBox

This to set either the vertical scrollbars or horizontal scrollbars to make


ScrollBars
appear in the TextBox. User can also set it to both vertical and
horizontal. This property is used with the Multiline property.

29
Text Specifies the text to be displayed in the TextBox at runtime

ToolTipIndex This is used to display what text is displayed or in the control

By setting this user can make the Textbox control visible or invisible at
Visible
runtime

Method
SetFocus Transfers focus to the TextBox

Event procedures
Change Action happens when the TextBox changes

Click Action happens when the TextBox is clicked

GotFocus Action happens when the TextBox receives the active focus

LostFocus Action happens when the TextBox loses it focus

KeyDown Called when a key is pressed while the TextBox has the focus

KeyUp Called when a key is released while the TextBox has the focus

Using a Label Control

Most people use Label controls to provide a descriptive caption and possibly an associated hot
key for other controls, such as TextBox, ListBox, and ComboBox, that don't expose the Caption
property

Caption is the default property for Label controls. Be careful to set the Label's TabIndex
property so that it's 1 minus the TabIndex property of the companion control.

Other useful properties are BorderStyle(if you want the Label control to appear inside a 3D
border) and Alignment (if you want to align the caption to the right or center it on the control).

In most cases, the alignment depends on how the Label control relates to its companion
control: for example, if the Label control is placed to the left of its companion field, you might want
to set its Alignment property to 1-Right Justify. The value 2-Center is especially useful for stand-
alone Label controls.
30
Different settings for the Alignment property of Label controls.

 If the caption string is a long one, you might want to set the Label's WordWrap property to true so
that it will extend for multiple lines instead of being truncated by the right border of the control.
 Alternatively, you might decide to set the AutoSize property to True and let the control
automatically resize itself to accommodate longer caption strings.
 If you want to show a character string somewhere on the form but at the same time you don't want
to obscure underlying objects, set the BackStyle property to 0-Transparent.
 If you're using the Label control to display data read from elsewhere—for example, a database field
or a text file—you should set its UseMnemonics property to False.

Frame Controls

 Frame controls are similar to Label controls in that they can serve as captions for those controls that
don't have their own.
 Moreover, Frame controls can also (and often do) behave as containers and host other controls.
 In most cases, you only need to drop a Frame control on a form and set its Caption property. If you
want to create a borderless frame, you can set its BorderStyle property to 0-None.
 Controls that are contained in the Frame control are said to be child controls. Moving a control at
design time over a Frame control—or over any other container, for that matter—doesn't
automatically make that control a child of the Frame control.
 After you create a Frame control, you can create a child control by selecting the child control's icon
in the Toolbox and drawing a new instance inside the Frame's border.
 Alternatively, to make an existing control a child of a Frame control, you must select the control,
press Ctrl+X to cut it to the Clipboard, select the Frame control, and press Ctrl+V to paste the
control inside the Frame
 Frame controls, like all container controls, have two interesting features. If you move a Frame
control, all the child controls go with it.
 If you make a container control disabled or invisible, all its child controls also become disabled or
invisible. You can exploit these features to quickly change the state of a group of related controls.

CommandButton Controls in VB6

Using CommandButton controls is trivial. Just draw the control on the form's surface, set its
Caption property to a suitable string (adding an & character to associate a hot key with the control if

31
you so choose), and finished, at least with user-interface issues. To make the button functional, need
to write code in its Click event procedure, as in this fragment:

Private Sub Command1_Click()


' Save data, then unload the current form.
Call SaveDataToDisk
Unload Me
End Sub

Two other properties at design time to modify the behavior of a CommandButton control. Set
the Default property to True if it's the default push button for the form (the button that receives a click
when the user presses the Enter key—usually the OK or Save button).

Similarly, set the Cancel property to True if you want to associate the button with the Escape
key.

The only relevant CommandButton's run-time property is Value, which sets or returns the
state of the control (True if pressed, False otherwise). Value is also the default property for this type
of control.
Command1.Value = True

The CommandButton control supports the usual set of keyboard and mouse events
(KeyDown, KeyPress, KeyUp, MouseDown, MouseMove, MouseUp, but not the DblClick event)
and also the GotFocus and LostFocus events, but you'll rarely have to write code in the corresponding
event procedures.

Properties of a CommandButton control

 To display text on a CommandButton control, set its Caption property.


 An event can be activated by clicking on the CommandButton.
 To set the background colour of the CommandButton, select a colour in the BackColor property.
 To set the text colour set the Forecolor property.
 Font for the CommandButton control can be selected using the Font property.
 To enable or disable the buttons set the Enabled property to True or False
 To make visible or invisible the buttons at run time, set the Visible property to True or False.
 Tooltips can be added to a button by setting a text to the Tooltip property of the CommandButton.
 A button click event is handled whenever a command button is clicked. To add a click event handler,
double click the button at design time, which adds a subroutine like the one given below.

Private Sub Command1_Click( )


..................
End Sub

32
OptionButton Controls in VB6

OptionButton controls are also known as radio buttons because of their shape. It used a group
of two or more because their purpose is to offer a number of mutually exclusive choices. Anytime
you click on a button in the group, it switches to a selected state and all the other controls in the group
become unselected.

Set an OptionButton control's Caption property to a meaningful string, and change its
Alignment property to make the control right aligned. If the control is the one in its group that's in the
selected state, also set its Valueproperty to True. (The OptionButton's Value property is a Boolean
value because only two states are possible.) Value is the default property for this control.

At run time, typically query the control's Value property to learn which button in its group
has been selected. Let's say you have three OptionButton controls, named optWeekly, optMonthly,
and optYearly. You can test which one has been selected by the user as follows:

If optWeekly.Value Then
' User prefers weekly frequency.
ElseIf optMonthly.Value Then
' User prefers monthly frequency.
ElseIf optYearly.Value Then
' User prefers yearly frequency.
End If

Strictly, avoid the test for the last OptionButton control in its group because all choices are
supposed to be mutually exclusive. But the approach I just showed you increases the code's
readability.

A group of OptionButton controls is often hosted in a Frame control. This is necessary when
there are other groups of OptionButton controls on the form.

Example

Open a new Standard EXE project and the save the Form as Option.frm and save the project as
Option.vbp.

Design the Form as per the following specifications table.

Object Property Settings

Caption Enter a Number


Label
Name Label1
TextBox Text (empty)

33
Name Text1

Caption &Close
CommandButton
Name Command1
Caption &Octal
OptionButton
Name optOct
Caption &Hexadecimal
OptionButton
Name optHex
Caption &Decimal
OptionButton
Name optDec

The application responds to the following events

 The change event of the TextBox reads the value and stores it in a form-level numeric variable.
 The click event of optOct button returns curretval in octal.
 The click event of the optHex button curerntval in hexadecimal
 The click event of the optDec button returns the decimal equivalent of the value held currentval.

The following code is entered in the general declarations section of the Form.

Dim currentval as variant

The variable is initialized to 0 by default. The change event procedure checks to ascertain the number
system (Octal, Hexadecimal) that is in effect and then reads in the number.

Private Sub Text1_Change()


If optOct.Value = True Then
currentval = Val ("&O" & LTrim (Text1.Text) & "&")
Elseif optDec.value = True Then
currentval = Val (LTrim (Text1.Text) & "&")
Else
currentval = Val ("&H" & LTrim (Text1.Text) & "&")
End if
End Sub

The Val function is used to translate string to a number and can recognize Octal and Hexadecimal
strings. The LTrim function trims the leading blanks in the text. The following code is entered in the
click events of the OptionButton controls.

34
Private Sub optOct_Click()
Text1.Text = Oct(currentval)
End Sub

Private Sub optHex_Click()


Text1.Text = Hex(currentval)
End Sub

Private Sub optDec_Click()


Text1.Text = Format(currentval)
End Sub

The follwoing code is entered in the click event of the Close button.

Private Sub cmdClose_Click()


Unlod Me
End Sub

The Application is run by pressing F5 or clicking on the Run icon in the tool bar. By pressing the Exit
button the program is terminated.

Using ListBox and ComboBox Controls In Visual Basic 6


ListBox and ComboBox controls present a set of choices that are displayed vertically in a
column. If the number of items exceed the value that be displayed, scroll bars will automatically
appear on the control. These scroll bars can be scrolled up and down or left to right through the list.

The following Fig lists some of the common ComboBox properties and methods.

Property/Method Description

Properties
By setting this property to True or False user can decide whether
Enabled
user can interact with this control or not

Index Specifies the Control array index

String array. Contains the strings displayed in the drop-down list.


List
Starting array index is 0.

ListCount Integer. Contains the number of drop-down list items

ListIndex Integer. Contains the index of the selected ComboBox item. If an

35
item is not selected, ListIndex is -1

Locked Boolean. Specifies whether user can type or not in the ComboBox

Integer. Specifies the shape of the mouse pointer when over the area
MousePointer
of the ComboBox

Integer. Index of the last item added to the ComboBox. If the


NewIndex
ComboBox does not contain any items , NewIndex is -1

Sorted Boolean. Specifies whether the ComboBox's items are sorted or not.

Style Integer. Specifies the style of the ComboBox's appearance

TabStop Boolean. Specifies whether ComboBox receives the focus or not.

Text String. Specifies the selected item in the ComboBox

ToolTipIndex String. Specifies what text is displayed as the ComboBox's tool tip

Visible Boolean. Specifies whether ComboBox is visible or not at run time

Methods
AddItem Add an item to the ComboBox

Clear Removes all items from the ComboBox

RemoveItem Removes the specified item from the ComboBox

SetFocus Transfers focus to the ComboBox

Event Procedures
Change Called when text in ComboBox is changed

DropDown Called when the ComboBox drop-down list is displayed

GotFocus Called when ComboBox receives the focus

LostFocus Called when ComboBox loses it focus

36
Adding items to a List

It is possible to populate the list at design time or run time

Design Time : To add items to a list at design time, click on List property in the property box and
then add the items. Press CTRL+ENTER after adding each item as shown below.

Run Time : The AddItem method is used to add items to a list at run time. The AddItem method uses
the following syntax.

Object.AddItemitem, Index

Theitem argument is a string that represents the text to add to the list

Theindexargument is an integer that indicates where in the list to add the new item. Not giving the
index is not a problem, because by default the index is assigned.

Following is an example to add item to a combo box. The code is typed in the Form_Load event

Private Sub Form_Load()

Combo1.AddItem 1
Combo1.AddItem 2
Combo1.AddItem 3
Combo1.AddItem 4
Combo1.AddItem 5
Combo1.AddItem 6

End Sub

Removing Items from a List

The RemoveItem method is used to remove an item from a list. The syntax for this is given below.

Object.RemoveItem index

The following code verifies that an item is selected in the list and then removes the selected item
from the list.

37
Private Sub cmdRemove_Click()
If List1.ListIndex > -1 Then
List1.RemoveItem List1. ListIndex
End If
End Sub

Selecting an item from a list box

Use listIndex and List properties. It sets the index number of the currently selected item. The
first item in the list is index number 0. If it is 1 no item is selected.Listcount always one more than the
index number of the last item in the list.NewIndex property returns the index of the last item added to
the list.

List1.addItem “Television”

List1.ListIndex=List1.NewIndex

Sorting the List

The Sorted property is set to True to enable a list to appear in alphanumeric order and False to display
the list items in the order which they are added to the list.

Using the ComboBox

A ComboBox combines the features of a TextBox and a ListBox. This enables the user to
select either by typing text into the ComboBox or by selecting an item from the list. There are three
types of ComboBox styles that are represented as shown below.

Simple combo
Dropdown combo Dropdown list

 Dropdown Combo (style 0)


 Simple Combo (style 1)
 Dropdown List (style 2)

The Simple Combo box displays an edit area with an attached list box always visible
immediately below the edit area. A simple combo box displays the contents of its list all the time. The
user can select an item from the list or type an item in the edit box portion of the combo box. A scroll
bar is displayed beside the list if there are too many items to be displayed in the list box area.

38
The Dropdown Combo box first appears as only an edit area with a down arrow button at the
right. The list portion stays hidden until the user clicks the down-arrow button to drop down the list
portion. The user can either select a value from the list or type a value in the edit area.

The Dropdown list combo box turns the combo box into a Dropdown list box. At run time ,
the control looks like the Dropdown combo box. The user could click the down arrow to view the list.
The difference between Dropdown combo & Dropdown list combo is that the edit area in the
Dropdown list combo is disabled. The user can only select an item and cannot type anything in the
edit area. Anyway this area displays the selected item.

Example

This example is to Add , Remove, Clear the list of items and finally close the application.

 Open a new Standard EXE project is opened an named the Form as Listbox.frm and save the
project as Listbox.vbp
 Design the application as shown below.

Object Property Settings

Caption ListBox
Form
Name frmListBox
Text (empty)
TextBox
Name txtName
Caption Enter a name
Label
Name lblName
ListBox Name lstName

Caption Amount Entered


Label
Name lblAmount
Caption (empty)
Label Name lblDisplay

Border Style 1 Fixed Single


Caption Add
CommandButton
Name cmdAdd

39
Caption Remove
CommandButton
Name cmdRemove
Caption Clear
CommandButton
Name cmdClear
Caption Exit
CommandButton
Name cmdExit

The following event procedures are entered for the TextBox and CommandButton controls.

Private Sub txtName_Change()


If (Len(txtName.Text) > 0) Then 'Enabling the Add button
'if atleast one character
'is entered
cmdAdd.Enabled = True
End If
End Sub
Private Sub cmdAdd_Click()
lstName.AddItem txtName.Text 'Add the entered the characters to the list box

txtName.Text = "" 'Clearing the text box

txtName.SetFocus 'Get the focus back to the


'text box

lblDisplay.Caption = lstName.ListCount 'Display the number of items in the list box

cmdAdd.Enabled = False ' Disabling the Add button


End Sub

40
The click event of the Add button adds the text to the list box that was typed in the Text box.
Then the text box is cleared and the focus is got to the text box. The number of entered values will is
increased according to the number of items added to the listbox.

Private Sub cmdClear_Click()


lstName.Clear
lblDisplay.Caption = lstName.ListCount
End Sub
Private Sub cmdExit_Click()
Unload Me
End Sub
Private Sub cmdRemove_Click()
Dim remove As Integer
remove = lstName.ListIndex 'Getting the index
If remove >= 0 Then 'make sure an item is selected
'in the list box
lstName.RemoveItem remove 'Remove item from the list box

lblDisplay.Caption = lstName.ListCount 'Display the number of items


'in the listbox
End If
End Sub

Remove button removes the selected item from the list as soon as you pressed the Remove
button. The number of items is decreased in the listbox and the value is displayed in the label.

The code for the clear button clears the listbox when you press it. And the number of items shown in
the label becomes 0.

VB ScrollBar - Using ScrollBar Control In Visual Basic 6 (VB6)

The ScrollBar is a commonly used control, which enables the user to select a value by
positioning it at the desired location. It represents a set of values.

The Min and Max property represents the minimum and maximum value. The value property
of the ScrollBar represents its current value, that may be any integer between minimum and
maximum values assigned.

The default initial value for those two properties is 1, but you'll probably have to change
LargeChange to a higher value. For example, if you have a scroll bar that lets you browse a portion of
text, SmallChange should be 1 (you scroll one line at a time) and LargeChange should be set to match
the number of visible text lines in the window.

41
The most important run-time property is Value, which always returns the relative position of
the indicator on the scroll bar. By default, the Min value corresponds to the leftmost or upper end of
the control:

There are two key events for scrollbar controls: the Change event fires when you click on the
scroll bar arrows or when you drag the indicator; the Scroll event fires while you drag the indicator.

Working with control arrays:

Control Arrays in Visual Basic 6

A control array is a group of controls that share the same name type and the same event
procedures. Adding controls with control arrays uses fewer resources than adding multiple control of
same type at design time.

A control array can be created only at design time, and at the very minimum at least one control must
belong to it. You create a control array following one of these three methods:

 You create a control and then assign a numeric, non-negative value to its Index property; you have
thus created a control array with just one element.
 You create two controls of the same class and assign them an identical Name property. Visual Basic
shows a dialog box warning you that there's already a control with that name and asks whether you
want to create a control array. Click on the Yes button.
 You select a control on the form, press Ctrl+C to copy it to the clipboard, and then press Ctrl+V to
paste a new instance of the control, which has the same Name property as the original one. Visual
Basic shows the warning mentioned in the previous bullet.

Control arrays are one of the most interesting features of the Visual Basic environment, and
they add a lot of flexibility to your programs:

 Controls that belong to the same control array share the same set of event procedures; this often
dramatically reduces the amount of code you have to write to respond to a user's actions.
 You can dynamically add new elements to a control array at run time; in other words, you can
effectively create new controls that didn't exist at design time.
 Elements of control arrays consume fewer resources than regular controls and tend to produce
smaller executables. Besides, Visual Basic forms can host up to 256 different control names, but a
control array counts as one against this number. In other words, control arrays let you effectively
overcome this limit.
Creating Controls at Run Time
Control arrays can be created at run time using the statements

 Load object (Index %)


 Unload object (Index %)

Where object is the name of the control to add or delete from the control array. Index % is the value
of the index in the array. The control array to be added must be an element of the existing array

42
created at design time with an index value of 0. When a new element of a control array is loaded,
most of the property settings are copied from the lowest existing element in the array.

Following example illustrates the use of the control array.

* Open a Standard EXE project and save the Form as Calculator.frm and save the Project as
Calculater.vbp.

* Design the form as shown below.

Object Property Setting

Caption Calculator
Form
Name frmCalculator
Caption 1
CommandButton Name cmd

Index 0
Caption 2
CommandButton Name cmd

Index 1
Caption 3
CommandButton Name cmd

Index 2
Caption 4
CommandButton Name cmd

Index 3
Caption 5
CommandButton Name cmd

Index 4
Caption 6
CommandButton
Name cmd

43
Index 5
Caption 7
CommandButton Name cmd

Index 6
Caption 8
CommandButton Name cmd

Index 7
Caption 9
CommandButton Name cmd

Index 8
Caption 0
CommandButton Name cmd

Index 10
Caption .
CommandButton Name cmd

Index 11
Caption AC
CommandButton
Name cmdAC
Caption +
CommandButton
Name cmdPlus
Caption -
CommandButton
Name cmdMinus
Caption *
CommandButton
Name cmdMultiply
Caption /
CommandButton
Name cmdDivide

44
Caption +/-
CommandButton
Name cmdNeg
Name txtDisplay
TextBox
Text ( empty )
Caption =
CommandButton
Name cmdEqual

The following variables are declared inside the general declaration

Dim Current As Double


Dim Previous As Double
Dim Choice As String
Dim Result As Double

The following code is entered in the cmd_Click( ) (Control Array) event procedure

Private Sub cmd_Click(Index As Integer)


txtDisplay.Text = txtDisplay.Text & cmd(Index).Caption
'&is the concatenation operator
Current = Val(txtDisplay.Text)
End Sub

The following code is entered in the cmdAC_Click ( ) event procedure

Private Sub cmdAC_Click()


Current = Previous = 0
txtDisplay.Text = ""
End Sub

The below code is entered in the cmdNeg_Click( ) procedure

45
Private Sub cmdNeg_Click()
Current = -Current
txtDisplay.Text = Current
End Sub

The following code is entered in the click events of the cmdPlus, cmdMinus, cmdMultiply,
cmdDevide controls respectively.

Private Sub cmdDevide_Click()


txtDisplay.Text = ""
Previous = Current
Current = 0
Choice = "/"
End Sub

Private Sub cmdMinus_Click()


txtDisplay.Text = ""
Previous = Current
Current = 0
Choice = "-"
End Sub

Private Sub cmdMultiply_Click()


txtDisplay.Text = ""
Previous = Current
Current = 0
Choice = "*"
End Sub

Private Sub cmdPlus_Click()


txtDisplay.Text = ""
Previous = Current
Current = 0
Choice = "+"
End Sub

To print the result on the text box, the following code is entered in the cmdEqual_Click ( ) event
procedure.

Private Sub cmdEqual_Click()

Select Case Choice

Case "+"
Result = Previous + Current
txtDisplay.Text = Result

46
Case "-"
Result = Previous - Current
txtDisplay.Text = Result
Case "*"
Result = Previous * Current
txtDisplay.Text = Result
Case "/"
Result = Previous / Current
txtDisplay.Text = Result
End Select

Current = Result

End Sub

47

You might also like