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

Unit I VB 6.0 Notes

Visual Basic 6.0 (VB 6.0) is an integrated development environment (IDE) for developing Windows applications. The VB 6.0 IDE contains components like menus, toolbars, a toolbox, and windows for displaying forms, code, and properties. The toolbox contains common controls like labels, text boxes, buttons, and more that can be placed onto forms to create the user interface. Forms are central to VB applications and serve as containers where controls are placed. Key properties of forms include the border style, caption, control box settings, and whether it is movable or resizable. The IDE allows visual design of forms and double clicking controls to add event handler code.

Uploaded by

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

Unit I VB 6.0 Notes

Visual Basic 6.0 (VB 6.0) is an integrated development environment (IDE) for developing Windows applications. The VB 6.0 IDE contains components like menus, toolbars, a toolbox, and windows for displaying forms, code, and properties. The toolbox contains common controls like labels, text boxes, buttons, and more that can be placed onto forms to create the user interface. Forms are central to VB applications and serve as containers where controls are placed. Key properties of forms include the border style, caption, control box settings, and whether it is movable or resizable. The IDE allows visual design of forms and double clicking controls to add event handler code.

Uploaded by

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

Visual Programming – Unit I

Getting Started with VB 6.0


1.1 Visual Basic 6.0 Programming Environment
Visual Basic is an ideal programming language for developing sophisticated professional
applications for MS Windows. Visual Basic was developed from the programming language BASIC in
the 1970s, Microsoft started developing ROM-based interpreted BASIC for the early microprocessor-
based computers. In 1982, MS QuickBasic revolutionized BASIC and was legitimated as a serious
development language for MS-DOS environment. VB 6.0 for Windows requires at least Microsoft
Windows 95 or later versions of Windows.

VB is imitated by using the Start  All Programs  MS Visual Studio  MS Visual Basic
6.0. By Clicking the VB 6.0 icon in Desktop it can be opened. Below Figure shows the interface screen of
VB 6.0 with Menu bar, Toolbar and etc.

The Integrated Development Environment (IDE)


The VB IDE is made up of a number of components such as Menu Bar, Toolbar, Project Explorer,
Properties Windows, Form Layout Window, Toolbox, Form Designer and Object Browser. In earlier
versions, IDE was designed as a Single Document Interface (SDI), but in VB 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.
Menu Bar
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 user commands and a button in the toolbar is clicked once to carry out the action
represented by it.

Dept. of Computer Science, BCAS, Erode 1


Visual Programming – Unit I

Toolbar Action Toolbar Action


Button Button
Adds a New Form Adds a New Module

Opens an existing Project Saves the current Project

Locks and Unlocks the command Display the Properties Window


controls
Display the Object Browser Displays the Project Explorer

Starts an application in design mode Used for debugging, stops execution of


a program while running
Stops execution of an application Toggles breakpoint on menu
and returns to the design mode
Displays the value of the current Traces through each line of code and
selection in the code window steps into procedures
Executes one code procedure or Displays the Menu Editor
statement at a time in the Code
window.
DataView window Visual Component Manager

Toolbox
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. A toolbar is shown in the below.
Pointer PictureBox

Label Textbox
Frame CommandButton
CheckBox Option Button
ComboBox List Box
Hscroll Bar VScrollBar
Timer Drive ListBox
DirListBox FileListBox
Shape Line
Image Data

OLE

Dept. of Computer Science, BCAS, Erode 2


Visual Programming – Unit I

 The pointer helps to move and resize the controls and Forms
 Label displays a text that the user cannot modify or interact with.
 Frame control serves as a visual and functional container for controls.
 CheckBox displays a True/False or Yes/No option.
 TextBox is a control used to display message and enter text.
 The ListBox displays a list of items from which a user can select one.
 ComboBox contains a TextBox and a ListBox. This allows the user to select an item from the
dropdown ListBox or to type a selection in the TextBox.
 HScrollBar or VScrollBar controls allow the user to select a value within the specified range of values.
 Timer control executes timer events at specified intervals of time.
 DirListBox allows the user to select directories and paths, which are displayed.
 Shape control adds a shape to a Form.
 Image control is used to display icons, bitmaps, metafiles, etc.
 OLE control is used to link or embed an object, display and manipulate data from other Windows
based applications
 PictureBox displays icons/bitmaps and metafiles. It display text or acts as a visual container for other
controls.
 CommandButton carries out the specified action when the user chooses it.
 The OptionButton control which is a part of an option group allows the user to select one option even
if it displays multiple choices.
 The DriveListBox displays the valid disk drives and allows the user to select one of them.
 The FileListBox displays a set of files from which a user can select the desired one.
 Line controls draws a straight line to the Form.
 Data control enables the user to connect to an existing database and display information from it.
Form serves as a window that can be customized and controls, graphics and pictures can also be
added to it.

Project Explorer
The project explorer serves as a quick reference to the various elements of a project namely form,
classes and modules. All of the objects that make up the application are packed in a project. A typically
project contains one form, which is a window that is designed as part of the program’s interface.

Properties Window
The Properties window exposes the various characteristics of selected objects. Each and every
Form in an application is considered an object. All the characteristics of an object are called its properties.

Object Browser
The object Browser allows browsing 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 by pressing F2.

Properties, Methods and Events


All the controls in the Toolbox except the Pointer are objects in VB. These objects have associated
properties, methods and events.

A property is a named attribute of a programming object. Properties define the characteristic of an


object such as size, color, etc. or sometimes the way in which it behaves. For example, a TextBox accepts
Dept. of Computer Science, BCAS, Erode 3
Visual Programming – Unit I

properties such as Enabled, Font, Multi Line, Text, Visible, etc. A method is an action that can be
perfomed on objects. The TextBox has associated with Refresh, SetFocus etc.

VB programs are built around Events. Events are various things that can happen in a program. In
an event driven application, the program statements are executed only when calls a specific part of the
code that is assigned to the events.

1.2 Working with Forms


Visual Basic has several different types of objects. A Form is one of the most basic objects in
which the application code and has other objects placed on it to create the user interface. A From may fill
the entire screen or have other Forms contained within it or it may be a custom dialog box. VB initially
includes a default form, Form1 file in each new project. User can change the form’s name and caption to
identify the purpose of the Form. Every Form object has its own properties, events and methods
associated with it.

Setting Form Properties


Any VB application program uses the Form to gather input from the user and to display the output
information to the user. Various Form properties are discussed below.

Border Style
Forms can have a variety of types of borders. Various borders that are available in VB are Name,
Fixed Single, Sizeable, Fixed Double, Fixed ToolWindow and Sizeable ToolWindow.

Caption
The title for the window is stored in the Caption property, the caption appears below the form’s
icon when the form is minimized.

Control Box
This property determines whether the Control box, available by clicking the upper left corner of a
window, will be shown or not.

Icon
This property specifies the icon for the window in the upper left corner of the window.

MousePointer
This property sets the value that indicates the type of mouse pointer displayed when the mouse
pointer appears over a particular area of the object at runtime.

MaxButton
This property indicates Whether the Maximize button should be shown and the Maximize choice
made available in the Control Box menu.

MDIChild
This property specifies if this window must be shown within a multiple document interface (MDI)
window.

Dept. of Computer Science, BCAS, Erode 4


Visual Programming – Unit I

MinButton
This property indicates whether the Minimize button should be shown and the Minimize choice
made available in the Control Box menu.

Moveable
By setting it to False, it is possible to prevent the user from moving the window manually. This is
useful for splash screens and other informational dialog boxes that are shown and dismissed quickly.

StartUpPosition
Instead of writing code to position user window, user can pick a starting position from this drop-
down menu. The available choices are Manual, CenterOwner, CenterScreen and Windows Default.

WindowState
This property indicates whether the window is shown normally, maximized or minimized. It is
possible to pick a starting state for your Form at design time so that when you show the window, it comes
up in that state.

Show Method
The Show method is used to display the Form object. For example, to display the form
frmCalculator, the following code is written.
FrmCalculator.Show

Using Load Statement


The Load statement is used to load a form or control into memory but does not display it. To load
the form frmCalculator, the following code should be entered.
Load frmCalculator

Using the Hide Method


The hide method hides a Form. For example, the following codes hides From object
frmCalculator
frmCalculator.Hide

Using the Unload Statement


The Unload statement removes the form from the display and releases its memory. The following
code should be entered to unload the frmCalculator from memory.
unload frmCalculator

Using the Unload Event


The Unload event procedure is used to verify that the form should be unloaded or specific actions
that have to take place when the form is unload. The unload events occurs when.
 The Form is unloaded using the Unload statement.
 The Form is closed by the user either clicking the Close command on the application menu or clicking
the Close button on the application title bar.

Dept. of Computer Science, BCAS, Erode 5


Visual Programming – Unit I

Setting Run Time and Design Time Properties


Many properties can be set at either design time or runtime, at design time, the controls are added
to a project, their properties set and the relevant code is written. During runtime, user examines the
program in action, just as the end user will eventually see it.
To set a property at design time, the following steps are followed.
 Select control or object whose characteristics are to be changed.
 Activate the Properties window.
 Scroll to the property user want to set and select its name.
 Enter a new setting.
At runtime, property settings can be changed by a program's code. This is accomplished by writing
a special kind of assignment statement that gives a new value to a specific property of a selected object.
Object.propertyName = value
The left side of this assignment statement, Object.propertyName is a compound name identifying the
object and the property that is to be reset. The value on the right side of the statement gives the new
setting. When a program resets a property at runtime, the new setting overrides the value assigned at
design time. Design time settings need not be permanent during a program run.
Example: The following example illustrates how the Caption, MousePointer, WindowState, Height and
Width properties for a form object are set at runtime.
Private Sub Form_Load()
Forml.MousePointer = vbHourglass
Forml.Caption = “Simple Application”
Forml.WindowState = vbNormal
Forml.Width = 5000
Forml.Height = 5000
End Sub

1.3 Developing an Applications


An application can be created with the project. A project is a collect.ion of files that are used to
build an application. Writing a Visual Basic program involves the following two steps.
 Visual programming step
 Code programming step
Visual programming step involves designing an application with various tools that come along with the
Visual Basic package. Code programming step involves writing programs using a text editor. The
program window resembles as shown in the below figure comprising three CommandButton controls that
perform specific actions represented by their captions and an empty TextBox. The Display button displays
specified message and Clear button clears the message in the TextBox. The Exit button terminates the
application. Let us consider a simple display program using the TextBox control in this example.

A New Standard EXE Project item is selected from the File menu that displays a New Project
dialog box. The standard EXE is chosen for normal applications. Visual Basic responds by displaying the
Project and Form windows. Though no change have made to the Form, it is better to save the project at
the early stage of the design. When a project is saved, two files are saved, namely Project file and Form
file. The project file has .VBP extension and its contains information that VB uses for building the
project. The Form file contains information about from and has .FRM extension. The Save Project
command is selected from the File Menu. VB responds by displaying a Save File As dialog box. A file
name called Display.frm is given and Save button has to be clicked on. VB than display a Save Project As
dialog box. The project file is saved as Display.vbp.

Dept. of Computer Science, BCAS, Erode 6


Visual Programming – Unit I

Examining the Project Window


At this Stage, project consists of a single Form. In order to examine the Project window, Project
Explorer command is selected from the View menu. It displays the Project window with the Form.

Changing properties and Adding Controls


The next step is to add the controls and set their properties. The application is designed as per the
specifications given in the below Table.
Object Property Setting
Form Caption The Display Program
Name FrmDisplay
CommandButton Caption &Exit
Name cmdExit
CommandButton Caption &Clear
Name cmdCtear
CommandButton Caption &Display
TextBox Name Txt Display

Changing the Properties of Form


In order to change the property of the Form, click anywhere on it and press F4 or select Properties
window from the View menu. We can change the Caption and Name in the Properties window as given
in the above Table. The CommandButton control is added by double clicking it in the Toolbox, which
places it in the centre of the Form. It can then be dragged and dropped at the required location. It has a
caption Command1. Now the properties are set in the Properties window according to the specifications
given in the above Table. The same step is followed for the other controls. Property window displays the
properties alphabetically and in a categorized form with a description pane at the bottom.

Adding Code for the Program


The visual programming step is now completed and selecting Save Project command from the
File menu saves the work. The next step is the code programming step. Visual Basic code is written in the
Code window that consists of an Object box and Procedure list box. The Object box displays the name of
the selected object associated with the Form. The Procedure list box lists the procedures for an object such
as click, double-clicks, etc. An event procedure is written in the Code window that combines the control’s
name, which is listed in the ListBox, an underscore and the event name. The Code window is viewed by
selecting View Code from the Project window or by selecting Code from the View menu or
pressing F7.

Dept. of Computer Science, BCAS, Erode 7


Visual Programming – Unit I

Code editor window includes List Properties/Methods which presents a list of properties available
for controls.

The application is run by clicking Start command form the Run menu or Pressing F5. When the
Display button is clicked the message Visual Basic 6 is displayed in the TextBox. Clicking the Clear
button clears the message, while button terminates the application.

Creating an Executable File


We can create an executable file in Visual Basic by choosing Make EXE File command in the File
menu. A Make EXE dialog box appears. Now the file is saved as Display.exe in the required directory or
hard-disk and the OK button is clicked. As the application is converted into an executable file the user can
run it on any other Windows program.

Ending an Application
The End statement is used to terminate the execution of the application. It unloads all the forms
from memory.

1.4 Variables Data Types and Modules


Modules
Code in Visual Basic is stored in the form of module. The three kinds 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 duplication of Code, a separate module
containing a procedure is created that implements the common code. This is a Standard module.

Class modules (.CLS filename extension) are the foundation of object oriented programming in VB.
New objects can be created by writing code in class modules. Each module can contain:
 Declaration
May include constant, type, variable and DLL procedure declarations.
 Procedure
A sub function or property procedure that contains piece of code that can be executed as a unit

Data Types
By default Visual Basic variables are of the variant data type. 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 of data it can store. The fundamentals data types in VB including variant are
integer, long, single, double, string, currency, byte and Boolean. VB supports a vast array of data types.
Each data type has limits to the kind of information and minimum and maximum values it can hold.

Dept. of Computer Science, BCAS, Erode 8


Visual Programming – Unit I

Variables
Variables are used for storing values temporarily. A defined naming strategy has to be followed
while naming a variable. A variable name must begin with an alphabet letter and should not exceed 255
characters. It must be unique within the same scope. It should not contain any special characters such as
%, &, #, etc. There are ways of declaring variable in VB. Depending on where variable are declared and
how they are declared, user can determine how they can be used in the application. The different types of
declaring variables in VB are discussed below

Explicit Declaration
Declaring a Variable tells Visual Basic to reserve space in memory. It is not a 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, 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]
Example
Dim strname As String
Dim intCounter As Integer

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. Say, e.g. 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 = intcont + 1
This calculation will result in intcount yielding a value of 1 as intcont would have been initialized
to zero. This is because the intcount variable has been mistyped as intcont in the right hand side of the
second variable. But Visual Basic does not view this as a mistake and considers it to be a new variable
and hence gives a wrong result. To prevent errors of this nature, we can declare a variable by adding the
following statement to the general declaration section of the Form.
Option Explicit
This forces the user to declare the entire variable. The Option Explicit statement checks in the module for
usage of any undeclared variables and reports an error to the user. The Option Explicit statement can be
explicitly placed in the general declaration of each module using the following steps.
 Click Option item in the Tool Menus
 Click the Editor tab in the Options dialog box.
 Check Require Variable declaration option and then click the OK button.

Scope of Variables
A scope of variable to a procedure-level (local) or module-level variable depending on how it is
declared. The scope of variable, procedure or object determines which parts of the code in the application
are aware of the variable’s existence.

Dept. of Computer Science, BCAS, Erode 9


Visual Programming – Unit I

A variable is declared is general declaration section of a Form and hence is available to all the
procedure. 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 the procedures within
the same module or to all the procedures in an application, a variable is declared with border 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 statement
Dim intTemp As Integer
The local variables exist as long as the procedure in which they are declared, is executing. Once a
procedure is executed the value of its local variables are lost and 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 re-initialized each time Visual Basic invoke a procedure and thus retains or
preserves value even when a procedure ends. In case we need to keep track of the number of times a
CommandButton in an application is clicked, a static counter variable has to be declared. These static
variables are also ideal for making controls alternatively visible or invisible. A static variable is declared
as given below.
Static intPermanent As Integer
Variables have a lifetime in addition to scope. The values in 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 following procedure calculates the running total by adding new
values to the previous variable value.
Function RunningTotal()
Static Accumulate
Accumulate = Accumulate + num
RunningTotal = Accumulate
End Function
If the variable Accumulated was declared with Dim instead of Static, the previously accumulated values
would not be preserved across 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 heading in the statement below.
Static Function RunningTotal()

Module Level Variables


A module-level variable is available to all the procedures in the module. They are delcared using
the Public or the Private keyword.
Public 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 Private is
preferred because it makes the code easier to read. Pubic variable should not be declared within a
procedure. Public variable in different modules can share the same name and they can be differentiated in

Dept. of Computer Science, BCAS, Erode 10


Visual Programming – Unit I

code. For example, if the public integer variable intY is declared in both Forml and Modulel of a project
it can be referred as Fonnl.intY and Module1.intY.

Public vs Local Variables. A variable can have the same name and different scope. For example, we can
have 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 local variable and references to R outside the procedure
would access the public variable.

1.5 Procedure and Control Structures


Procedures
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. Following are the benefits of using procedures in programming.
 It is easier to debug 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 a Sub, Function or Property Procedure.

Sub Procedures
A sub procedure can be placed in standard, class and form module. 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 | Pub1ic] [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-general procedures and event procedures.

Event Procedures
An event procedure is a procedure block that contains the control’s name, an under score( _ ), and
the event name. The following syntax represents the event procedure for a Form_Load event.
Private Sub Form_Load( )
… Statement block …
End Sub
Event Procedures acquire the declaration 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 statement m a separate procedure (general procedure) and
then call them in the event procedure. In order to add a general procedure following steps are followed.
 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 as Add Procedure dialog box
 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.

Dept. of Computer Science, BCAS, Erode 11


Visual Programming – Unit I

 Under Scope, Public is selected to create a procedure that can be invoked 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 that 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 function returns a value that indicates the results of the tasks which are 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 result.
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 kinds of
property procedures - Property Let that sets the value of a property, Property Get procedure that returns
the value of a property and Property Set procedure that sets the reference to an object.

Control Structure
If...Then...Else Statement
The If…Then block is used for conditional execution of one or more statements.
If Condition Then
Statements
End If
The statement is executed only if the condition is true. The condition is usually a comparison, but it can
be any expression that evaluates a numeric value. If…Then-Else block is used to define several blocks of
statements, in order to execute one block. The following block of statement illustrates If...Else...End If
statements.
If A=l Then
Statements
Else
Statements
End if
The following example illustrates the If...Then ...Else statement.
Private Sub Commandl_Click()
If Val(Textl.Text) < 10 Then
MsgBox “It is a Single Digit Number"
Else lf Val(Text1.Text) < 100 Then

Dept. of Computer Science, BCAS, Erode 12


Visual Programming – Unit I

MsgBox "It is a Two Digit Number"


Else If Val(Text1.Text) < 1000 Then
MsgBox "It is a Three Digit Number"
Else
MsgBox "The Value is More Than Three Digits"
End If
End Sub
The program is executed by pressing F5. When a number is entered in the TextBox it displays a message
accordingly.

Select…Case Statement
Select...Case structure is an alternative to If…Then .... Elself for selectively executing a single
block of statements from among multiple blocks of statement. Select...Case is more convenient to use
than the If..Else..End If. The following program block illustrates the working of Select ... Case.
Select case Index
Case 0
Statements
Case 1
Statements
End select
Select…Case structure evaluates an expression once at the top of the structure, where as If..Then…Else If
structure evaluates different expressions for each Else If statement.

Do While Loop Statement


The Do While ....Loop is used to execute statements until a certain condition is met. The variable
counter is initialized to 1 and then Do While loop starts.
counter = 1
Do while counter < 101
counter = counter + 1
Loop

Do… Loop While Statement


The Do...Loop While statement, first executes the statements and, then tests the condition after the
execution.
counter = 200
Do
Text1.Text = Str(counter)
counter = counter + 1
Loop while counter < 501
The program executes the statements between Do and Loop While structure in any case. Then it
determines whether the counter is less than 501. If so, the program again executes the statements between
Do and Loop While else exits the loop.

Do…Loop Until Statement


The Do…Loop Until structure executes the statements until the condition is satisfied is false.
Private Sub Form_Load()
Do
name$ = InputBox(“Enter Name please…”)
Dept. of Computer Science, BCAS, Erode 13
Visual Programming – Unit I

msgbox name$
Loop Until name$ = “NIL”
End Sub
At the runtime it asks for the Name and until it is entered as “NIL” the loop remains infinite.

The For…Next Loop Statement


The For…Next Loop Statement is another way to make loops in Visual Basic. The following loop
counts from 1 to 50.
For I = 1 to 50 step 1
Text1.Text = Str(I)
Next
In order to count from 1 to 50 in steps of 2, the following loop can be used:
For I = 1 to 50 step 2
Text1.Text = Str(I)
Next

The Exit For and Exit Do Statement


A For…Next Loop can be terminated by an Exit For statement. Consider the following statement
block.
For I = 1 to 100
Text1.Text = Str(I)
If I = 50 then
Exit for
End If
Next
The preceding code increments the value of I by 1 until it reaches the condition I = 50. The Exit For
statement is executed and it terminates the For…Next Loop. The following statement block containing
Do..While loop using Exit Do statement.
I = 1
Do while I < 1001
Textl.Text = Str(I)
I = I + 2
If I > 500 then
Exit Do
End If
Loop

With - End With Statement


When properties are set for objects or methods are called, a lot of coding is included that acts on
the same object. It is easier to read the code by implementing the With-End With statement. Multiple
properties can be set and multiple methods can be called by using the With- End With statement. The
code is executed more quickly and efficiently as the object is evaluated only once. This concept can be
clearly understood with the following example.
with textprice
.Font.Size = 16
.Font.Italic = True
.Height = 235

Dept. of Computer Science, BCAS, Erode 14


Visual Programming – Unit I

.Text = "Welcome to Visual Basic 6.0"


End With
In the above coding, the object textprice, which is evaluated only once instead of every associated
property or method. This makes the coding simpler and efficient.

1.6 Arrays in Visual Basic


A sequence of variables by the same name can be referred using arrays. The individual elements
of an array are identified using an index. Arrays have upper and lower bounds and the elements have to lie
within these bounds. Each index number in an array is allocated individual memory space and hence users
must avoid declaring arrays of larger size than required. We can 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. Following are the two types of arrays in VB:
 Fixed-size array The size of array always remains the same.
 Dynamic array The size of can be changed at runtime.

Fixed Size Array


Fixed arrays can be declared by giving a name to the array with the upper limit in the parentheses.
The upper limit should always be within the range of Long data type. Declaring fixed arrays in difference
cases are given below. Array declaration in the General Declaration section of a module or a procedure is
as shown in this example.
Dim lengths(9) As Integer
In the above illustration, lengths is the name of the array and the number 9 included in the parentheses is
the upper limit of the array. The above declaration creates an array with 10 elements, with index running
from 0 to 9.

If we want to specify the lower limit, then the parenthesis should include both the lower and upper
limit along with the To keyword. An example for this is given below.
Dim lengths(1 To 10) As Integer
In the above statement, an array of 10 elements is declared but with indexes running from 1 to 10. A
public array can be created using the keyword Public instead of Dim as shown below:
Public digits(20) As Integer

Multidimensional Arrays
A multidimensional array is used when we need to represent or store information of different
dimension. For example to hold the student registration number and marks of the student, we need to
mention its x and y co-ordinates. The following statement declares a two-dimensional 50 by 50 array
within the procedure.
Dim Marks(50,50)
It is also possible to define explicit lower limits for one or both the dimensions as for fixed size arrays.
An example for this is given here.
Dim StudMarks(101 to 200, 1 to 100)
Any number of dimensions can he declared in a multidimensional array. An example for a three
dimensional array with defined lower limits is given below.
Dim StudDetails(101 To 200,1 To 100,1 To 100)

Dept. of Computer Science, BCAS, Erode 15


Visual Programming – Unit I

Dynamic Array
There will be a situation when the user may not know the exact size of the array at design time.
Under such circumstances, a dynamic array can be initially declared and the user can then add elements
when needed instead of declaring the size of the array at design time.
Dim NewArray()
The actual number of elements can be allocated using a ReDim statement. This example allocates the
number of elements in the array based on the value of the variable Y.
ReDim NewArray(Y + 1)
The ReDim statement can appear only in a procedure, which is an executable statement. The same way of
declaration as used for fixed arrays is used for declaring ReDim statement also. ReDim is an executable
statement. The lower and upper limits for each dimension can also be specified explicitly as in a fixed size
array. An example for this is given below
ReDim FirstArray(4 to 12)
Each time on executing the ReDim statement, the current data stored in the array is lost and the default
value is set. But if we want to change the size of the array without losing the previous data, we have use
the preserve keyword with the ReDim statement. This is shown in the example given below.
ReDim Preserve NewArray(Ubound(FirstArray)+1)
When the Preserve keyword is used, only the upper limits of the last dimension in a multi dimensional
array can be changed. No other dimensions or the lower limit of the last dimension can be changed.

User-Defined data types


Variables of different data types when combined as a single variable to hold several related
information’s is called a User-Defined data type. A Type statement is used to define a user-defined type in
the General declaration section of a form or module. User defined data types can only be private in form
while standard modules they can be public or private. An example for a user defined data type to hold the
product details is as given below.
Private Type ProductDetails
Prodld As String
ProdName As String
Price As Currency
End Type

The user defined data type can be declared with a variable using the Dim statement as in any other
variable declaration statement. An array on these user-defined data types can also be declared. An
example to consolidate these two features is given below.
Dim Electronicgoods As ProductDetails ‘ One record
Dim Electronicgoods(lO) As ProductDetails ‘ An array of 11 record
A User-defined type can be referenced in an application by using the variable name in the
procedure along with the item name in the Type block. Say, for example if the text property of a textbox
namely text1 is to be assigned the name of an electronic item is written as given below.
Textl.text = Electronicgoods.prodname
If the same is implemented as an array, then the statement changes to the following.
Textl.text = Electronicgoods(i).prodname
Here i is the index of the array. User defined types can also be passed to procedures to allow many related
items as one argument.
Sub ProdData(Electronicgoods As ProductDetails)
Textl.text = Electronicgoods.prodname

Dept. of Computer Science, BCAS, Erode 16


Visual Programming – Unit I

Text2.text = Electronicgoods.price
End sub

Constants
Constants are named storage locations in memory, the value of which does not change during
program execution. They remain the same throughout the program execution. When the user wants to use
a value that never changes, a constant can be declared and created. The Const statement is used to create
a constant. Constants can be declared in local, form, module or global scope and can be public or private
as for variables. Constants can be declared as illustrated below.
Public Const gravityconstant As Single = 9.81

Predefined Visual Basic Constants


The predefined constants can be used anywhere in the code in place of the actual numeric values.
This makes the code easier to be read or write. For example consider a statement that will set the window
state of a form to be maximized.
Form1.Windowstate = 2
The same task can be performed using a Visual Basic constant.
Forml.WindowState=vbMaximised

Data Type Conversion


Visual Basic functions either to convert a string into an integer or vice versa and many more
conversion functions. A complete listing of all conversion functions offered by Visual Basic is listed
below
Conversion To Function
Boolean Cbool
Byte Cbyte
Currency Ccur
Date Cdate
Decimals Cdec
Double CDbl
Integer Cint
Long CLng
Single CSng
String CStr
Variant CVar
Error CVErr
A conversion function should always be placed at the right hand side of the calculation statement.

Visual Basic Built-in Functions


Many built-in functions are offered by VB that fall under various categories. These functions are
procedures that return a value.
 Date and Time Functions
 Format Function
 String Functions
Date and Time Functions
Date and time are internally stored as numbers in VB. The Whole number portion of the number
represents the date between 1st January, 100 and December 31, 1999 inclusive. The decimal portion

Dept. of Computer Science, BCAS, Erode 17


Visual Programming – Unit I

represents the time between 0:00:00 and 29:59:59 hours inclusive. The system's current date and time can
be retrieved using the Now, Date and Time functions in VB, The Now function retrieves the date and
time, While Date function retrieves only date and Time function only retrieves the time. To display both
the date and time together a message box is displayed using the statement given below.
MsgBox "The current date and time of the system is" & Now
Here ‘&’ is used as a concatenation operator to concatenate the string and the Now function. Selective
portions of the date and time value can be extracted using following functions given in the below.
Function Extracted Portion
Year() Year(Now)
Month() Month(Now)
Day() Day(Now)
WeekDay() WeekDay(Now)
Hour() Hour(Now)
Minute() Minute(Now)
Second() Second(Now)
The calculation and conversion functions related to data and time are listed below
Function Description
DateAdd( ) Returns a date to which a specific interval has been added
DateDiff( ) Returns a Long data type value specifying the interval between the two values
DatePart( ) Returns an Integer containing a specified part of a given date.
DateValue( ) Converts a string to a date.
TimeValue( ) Converts a string to a time.
DateSerial( ) Returns a date for a specified year, month and day.

DateDiff Function
The DateDiff function returns the interval between two dates in terms of years, months or days.
The syntax for this given below
DateDiff(interval, date1, date2 [,firstdayofweek[,firstdayofweek]])

Format Function
The format function accepts a numeric value and converts it to a string in the format specified by the format
argument. The syntax is given below
Format(expression[, format [,firstdayofweek[,firstdayofweek]]])
The Format function syntax with various parts are listed below
Part Expression format
Expression Required any valid expression
format Optional. A valid named or user-defined format expression
firstdayofweek Optional. A constant that specifies the first day of the week
firstweekofyear Optional. A constant that specifies the first week of the year

Comparison and Relational Operators


There are six relational operators used in testing expressions. They are < (less than), <= (leass or
equal to), > (greater than), >= (greater or equal to) and = (Equal to) and <> (Not Equal to). When two
expressions are compared, it returns either True or False. True or False are Boolean values, with 0 for
Fa1se and 1 for True.

Dept. of Computer Science, BCAS, Erode 18


Visual Programming – Unit I

Logical Operators
There are six logical operators. The most common operators are And, Or and Not operators. And
Xor, Equ and Imp operators are advanced operators.
Operator Functions
And Combines two expressions. Both the expression must be True for the entire expression
to be True
Or Combines two expressions. If one of the expression is True for the entire expression is
True
Not The Negative of single expression
Xor Combines two expressions. The entire expression consider to be True if the two
expression are not both True or False
Equ Combines two expressions. Both expression must be True or False for the entire
expression to be True
Imp Combines two expretyg rssions. The entire expression is True except when first
expression is True and the second expression is False

Test Strings
VB string functions can manipulate strings in applications. Below table given brief description
about the string functions in VB.
Function Name Purpose
StrComp( ) Compare two strings
Format, Lcase( ) Converts the string to lowercase
Format, Ucase( ) Converts the string to uppercase
Space, String( ) Creates a string of repeating character
Len( ) Finds the length of a string
Format( ) Format a string
Lset( ), Rset( ) Justify a string
Instr( ) Returns a Variant(Long) specifying the position of the
first occurrence of one string within another
Left( ) Returns a Variant(String) containing a specified number
of characters from the left side of the string
Mid( ) Returns a Variant(String) containing a specified number
of characters from a string
Right( ) Returns a Variant(String) containing a specified number
of characters from the right side of the string
Trim( ) Returns a Variant (String) containing a copy of a
specified string without leading spaces and trailing
spaces.
Ltrim( ) Returns a Variant (String) containing a copy of a
specified string without leading spaces.
Rtrim( ) Returns a Variant (String) containing a copy of a
specified string without trailing spaces.
StrConv( ) Converts the strings

**********

Dept. of Computer Science, BCAS, Erode 19


Visual Programming – Unit I

2. Working with Controls


2.1 Creating and using Controls
A control is an object be drawn on a Form object to enable or enhance user interaction with an
application controls have properties that define aspects of their appearance, such as position, size and
colour and aspects of their behaviour, such as their response to the user input. They can respond to events
initiated by the user or triggered by the system. For example, a code could be written in a Command
Button control's Click event procedure that would load a file or display result.

In addition to properties and events, methods can also be used to manipulate controls from code.
For example, 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 OptionButton or CheckBox controls, ListBox
entries or ScrollBars to select a value.

Classification of Controls
Visual Basic controls are broadly classified as standard controls, ActiveX controls and insertable
objects. Standard controls such as CommandButton, Label and Frame controls are contained inside a
.EXE file and are always included in the 'l'oolbox which cannot removed. ActiveX controls exist as
separate files with .VBX or .OCX extension. They include specialized controls such as
 MSChart Control
 The Communicating Control
 The Animation control
 The List View control
 An ImageList control
 The Multimedia control
 The Internet Transfer control
 A WinSock control
 The Tree View control
 The Syslnfo Control
 The Picture Clip control
These built-in ActiveX controls will be discussed at length in Chapter 14. Some of these objects support
OLE automation, which allow programming another application object from within Visual Basic
application.

Tablndex Property of Controls


Visual Basic uses the Tablndex property to determine the control that would receive the focus next
when a Tab key is pressed. Every time a Tab key is pressed, VB looks at the value of Tablndex for the
control that currently has focus and then it scan through the controls searching for the next highest
Tabludex number. If this new control can accept the keyboard focus, the focus moves to the control.
Otherwise, it looks for the next control with next higher Tablndex value. 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 ot more that can accept keyboard input.

By default, Visual Basic assigns a tab order to controls as we draw them on a form, with the
exception of the Menu, Timer. Data, Image, Line and Shape controls which are not included in the tab
order. At run time, invisible or disabled controls and controls that cannot receive the focus (Frame and

Dept. of Computer Science, BCAS, Erode 20


Visual Programming – Unit I

Label controls) remain in the tab but are skipped during tabbing. Setting the TabIndex property of
controls is a must in development environment.

Each new control is placed last in the tab order. If we change the value of a control's
Tablndex property to adjust the default tab order, VB automatically re-numbers the TabIndex of other
controls to reflect insertion and deletions. We can make changes at the design time using the Properties
window or at run time in code.

Using Text Box Control


A TextBox control sometimes called an edit field or edits control, display information entered at
design time. This could be entered by the user or assigned to the control in code at run time.

Setting Properties to a Text Box


 Text can be entered into the text box by assigning the necessary string to the text property of the
control
 If the user is interested in displaying multiple line of text in a TextBox control, he has to set the
MultiLine property to True. If a multiple-line Textbox does not have a horizontal ScrollBar, text
wraps automatically even when the Textbox is resized.
 In order to customize the scroll bar combination on a TextBox, set the ScrollBars property.
 ScrollBars will always appear on the TextBox when its Multiline property is set to True and its
ScrollBars property is set to anything except None (0).
 If the user sets MultiLine property to True, he can use the Alignment property to set the alignment
of text within the TextBox. The text is left-justified by default. If the MultiLine property is False,
setting the Alignment property has no effect.
 A TextBox control can also act as a destination link in a DDE conversation.
 In order to work with the part of a text in a TextBox, the text can be selected using the following three
properties.
 SelLength Returns or sets the number of characters selected.
 SelStart Returns or sets the starting point of selected text. when no text is selected, SelStart indicates
the position of the insertion point.
 SelText Returns or sets the string containing the currently selected text. If no text is selected, SelText
consists of a zero-length string.
 The selected text can be copied to the Clipboard by using SelText in the following form
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.
 VbCFLink - conversation information
 VbCPRTF - Rich Text Format
 VbCFText – Text
We can get the text from the clipboard using the GetText( ) function in the following way.
Clipboard.GetExt([format])

Using a label Control


A Label control is a graphical control you can use to display text that a user can’t change directly.

Properties of a Label control

Dept. of Computer Science, BCAS, Erode 21


Visual Programming – Unit I

 We can write code that changes the caption property displayed by a Label control in response to
events at run time. We can also use a Label to identify the control, such as TextBox control, that
doesn't have its own Caption property.
 The AutoSize and WordWrap properties should be set if users wants the Label to properly display
variable-length lines or varying numbers of lines.
 A Label control can also act as a destination in a DDEconversation. Set the LinkTopic property to
establish a link, set the LinkItem property to specify an item for the conversation, and set the
LinkMode property to activate the link. When these properties have been set, VB attempts to initiate
the conversation and displays a message if it’s unable to do so.
 Set the UseMnemonic property to True if you want to define a character in the Caption property of
the Label as an access key

Using a Command button


A Command Button control is used to begin interrupt or end a process. When chosen, a
CommandButton appears pushed in and so is sometimes called a push button.

Properties of a Command Button Control


 To display text on a CommandButton control, set its Caption property.
 An event can be activated by clicking a command button.
 A button's background colour can be set by setting the Backcolour property to the desired choice.
 The text colour of a command button can be set using the Forecolour property.
 The Font of a command button can be selected by setting the Font property in the Font dialog box to
the desired one.
 The buttons can be enabled or disabled by setting the Enabled property to True or False respectively.
 Also the buttons can be made visible or invisible at run time using the Visible property.
 Tooltips can be added to a button by setting a text to the Tooltip property of the command button.
 A button click event is triggered or fired the following Code is entered in the General Declarations
Private Sub Commandl_Click( )
......
End Sub

Using OptionButton Control


OptionButton provides a set of choices from which a user can select only one button by
 Clicking it at run time.
 Assigning the value property t o True in code like Option1.Value=True
 Using the shortcut keys specified in the Caption of a Label.
To disable an OptionButton at run time, its Enabled propert y is set to False. Let us develop a
number system application that illustrates the operation of the OptionButton control. The program
contains Label, TextBox, CommandButton and three OptionButton controls.

Example
 A new Standard EXE project is opened and the Form and the project is saved as Option. frm and
Option.vbp respectively.
 The Form is designed as per the following specifications table. The design Form appears as shown
below Figure.

Dept. of Computer Science, BCAS, Erode 22


Visual Programming – Unit I

Object Properties Setting


Label Caption Enter a Number
Name Label 1
TextBox Text (Empty)
Name Text 1
CommandButton Caption &Close
Name Command 1
OptionButton Caption &Octal
Name optOct
OptionButton Caption &Hexadecimal
Name optHex
OptionButton Caption &Decimal
Name optDec
The application responds to the following events
 The change events of the TextBox read the value and store it in a form-level numeric variable as
currentval.
 The click event of optOct button returns currentvalin octal.
 The click event of optHexa button returns currentvalin hexadecimal.
 The click event of optDec button returns currentvalin decimal.
The following code is entered in the general declarations section of the Form.
Dim currentval as variant
The variable is initialised 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 Textl_Change()
If optOct.Value = True Then
currentval = Val("&0" & LTrim(Textl.Text) & "&")
Elseif optDec.value = True then
currentval = Val(Ltrim(textl.text) & "&")
Else
Currentval = Val("&H" & LTrim(Textl.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 event of the OptionButton controls.
Private Sub optOct_Click()
Textl.Text = Oct(currentval)
Dept. of Computer Science, BCAS, Erode 23
Visual Programming – Unit I

End Sub
Private Sub optHex_Click()
Textl.Text = Hex(currentval)
End Sub

Private Sub optDec_Click()


Textl.Text = Format(currentval)
End Sub
The following code is entered in-the click event of the Close button.
Prlvate Sub cmdclose_Click()
Unload Me
End Sub

Using ListBox and ComboBox Controls


ListBox and ComhoBox controls present a set of choice that is displayed vertically in a single
column. If the number of items exceeds the value that can be displayed, scroll bar will automatically
appear on the control. These scroll bars can be scrolled up and down or left to right through the list.

Adding Items to Lists


It is possible to populate the list at design or at run time.
Deign Time - To add items to list at design time, click List in the property box and then add the items.
Press CTRL+ENTER after adding each item.
Run time - The AddItem method is us to add items to a list at run lime. The AddItem method uses the
following syntax.
Object.Addltem item, index
The item argument is string that represents the text to be added to the list.
The index argument is an integer that indicates where in the list to add the new item.

Removing Items from a List


The RemoveItem method is used to remove an item from list. The syntax for this is given below.
Object.RemoveItem index
The following code verifies an item which is selected in the list and then removes the selected item.
Private Sub cmdRemovelistltem_Click()
If Mylist.Listlndex > -1 Then
MyList.removeItem MyList.ListIndex
End if
End Sub
An error occurs if you attempt to use RemoveItem when no items are selected.

Selecting an item from a List Box


To access items in a list box, we use the ListIndex and List properties. The ListIndex property sets
the index number of the currently selected item. The first item in the list in index number is 0. The
ListIndex retirns -1 if no item is selected. The ListCount property is always one more than the index of the
last item in the list. The NewIndex property returns the index of the last item added to the list. The
following example adds an item to the list box and sets the new item as current selection.
List1.AddItem = “Television”
List1.ListIndex = List1.NewIndex

Dept. of Computer Science, BCAS, Erode 24


Visual Programming – Unit I

The List property sets or returns that text of an item in a list box. The index number is passed to the list
property to specify the item to be accessed. To return the text of the selected item, the ListIndex property
is passed as shown in the following example:
Str = MyList.List(MyList.ListIndex)
To return the string for a ListBox, the Text property of the control is used as shown in the following
example:
Str = cmbList1.Text

Sorting the List


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

Using the ComboBox


A ComboBox combines the features of TextBox and a ListBox. This control 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.
 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 ComboBox 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 ScrollBar is displayed beside the
list if there are too many items to be displayed in the list box area.

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 Drop-down list combo box turns the combo box into a drop-down list box. At run time, the
control looks like the drop-down combo box. The user could click the down arrow to view the list. The
difference between Dropdown combo and Drop-down list combo is that the edit area in the dropdown list
is disabled. The user can select only one of the list items and cannot type an item in the edit area. This
area, however, does display the item currently selected in the list.

Generally the ComboBox is preferred when there is a list of choices. It saves space on a Form. The
full list is not displayed until the user clicks the down arrow (except for style 1). An illustration of
different types of combo boxes is shown in below figure.

Dept. of Computer Science, BCAS, Erode 25


Visual Programming – Unit I

The AddItem method is used to add values to the ComboBox and ListBox. Similarly the
RemoveItem method is used to remove items from the ListBox or ComboBox. Let us now develop a
small application that uses AddItem, RemoveItem and Clear methods. The application contains a
TextBox, ListBox and three Label and CommandButton controls as shown in below figure. It is designed
in name in the TextBox. When the Add button is clicked, the types name is added in the ListBox. A
particular entry in the ListBox can be removed by selecting the item and choosing the Remove button.
Example
For the supermarket SM & Co. develop an application to Add, Remove, Clear the list of items and
then finally close the application.

Object Properties Setting


Form Caption List Box Application
Name Form1
TextBox Name Text 1
Text (Empty)
Label Name Label1
Caption Enter a Name
ListBox Name List1
Sorted True
Label Name Label2
Caption #Clients
Label Name Label3
Caption (Empty)
Border style 1-Fixed Single
CommandButton Caption &Add
Name cmdAdd
Enabled False
CommandButton Caption &AddRemove
Name cmdRemove
CommandButton Caption &Clear
Name cmdClear
CommandButton Caption E&ixt
Name cmdExit

Following event procedure are added for the TextBox, CommandButton and ListBox controls.
Private Sub Text1_Change()
cmdAdd.Enabled = (Len(Text1.Text) > 0)
End Sub

Dept. of Computer Science, BCAS, Erode 26


Visual Programming – Unit I

Private Sub cmdAdd_Click()


List1.AddItem Text1.Text
Text1.Text = ““
Text1.SetFoucs
Label3.Caption = List1.ListCount
End Sub
The click event of the Add buttons adds the text into the list box that was types in the TextBox. It
then clears the TextBox. The value of the Label which shows the number of ListBox items immediately
incremented. The focus is again set back to the TextBox for adding the item.
Private Sub cmdRemove_Click()
Dim Ind As Integer
Ind = List1.ListIndex
If Ind >= 0 then
List1.RemoveItem Ind
Label3.Caption = List1.ListCount
End If
cmdRemove.Enabled = (List1.ListIndex <> -1)
End Sub
The code written in the Remove button removes the selected items from the ListBox. If none of
items in the ListBox are selected, the Remove command is disabled. The number of items in the list box is
decremented by 1 and value is displayed in Label.
Private Sub cmdClear_Click()
List1.Clear
cmdRemove.Enabled = False
Label3.Caption = List1.ListCount
End Sub
The code in the clear button clears all the items in the ListBox. Then it disables the remove
CommandButton and the Label that displays the list items becomes zero.
Private Sub cmdExit_Click()
Unload Me
End Sub
Private Sub List1_Click()
cmdRemove.Enabled = (List1.ListIndex <> -1)
End Sub
We can have multiple column and multiple selection ListBox by setting both the Columns and
MultiSelect properties of the ListBox.

Using ScrollBar control


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. 'I'he Min and Max property represents the minimum
and maximum value. The Value property of the scroll bar represents its current value, which may be any
integer between minimum and maximum value. Let us develop a small program that illustrates the
ScrollBur control.
Example
For the supermarket SM&Co. we need to develop an application where the ScrollBar is used to
indicate the weights in grams. A standard Exe project is opened and saved. The Form is designed as

Dept. of Computer Science, BCAS, Erode 27


Visual Programming – Unit I

shown below where thumb of the ScrollBar is positioned at the centre. When the thumb’s position is
changed, it should in the TextBox.

The Form is designed as per the below specifications


Object Properties Setting
Form Caption Weight Program
Name Form1
TextBox Name Text 1
Text Gms
CommandButton Caption Exit
Name Command1
HScrollBar Max 100
Min 0
Name HScroll1
Value 50
The following code is entered in the HScroll_Change( ) procedure
Private Sub HScroll_Change()
Text1.Text = HScroll1.Value & “gms”
End Sub
The following code is entered in the Command1_Click() procedure.
Private Sub Command1_Click()
End
End Sub
The project is saved and the application is run by pressing F5. By changing the position of
HScrollBar, we can find the change in the speed in the TextBox.

2.2 Working with ControlArrays


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

Creating Control Arrays at Design time


There are three ways to create a control array at design time.
 Assigning the same in the Name property for more than one control.
 Copying an existing control and then pasting it into the Form. This can be done by focusing the
control and choosing the Copy from Edit menu and then choosing the Paste option from Edit menu.
 Setting the Index property to a value that is not null.

Dept. of Computer Science, BCAS, Erode 28


Visual Programming – Unit I

Adding a Control Array at Run Time


Control arrays can be created at run time using the following statements.
 Load object (index %)
 Unload object (index %)
Where object is the name of the control which is to be added or deleted 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
created at design time with an index value of 0. When a new element of control array is loaded, most of the
property settings are copied from the lowest exiting element in the array.

Control Array Application


The application use a set of CommandButton controls in an array to illustrate the working of a
Calculator.
Example
A standard EXE form is created and saved. The form is designed as per the following below
specifications.
Object Properties Setting
CommandButton Name Cmd
Caption 0
Index 1
CommandButton Name Cmd
Caption 2
Index 1
CommandButton Name Cmd
Caption 3
Index 2
CommandButton Name Cmd
Caption 4
Index 3
CommandButton Name Cmd
Caption 5
Index 4
CommandButton Name Cmd
Caption 6
Index 5
CommandButton Name Cmd
Caption 7
Index 6
CommandButton Name Cmd
Caption 8
Index 7
CommandButton Name Cmd
Caption 9
Index 8
CommandButton Name Cmd
Caption 0
Index 9

Dept. of Computer Science, BCAS, Erode 29


Visual Programming – Unit I

CommandButton Name Cmd


Caption .
Index 10
Text box Name Text1
Alignment Right Justify
CommandButton Name CmdAC
Caption AC
In addition to these controls, six command button controls are added and they are named as CmdPlus,
CmdMinus, CmdDiv, CmdMul, CmdNegtive and Cmd Equal with their caption +, -, /, *, +/- ,=,
respectively. The following variables are declared in the general declarations of the form.
Public curval As Double
Public preval As Double
Public choice As String
Public result As Double
The following code is entered in the cmd_Click( ) (Control Array) event procedure.
Private Sub cmd_Click(Index As Ingeter)
Text1.Text = Text1.Text & cmd(Index).Caption
curval = Val(Text1.Text)
End Sub
In the cmdAC_Click( ) procedure, the following code is entered.
Private Sub cmdAC_Click()
curval = preval = 0
Text1.Text = “”
End Sub
The following code is written in the CmdNegtive_Click( ) procedure
Private Sub CmdNegtive_Click()
curval = - curval
Text1.Text = Val(curval)
End Sub
The following code is entered in the click events of the cmdPlus, cmdMinus, cmdMul, cmdDiv control
respectively.
Private Sub cmdPlus_Click()
Text1.Text = “”
preval = curval
curval = 0
choice = “+”
End Sub
Private Sub cmdMinus_Click()
Text1.Text = “”
preval = curval
curval = 0
choice = “-”
End Sub
Private Sub cmdMul_Click()
Text1.Text = “”
preval = curval
curval = 0

Dept. of Computer Science, BCAS, Erode 30


Visual Programming – Unit I

choice = “*”
End Sub
Private Sub cmdDiv_Click()
Text1.Text = “”
preval = curval
curval = 0
choice = “/”
End Sub
To print the result on the TextBox, the following code is entered in the cmdEqual_Click( ) event
procedure.
Private Sub Command2_Click()
Select Case choice
Case "+"
result = preval + curval
Text1.Text = Str(result)
Case "-"
result = preval - curval
Text1.Text = Str(result)
Case "*"
result = preval * curval
Text1.Text = Str(result)
Case "/"
result = preval / curval
Text1.Text = Str(result)
End Select
curval = result
End Sub

Save and Run the project. On clicking digits of user ‘s choice and an operator button, the output appears
as shown below:

***** End of Unit I ****

Dept. of Computer Science, BCAS, Erode 31

You might also like