Core 9: Visual Programming E-Content Unit - 1 1.1 Getting Started With VB6
Core 9: Visual Programming E-Content Unit - 1 1.1 Getting Started With VB6
Core 9: Visual Programming E-Content Unit - 1 1.1 Getting Started With VB6
E-Content
Unit - 1
VISUAL BASIC is a high-level programming language that evolved from the earlier DOS
version called BASIC. BASIC means Beginners' All-purpose Symbolic Instruction Code. The
code looks a lot like the English Language. Now, there are many versions of Visual Basic
available in the market, the latest being Visual Basic 2017 that is bundled with other
programming languages such as C#. However, the most popular one and still widely used by
many VB programmers is none other than Visual Basic 6.
In addition, Visual Basic 6 is Event-driven because we need to write code that performs some
tasks in response to certain events. The events usually comprise but not limited to the user's
inputs. Some of the events are load, click, double click, drag, and drop, pressing the keys and
more. We will learn more about events in later lessons. Besides that, a VB6 Program is made up
of many subprograms or modules, each has its own program code, and each can be executed
independently; they can also be linked together in one way or another.
Programming Environment
Before you can write programs in VB 6, you need to install Visual Basic 6 compiler on your
computer. You can purchase a copy of Microsoft Visual Basic 6.0 Learning Edition
or Microsoft Visual Basic Professional Edition from Amazon.com, both are vb6 compilers.
Besides, you can also buy it from eBay at Microsoft Visual Basic 6.0 6 Professional PRO MSDN
Library Manual Service Pack. If you have already installed Microsoft Office in your PC or
laptop, you can also use the built-in Visual Basic Application in Excel to start creating Visual
Basic programs without having to spend extra cash to buy the VB6 compiler.
You can also install VB6 on Windows 10 but you need to follow certain steps otherwise the
installation will fail. First, you need to run setup as administrator. Next, you need to use custom
installation. Clear the checkbox for Data Access. If you don't, set up will hang at the end of the
installation. Finally, click next and wait for the installation to complete. For complete
instructions, please follow this link Install VB6 on Windows 10
After installing the vb6 compiler, the icon will appear on your desktop or in your programs
menu. Click on the icon to launch the VB6 compiler. On start up, Visual Basic 6.0 will display
the following dialog box as shown in Figure 1.1.
You can choose to either start a new project, open an existing project or select a list of recently
opened programs. A project is a collection of files that make up your application. There are
various types of applications that we could create, however, we shall concentrate on creating
Standard EXE programs (EXE means executable). Before you begin, you must think of an
application that preferably have commercial ,educational or recreational value. Next, click on the
Standard EXE icon to go into the actual Visual Basic 6 programming environment.
When you start a new Visual Basic 6 Standard EXE project, you will be presented with the
Visual Basic 6 Integrated Development Environment (IDE). 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 Form is the primary building block of a Visual Basic 6 application. A Visual Basic 6
application can actually comprise many forms, but we shall focus on developing an application
with one form first. We will learn how to develop applications with multiple forms later. Before
you proceed to build the application, it is a good practice to save the project first. You can save
the project by selecting Save Project from the File menu, assign a name to your project and save
it in a certain folder. You shall now proceed to learn Visual Basic programming from the next
lesson onwards.
Working with 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
Load FormName
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. You have to call the Form's Show method to display it on the desktop.
* 0-Modeless (default)
* 1-Modal
Modeless Forms are the normal Forms. Modeless Forms interact with the user and the user
allowed to switch to any other Form of the application. If you do not specify the optional mode
argument, by default the mode is set to modeless.
The 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. A modal Form, thus, must have a Close
button or some means to close the Form in order to return to the Form where the Modal Form
was loaded.
Hiding Forms
The Hide method is used to hide a Form. The following is the syntax of the Hide Method.
FormName.Hide
To hide a Form from within its own code, the following code can be used.
Me.Hide
You must understand that the 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, you can
still access its properties and code. For instance, you 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
The following code is typed in the Click event of the command buttons
Run the application. Clicking on the buttons will display the Forms respectively. But you can see
that in the cmd2_Click( ) event additionally VbModal argument has been added. You can see the
difference after you display the forms by clicking on the command buttons. You can notice that
you cannot switch to any other Forms in the application unless you close the Form3
Finding out the difference between Unload and Hide method
To know what the difference is between Unload and Hide methods we will do an example. Open
a new project and save the project. Draw two buttons on the form and name those as shown
above.
Developing an application
To start writing an event procedure, you need to double-click an object. For example, if you want
to write an event procedure for clicking a command button, you double-click the command
button and an event procedure will appear in the code window,The structure is as follows:
End Sub
After declaring various variables using the Dim statements, we can assign values to those
variables. The syntax of an assignment is
Variable=Expression
The variable can be a declared variable or a control property value. The expression could be a
mathematical expression, a number, a string, a Boolean value (true or false) and more.
firstNumber=100
secondNumber=firstNumber-99
userName="John Lyan"
userpass.Text = password
Label1.Visible = True
Command1.Visible = false
Label4.Caption = textbox1.Text
ThirdNumber = Val(usernum1.Text)
X = (3.14159 / 180) * A
To compute inputs from users and to generate results, we need to use various mathematical
operators. In Visual Basic, except for + and -, the symbols for the operators are different from
normal mathematical operators, as shown in Table 6.1.
^ Exponential 2^4=16
* Multiplication 4*3=12,
/ Division 12/4=3
"Visual"&"Basic"="Visual
+ or & String concatenation
Basic"
Example
firstName = Text1.Text
secondName = Text2.Text
yourName = secondName +"" + firstName
Label1.Caption = yourName
End Sub
There are many types of data that we come across in our daily life. For example, we need to
handle data such as names, addresses, money, date, stock quotes, statistics and more every day.
Similarly, in Visual Basic, we have to deal with all sorts of data, some can be mathematically
calculated while some are in the form text or other forms. VB divides data into different types so
that they are easier to manage when we need to write the code involving those data.
Visual Basic classifies the information mentioned above into two major data types, they are the
numeric data types and the non-numeric data types.
Numeric data types are types of data that consist of numbers that can be computed
mathematically with standard operators. Examples of numeric data types are height, weight,
share values, the price of goods, monthly bills, fees and others. In Visual Basic, numeric data are
divided into 7 types, depending on the range of values they can store. Calculations that only
involve round figures can use Integer or Long integer in the computation. Programs that require
high precision calculation need to use Single and Double decision data types, they are also called
floating point numbers. For currency calculation , you can use the currency data types. Lastly, if
even more precision is required to perform calculations that involve many decimal points, we
can use the decimal data types. These data types summarized in Table 5.1
Nonnumeric data types are data that cannot be manipulated mathematically. Non-numeric data
comprises string data types, date data types, boolean data types that store only two values (true or
false), object data type and Variant data type .They are summarized in Table 5.2
Literals are values that you assign to data. In some cases, we need to add a suffix behind a literal
so that VB can handle the calculation more accurately. For example, we can use num=1.3089#
for a Double type data. Some of the suffixes are displayed in Table 5.3.
Table 5.3
& Long
! Single
# Double
@ Currency
In addition, we need to enclose string literals within two quotations and date and time literals
within two # sign. Strings can contain any characters, including numbers. The following are few
examples:
memberName="Turban, John."
TelNumber="1800-900-888-777"
LastDay=#31-Dec-00#
ExpTime=#12:00 am#
Managing Variables
Variables are like mail boxes in the post office. The contents of the variables changes every now
and then, just like the mail boxes. In term of VB, variables are areas allocated by the computer
memory to hold data. Like the mail boxes, each variable must be given a name. To name a
variable in Visual Basic, you have to follow a set of rules. All modern programming languages
such as PHP (PHP runs on hosts like iPage - see hosting review) allow us developers to use
variables to store and retrieve data. Each language has its own special syntax to learn.
Variable Names
The following are the rules when naming the variables in Visual Basic
Examples of valid and invalid variable names are displayed in Table 5.4
My_Car My.Car
ThisYear 1NewBoy
In Visual Basic, it is a good practice to declare the variables before using them by assigning
names and data types. They are normally declared in the general section of the codes' windows
using the Dim statement. You can use any variable to hold any data , but different types of
variables are designed to work efficiently with different data types .
The syantax is as follows:
If you want to declare more variables, you can declare them in separate lines or you may also
combine more in one line , separating each variable with a comma, as follows:
Example 5.1
Dim password As String
Dim yourName As String
Dim firstnum As Integer
Dim secondnum As Integer
Dim total As Integer
Dim doDate As Date
Dim password As String, yourName As String, firstnum As Integer
Unlike other programming languages, Visual Basic actually doesn't require you to specifically
declare a variable before it's used. If a variable isn't declared, VB willautomatically declare the
variable as a Variant. A variant is data type that can hold any type of data.
For string declaration, there are two possible types, one for the variable-length string and another
for the fixed-length string. For the variable-length string, just use the same format as example 5.1
above. However, for the fixed-length string, you have to use the format as shown below:
Dim VariableName as String * n, where n defines the number of characters the string can hold.
Example 5.2:
Dim yourName as String * 10
Scope of Declaration
Other than using the Dim keyword to declare the data, you can also use other keywords to
declare the data. Three other keywords are private ,static and public. The forms are as shown
below:
The above keywords indicate the scope of the declaration. Private declares a local variable or a
variable that is local to a procedure or module. However, Private is rarely used, we normally use
Dim to declare a local variable. The Static keyword declares a variable that is being used
multiple times, even after a procedure has been terminated. Most variables created inside a
procedure are discarded by Visual Basic when the procedure is finished, static keyword
preserves the value of a variable even after the procedure is terminated. Public is the keyword
that declares a global variable, which means it can be used by all the procedures and modules of
the whole program.
Constants
Constants are different from variables in the sense that their values do not change during the
running of the program.
Declaring a Constant
Example 5.3
Const Pi As Single=3.142
Const Temp As Single=37
Const Score As Single=100
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.
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:
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.
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.
● 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.
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, and Property Set procedure that sets the references
to an object.
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.
These are the rules to follow when naming elements in VB - variables, constants, controls,
procedures, and so on:
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.
The If...Then selection structure performs an indicated action only when the condition is True;
otherwise the action is skipped.
If <condition> Then
statement
End If
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
Method 1
Method 2
e.g.: Assume you have to find the grade using nested if and display in a text box
e.g.: Assume you have to find the grade using select...case and display in the text box
average = txtAverage.Text
Select Case average
Case 100 To 75
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
A repetition structure allows the programmer to that an action is to be repeated until given
condition is true.
The Do While...Loop is used to execute statements until a certain condition is met. The
following Do Loop counts from 1 to 100.
A variable number is initialized to 1 and then the Do While Loop starts. First, the condition is
tested; if condition is True, then the statements are executed. When it gets to the Loop it goes
back to the Do and tests condition again. If condition is False on the first pass, the statements are
never executed.
number = 1
While number <=100
number = number + 1
Wend
The Do...Loop While statement first executes the statements and then test the condition after
each execution. The following program block illustrates the structure:
The programs 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 Until...Loop Statement
Unlike the Do While...Loop and While...Wend repetition structures, the Do Until...
Loop structure tests a condition for falsity. Statements in the body of a Do Until...Loop are
executed repeatedly as long as the loop-continuation test evaluates to False.
An example for Do Until...Loop statement. The coding is typed inside the click event of the
command button
Numbers between 1 to 1000 will be displayed on the form as soon as you click on the command
button.
The For...Next Loop is another way to make loops in Visual Basic. For...Next repetition
structure handles all the details of counter-controlled repetition. The following loop counts the
numbers from 1 to 100:
Dim x As Integer
For x = 1 To 50
Print x
Next
In order to count the numbers from 1 yo 50 in steps of 2, the following loop can be used
For x = 1 To 50 Step 2
Print x
Next
The above coding will display numbers vertically on the form. In order to display numbers
horizontally the following method can be used.
For x = 1 To 50
Print x & Space$ (2);
Next
To increase the space between the numbers increase the value inside the brackets after the &
Space$.
Following example is a For...Next repetition structure which is with the If condition used.
In the output instead of number 4 you will get the "This is number 4".
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, we 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. 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.
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".
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.
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
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.
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.
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. Note that 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.
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.
An example for three dimensional-array with defined lower limits is given below.
Basically, you can create either static or 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:
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. You declare and create dynamic arrays in two distinct steps.
In general, you declare 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:
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. My suggestion is this: Never use an
Option Base statement because it makes code reuse more difficult. (You can't cut and paste
routines without worrying about the current Option Base.) If you want to explicitly use a lower
index different from 0, use this syntax instead:
Dynamic arrays can be re-created at will, each time with a different number of items. When you
re-create a dynamic array, its contents are reset to 0 (or to an empty string) and you lose the data
it contains. If you want to resize an array without losing its contents, use the ReDim Preserve
command:
When you're resizing an array, you can't change the number of its dimensions nor the type of the
values it contains. Moreover, when you're using ReDim Preserve on a multidimensional array,
you can resize only its last dimension:
You can use the LBound and UBound functions to retrieve the lower and upper indices. If the
array has two or more dimensions, you need to pass a second argument to these functions to
specify the dimension you need:
UDT structures can include both static and dynamic arrays. Here's a sample structure that
contains both types:
Type MyUDT
StaticArr(100) As Long
DynamicArr() As Long
End Type
...
Dim udt As MyUDT
' You must DIMension the dynamic array before using it.
ReDim udt.DynamicArr(100) As Long
' You don't have to do that with static arrays.
udt.StaticArr(1) = 1234
The memory needed by a static array is allocated within the UDT structure; for example, the
StaticArr array in the preceding code snippet takes exactly 400 bytes. Conversely, a dynamic
array in a UDT takes only 4 bytes, which form a pointer to the memory area where the actual
data is stored. Dynamic arrays are advantageous when each individual UDT variable might host
a different number of array items. As with all dynamic arrays, if you don't dimension a dynamic
array within a UDT before accessing its items, you get an error 9—"Subscript out of range."
This lesson concentrates on Visual Basic controls and the ways of creating and implementing
the. It also helps us to understand the concept of Control Arrays. Controls are used to recieve
user input and display output and has its own set of properties, methods and events. Let us
discuss few of these controls in this lesson.
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.
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. Let us discuss these controls
by means of a few simple applications in the following lessons.
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
Some of these objects support OLE Automation, which allow programming another application's
object from within Visual Basic application.
I would like to stress that knowing how and when to set the objects' properties is very important
as it can help you to write a good program or you may fail to write a good program. So, I advice
you to spend a lot of time playing with the objects' properties
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.
Windows applications provide groups of related commands in Menus. These commands depends
on the application, but some-such as Open and Save are frequently found in applications. Menus
are intrinsic controls, and as such they deserve a place in this chapter. On the other hand, menus
behave differently from other controls. For example, you don't drop menu items on a form from
the Toolbox; rather, you design them in the Menu Editor window, as you can see in the figur
below. You invoke this tool from the Menu Editor button on the standard toolbar or by pressing
the Ctrl+E shortcut key. There's also a Menu Editor command in the Tools menu, but you
probably won't use it often.
Visual Basic provides an easy way to create menus with the modal Menu Editor dialog. The
below dialog is displayed when the Menu Editor is selected in the Tool Menu. The Menu Editor
command is grayed unless the form is visible. And also you can display the Menu Editor window
by right clicking on the Form and selecting Menu Editor.
Basically, each menu item has a Caption property (possibly with an embedded & character to
create an access key) and a Name. Each item also exposes three Boolean properties, Enabled,
Visible, and Checked, which you can set both at design time and at run time. At design time, you
can assign the menu item a shortcut key so that your end users don't have to go through the menu
system each time they want to execute a frequent command. (Do you really like pulling down the
Edit menu any time you need to clear some text or copy it to the Clipboard?) The assigned
shortcut key can't be queried at run time, much less modified.
Building a menu is a simple, albeit more tedious, job: You enter the item's Caption and Name,
set other properties (or accept the default values for those properties), and press Enter to move to
the next item. When you want to create a submenu, you press the Right Arrow button (or the
Alt+R hot key). When you want to return to work on top-level menus—those items that appear
in the menu bar when the application runs—you click the Left Arrow button (or press Alt+L).
You can move items up and down in the hierarchy by clicking the corresponding buttons or the
hot keys Alt+U and Alt+B, respectively.
You can create up to five levels of submenus (six including the menu bar), which are too many
even for the most patient user. If you find yourself working with more than three menu levels,
think about trashing your specifications and redesigning your application from the ground up.
You can insert a separator bar using the hypen (-) character for the Caption property. But even
these separator items must be assigned a unique value for the Name property, which is a real
nuisance. If you forget to enter a menu item's Name, the Menu Editor complains when you
decide to close it. The convention used in this book is that all menu names begin with the three
letters mnu.
An expanded menu
One of the most annoying defects of the Menu Editor tool is that it doesn't permit you to reuse
the menus you have already written in other applications. It would be great if you could open
another instance of the Visual Basic IDE, copy one or more menu items to the clipboard, and
then paste those menu items in the application under development. You can do that with controls
and with pieces of code, but not with menus! The best thing you can do in Visual Basic is load
the FRM file using an editor such as Notepad, find the portion in the file that corresponds to the
menu you're interested in, load the FRM file you're developing (still in Notepad), and paste the
code there. This isn't the easiest operation, and it's also moderately dangerous: If you paste the
menu definition in the wrong place, you could make your FRM form completely unreadable.
Therefore, always remember to make backup copies of your forms before trying this operation.
Better news is that you can add a finished menu to a form in your application with just a few
mouse clicks. All you have to do is activate the Add-In Manager from the Add-Ins menu, choose
the VB 6 Template Manager, and tick the Loaded/Unloaded check box. After you do that, you'll
find three new commands in the Tools menu: Add Code Snippet, Add Menu, and Add Control
Set. Visual Basic 6 comes with a few menu templates, as you can see in the following figure, that
you might find useful as a starting point for building your own templates. To create your menu
templates, you only have to create a form with the complete menu and all the related code and
then store this form in the \Templates\Menus directory. (The complete path, typically c:\Program
Files\Microsoft Visual Studio\VB98\Template, can be found in the Environment tab of the
Options dialog box on the Tools menu. The Template Manager was already available with
Visual Basic 5, but it had to be installed manually and relatively few programmers were aware of
its existence.
The Template Manager in action
The programmer can create menu control arrays. The Index TextBox specifies the menu's index
in the control array.
The Menu Editor dialog also provides several CheckBoxes to control the appearance of the
Menu.
Checked : This is unchecked by default and allows the programmer the option of creating a
checked menu item( a menu item that act as a toggle and displays a check mark when selected.
The following is a Check Menu items.
Enabled : specifies whether a menu is disabled or not. If you see a disabled command in a menu
that means that feature is not available. The Visible checkbox specifies whether the menu is
visible or not.
To add commands to the Form's menu bar, enter a caption and a name for each command. As
soon as you start typing the command's caption, it also appears in a new line in the list at the
bottom of the Menu Editor window. To add more commands click Enter and type the Caption
and the Name.
Creating Menus
Open a new Project and save the form as menu.frm and save the project as menu.vbp.
Choose Tools ››› Menu Editor and type the menu items as shown below.
Caption Name
File mnuFile
Open mnuOpen
Save mnuSave
Exit mnuExit
Edit mnuEdit
Copy mnuCopy
Cut mnuCut
Paste mnuPaste
An MDI application must have at least two Form, the parent Form and one or more child Forms.
Each of these Forms has certain properties. There can be many child forms contained within the
parent Form, but there can be only one parent Form.
The parent Form may not contain any controls. While the parent Form is open in design mode,
the icons on the ToolBox are not displayed, but you can't place any controls on the Form. The
parent Form can, and usually has its own menu.
1. Start a new project and then choose Project >>> Add MDI Form to add the parent
Form.
2. Set the Form's caption to MDI Window
3. Choose Project >>> Add Form to add a SDI Form.
4. Make this Form as child of MDI Form by setting the MDI Child property of the
SDI Form to True. Set the caption property to MDI Child window.
Visual Basic automatically associates this new Form with the parent Form. This child Form can't
exist outside the parent Form; in the words, it can only be opened within the parent Form.
MDI Form cannot contain objects other than child Forms, but MDI Forms can have their own
menus. However, because most of the operations of the application have meaning only if there is
at least one child Form open, there's a peculiarity about the MDI Forms. The MDI Form usually
has a menu with two commands to load a new child Form and to quit the application. The child
Form can have any number of commands in its menu, according to the application. When the
child Form is loaded, the child Form's menu replaces the original menu on the MDI Form
* Open a new Project and name the Form as Menu.frm and save the Project as Menu.vbp
At design time double click on MDI Open and add the following code in the click event of the
open menu.
Form1.Show
And so double click on MDI Exit and add the following code in the click event
End
Double click on Child Close and enter the following code in the click event
Unload Me
Before run the application in the project properties set MDI Form as the start-up Form. Save and
run the application. Following output will be displayed.
And as soon as you click MDI Open you can notice that the main menu of the MDI Form is
replaced with the Menu of the Child Form. The reason for this behavior should be obvious. The
operation available through the MDI Form are quite different from the operations of the child
window. Moreover, each child Form shouldn't have it's own menu.
The first argument is an integer called Button. The value of the argument indicates whether the
left, right or middle mouse button was clicked. The second argument in an integer called shift.
The value of this argumnet indicates whether the mouse button was clicked simultaneously with
the Shift key, Ctrl key or Alt key. The third and fourth arguments X and Y are the coordinates of
the mouse location at the time the mouse button was clicked. As the Form_MouseDown( ) is
executed automatically whenever the mouse button is clicked inside the Form's area the X, Y
co-ordinates are referenced to the form.
Positioning a control
MouseDown is the commonly used event and it is combined wiyth the move method to move an
Image control to different locations in a Form. The following application illustrates the
movement of objects responding to move events. it makes use of two OptionButton Controls,
two image controls and a CommandButton. The application is designed in such a way that when
an OptionButton is selected, the corresponding image control is placed anywhere in the form
whenever it is clicked.
Open a new standard EXE project and save the Form as Move.frm and save the project
as Move.vbp Design the Form as shown below.
Name frmMouseDown
Name optCredit
Value True
Name optCash
Picture c:/credit.jpg
Picture c:/cash.jpg
The follwoing code is entered in the general declarations section of the Form.
Option Explicit
Run the application by keying in F5. You can notice that when the mouse is clicked on the form
somewhere, the selected image moves to that clicked location. This is shown in the below figure.
UNIT III: ODBC and Data Access Objects:
Further Microsoft Visual Basic provides tools for creating and accessing a variety of RDBMS
(Relational Database Management System). An RDBMS stores and retrieves information
according to the relationship defined. In a RDBMS, the data is the container of the tables in
which all data is stored in the relationships is formed by data values.
A database is a collection of data that is related one to another to support a common application.
For example Employee details - Name, Address, etc. Each of these collections of data continue a
database.
If you need some databases for your website, I recommend you to take a look
at SQLdumpster.com databases. They have hundreds of useful databases at very reasonable
prices.
ADO (ActiveX Data Object) Data Control
• The ADO (ActiveX Data Object) data control is the primary interface between a Visual Basic
application and a database. It can be used without writing any code at all! Or, it can be a central
part of a complex database management system. This icon may not appear in your Visual Basic
toolbox. If it doesn’t, select Project from the main menu, then click Components. The
Components window will appear. Select Microsoft ADO Data Control, then click OK. The
control will be added to your toolbox.
• As mentioned in Review and Preview, previous versions of Visual Basic used another data
control. That control is still included with Visual Basic 6.0 (for backward compatibility) and has
as its icon:
Make sure you are not using this data control for the work in this class. This control is suitable
for small databases. You might like to study it on your own.
• The data control (or tool) can access databases created by several other programs besides
Visual Basic (or Microsoft Access). Some other formats supported include Btrieve, dBase,
FoxPro, and Paradox databases.
1. Connect to a database.
4. Pass database fields to other Visual Basic tools, for display or editing. Such tools are bound
tools (controls), or data aware.
LockType Indicates the type of locks placed on records during editing (default
setting makes databases read-only).
RecordSource Determines the table (or virtual table) the data control is attached to.
• As a rule, you need one data control for every database table, or virtual table, you need access
to. One row of a table is accessible to each data control at any one time. This is referred to as the
current record.
• When a data control is placed on a form, it appears with the assigned caption and four arrow
buttons:
The arrows are used to navigate through the table rows (records). As indicated, the buttons can
be used to move to the beginning of the table, the end of the table, or from record to record.
What is OLE?
OLE (Object Linking and Embedding) is a means to interchange data between applications. Of
late OLE has been enhanced to provide not just data but also methods that can be used by client
application.
Before we proceed any further, let us understand a few terms related to OLE.
OLE Server
This is an application that can provide objects to other applications. This is also called as OLE
Source application.
OLE Client
This is an application that uses objects provided by OLE Server. This is also called as OLE
Container as it contains objects provided by OLE Server.
Not every application is an OLE Server. Only a few applications are capable of providing
objects. In the same way not all applications are capable of receiving objects. However, there are
applications, such as MS-Word and MS-Excel that are capable of being OLE source as well as
OLE Container.
The advantage with Object Embedding is, client application maintains its own copy of the data.
The disadvantage is, changes made to original data (in source application) will not be
incorporated in the data maintained by client.
Whenever you double click on the object in container application, the source application will be
invoked (as information regarding source application is maintained) and the data of client
application is placed in source application for editing.
The following example, where we embed a few cells of Excel spreadsheet to a Word document,
will make this process clear:
As you have seen in the above example, once an object is embedded into MS-Word, you do not
have to invoke source application manually, instead just double click on the object and that will
invoke source application automatically.
However, if data is changed in the original worksheet of MS-Excel then those changes are not
copied to the data in MS-Word. This is because in Object Embedding, source and container
applications maintain two different copies of the data.
What is Object Linking?
Object linking makes changes made to source application available to container application. This
is because container doesn’t store a separate copy of the data, instead it maintains a link to data
in source application.
If you take the same example as previous one, in object linking, no separate copy of the required
portion of spreadsheet is stored in MS-Word document, instead, the name of the file and the
location of the data in the file are only maintained. Whenever you open MS-Word document, the
data is taken from the spreadsheet file from where the data for object is taken. That is the reason
why changes made in spreadsheet file (source) will be available to container application.
UNIT V
Additional controls in VB
MSFlexgrid control
1. Start up VB
2. Pick Standard EXE from the new project list
3. Add the MSFlexGrid control to your project:
1. Go to the Project menu, pick Components.
2. Scroll down the list of components until you find "Microsoft FlexGrid Control
6.0 (sp3)". Select that checkbox and hit the OK button to add the control to your
project.
4. Add a FlexGrid to your form by picking the tool and drawing it on your main form.
5. Add a data source to the form using the tool and drawing on the form. Change
its visibility property to False.
6. Add two frames to the form using the tool and drawing them on the form.
7. Change the caption of one to Add new entry and the caption of the other to Remove
Entry
8. Draw the following controls in the Add new entry frame (yes, actually in the frame):
1. A text box with the (name) txtArtistName
2. A label above that text box with the caption Artist Name
3. A text box with the (name) txtAlbumTitle
4. A label above that text box with the caption Album Title
5. A text box with the (name) txtTrackCount
6. A label above that text box with the caption Number of Tracks
7. A command button with the (name) cmdAddEntry and the caption Add this info
9. Now, to the Remove Entry frame, add the following controls:
1. A command button with the (name) cmdRemoveEntry and the caption Remove
Selected
2. A label with the caption Select the entry you want to remove and click the button:
10. Now, the most complicated part is formatting the FlexGrid (which is
called MSFlexGrid1) to do what you want. It's fairly customizable, but here's all I did for
this example program:
1. the AllowUserResizing property was set to 1
2. the C ols property was set to 3
3. the D ataSource property was set to Data1 (** this is required **) this hooks the
data source up to the FlexGrid.
4. the FixedCols property was set to 0 while the FixedRows property was set to 1.
(this is recommended)
5. the FocusRect property was set to 0.
6. the HighLight property was set to 1.
7. the ScrollTrack property was set to True.
8. the SelectionMode property was set to 1 (selection by row only).
9. the WordWrap property was set to True.
11. Okay, next the code. In the form design window, double click the form, which should
bring up the code window with a blank Form_Load() s ubroutine. Here's the code for it: