VB Unit 1
VB Unit 1
Declaring Array
We can use Public or Dim statement to declare an array just as the way we declare
a single variable. The Public statement declares an array that can be used
throughout an application while the Dim statement declares an array that could be
used only in a local procedure.
will declare an array that consists of 10 elements if the statement Option Base 1
appear in the declaration area, starting from CusName(1) to CusName(10).
Otherwise, there will be 11 elements in the array starting from CusName(0)
through to CusName(10)
CusName(1) CusName(2) CusName(3) CusName(4) CusName(5)
CusName(6) CusName(7) CusName(8) CusName(9) CusName(10)
The second way is to specify the lower bound and the upper bound of the subscript
using To keyword. The syntax is
Example 16.2
Dim Count(100 to 500) as Integer
declares an array that consists of the first element starting from Count(100) and ends at Count(500)
Example 16.3
Dim studentName(1 to 10) As String Dim num As Integer
**The program accepts data entries through an InputBox and displays the items in a list box.
16.2.2 Declaring two dimensional Array
Example 16.6
In this example, we want to summarize the first half-yearly sales volume for four
products. Therefore, we declare a two dimension array as follows:
For i = 1 To 4
listVolume.AddItem "Product" & "" & i & vbTab & saleVol(i, j) & vbTab & saleVol(i, j
+ 1) & vbTab & saleVol(i, j + 2) _
& vbTab & saleVol(i, j + 3) & vbTab & saleVol(i, j + 4) & vbTab &
saleVol(i, j + 5) Next i
End Sub
Dynamic Array
So far we have learned how to define the number of elements in an array during design
time. This type of array is known as static array. However, the problem is sometimes we
might not know how many data items we need to store during run time. In this case, we
need to use dynamic array where the number of elements will be decided during run time.
In VB6, the dynamic array can be resized when the program is executing. The first step in
declaring a dynamic array is by using the Dim statement without specifying the dimenson
list, as follows:
Dim myArray()
Then at run time we can specify the actual array size using the ReDim
statement,as follows: ReDim myArray(1 to n) when n is decided during
run time
You can also declare a two dimensional array using ReDim statement,
as follows: ReDim myArray(1 to n, 1 to m) when m and n are
known during run time
Example 16.7
In this example, we want to display the elements of an array in a list box. The size of the
array will only be known during run time. It demonstrates the creation of a dynamic array
using the ReDim keyword.
The Code
Private Sub cmd_display_Click()
Dim
myArray()
As Integer
Dim i, n
As Integer
n = InputBox("Enter the
upper bound of array")
List1.Clear
for i=1 to n
Redim myarray(i)
My Array(i) = i ^ 2
List1.AddItem
myArray(i) Next
End sub
Figure 16.2
Working with Controls
1.1 The Control Properties
Before writing an event procedure for the control to response to an event, you have to set
certain properties for the control to determine its appearance and how will it work with the
event procedure. You can set the properties of the controls in the properties window or at
runtime.
For example, in order to change the caption, just highlight Form1 under the name Caption
and change it to other names. You may also alter the appearance of the form by setting it
to 3D or flat, change its foreground and background color, change the font type and font
size, enable or disable, minimize and maximize buttons and more.
You can also change the properties at runtime to give special effects such as change of
color, shape, animation effect and so on. Example 3.1 show the code that will change the
form color to red every time the form is loaded. VB uses the hexadecimal system to
represent the color. You can check the color codes in the properties windows which are
showing up under ForeColor and BackColor .
Example 3.1: Program to change background color
This example changes the background colour of the form using the BackColor property.
Private Sub
Form_Load()
Form1.Show
Form1.BackColor =
&H000000FF& End
Sub
Example 3.2: Program to change shape
This example is to change the control's Shape using the Shape property. This code will
change the shape to a circle at runtime.
Private Sub
Form_Load()
Shape1.Shape =
3
End Sub
We are not going into the details on how to set the properties yet. However, we would like
to stress a few important points about setting up the properties.
You should set the Caption Property of a control clearly so that a user knows what
to do with that command.
Use a meaningful name for the Name Property because it is easier to write
and read the event procedure and easier to debug or modify the programs later.
One more important property is whether to make the control enabled or not.
Finally, you must also considering making the control visible or invisible at
runtime, or when should it become visible or invisible.
3.2 Handling some of the common Controls
Figure 3.2 below is the VB6 toolbox that shows the basic controls.
TextBox
The text box is the standard control for accepting input from the user as well as to
display the output. It can handle string (text) and numeric data but not images or
pictures.
A string entered into a text box can be converted to a numeric data by using the
function Val(text).
The following example illustrates a simple program that processes the input from the user.
The program use creates a variable sum to accept the summation of values from text box
1 and text box 2.The procedure to calculate and to display the output on the label is shown
below.
Private Sub Command1_Click()
'To add the values in
TextBox1 and TextBox2
Sum = Val(Text1.Text)
+Val(Text2.Text)
'To display the
answer on
label 1
Label1.Captio
n = Sum
End Sub
The output is shown in Figure 3.3
The Label
The label is a very useful control for Visual Basic, as it is not only used to provide
instructions and guides to the users, it can also be used to display outputs.
One of its most important properties is Caption. Using the syntax Label.Caption, it can
display text and numeric data .
You can change its caption in the properties window and also at runtime.
Please refer to Example 3.1 and Figure 3.1 for the usage of the label.
The command button is one of the most important controls as it is used to execute
commands.
It displays an illusion that the button is pressed when the user click on it.
The most common event associated with the command button is the Click event, and the
syntax for the procedure is
Private Sub Command1_Click () Statements
……
…..
End Sub
A Simple Password Cracker
In this program, we want to crack a secret passoword entered by the user. In the design
phase, insert a command button and change its name to cmd_ShowPass. Next, insert a
TextBox and rename it as TxtPassword and delete Text1 from the Text property. Besides
that, set its PasswordChr to *. Now, enter the following code in the code window.
Private Sub cmd_ShowPass_Click()
Dim yourpassword As String yourpassword = Txt_Password.Text
MsgBox ("Your password is: " & yourpassword)
End Sub
OUTPUT:
The PictureBox
The Picture Box is one of the controls that is used to handle graphics. You can load a
picture at design phase by clicking on the picture item in the properties window and select
the picture from the selected folder. You can also load the picture at runtime using the
LoadPicture method. For example, the statement will load the picture grape.gif into the
picture box.
Picture1.Picture=LoadPicture ("C:\VBprogram\Images\grape.gif")
Example 3.4 Loading Picture
In this program, insert a command button and a picture box. Enter the
following code:
Private Sub cmd_LoadPic_Click()
MyPicture.Picture=LoadPicture("C:\Users\admin.DESKTOP-G1G4HEK\Documents\My
Websites\vbtutor\vb6\images\uranus.jpg")
End Sub
* You must ensure the path to access the picture is correct. Besides that, the image in the
picture box is not resizable. The output is shown in Figure 3.5
3.2.6
The ListBox
The ListBox
The function of the ListBox is to present a list of items where the user can click and select
the items from the list.
In order to add items to the list, we can use the AddItem method.
For example, if you wish to add a number of items to list box 1, you can key in the
following statements
Example 3.2
The items in the list box can be identified by the ListIndex property, the value of the
ListIndex for the first item is 0, the second item has a ListIndex 1, and the third item has a
ListIndex 2 and so on
The ComboBox
The function of the Combo Box is also to present a list of items where the user can click
and select the items from the list. However, the user needs to click on the small arrowhead
on the right of the combo box to see the items which are presented in a drop-down list.
In order to add items to the list, you can also use the AddItem method. For example,
if you wish to add a number of items to Combo box 1, you can key in the following
statements
Example 3.3
The CheckBox
The Check Box control lets the user selects or unselects an option. When the Check Box
is checked, its value is set to 1 and when it is unchecked, the value is set to 0. You can
include the statements Check1.Value=1 to mark the Check Box and Check1.Value=0 to
unmark the Check Box, as well as use them to initiate certain actions. For example, the
program in Example 3.4 will show which items are selected in a message box.
Example 3.4
In this example, we want to change the background color of the form according to the
selected option. We insert three option buttons and change their captions to "Red
Background","Blue Background" and "Green Background" respectively. Next, insert a
command button and change its name to cmd_SetColor and its caption to "Set Background
Color". Now, click on the command button and enter the following code in the code
window:
Private Sub cmd_SetColor_Click()
If Option1.Value = True Then
Form1.BackColor = vbRed
ElseIf Option2.Value = True Then
Form1.BackColor = vbBlue
Else
Form1.BackColor = vbGreen
End If
End Sub
Run the program, select an option and click the "Set Background Color" produces the
output, as shown in Figure 3.10.
The Shape Control
In the following example, the shape control is placed in the form together with six
OptionButtons. To determine the shape of the shape control, we use the shape property.
The property values of the shape control are 0, 1, and 2,3,4,5 which will make it appear as
a rectangle, a square, an oval shape, a circle, a rounded rectangle and a rounded square
respectively.
Example 3.5
In this example, we insert six option buttons. It is better to make the option buttons into a
control array as they perform similar action, i.e to change shape. In order to create a
control array, click on the first option button, rename it as MyOption. Next, click on the
option button and select copy then paste. After clicking the paste button, a popup dialog
(Figure 3.11)will ask you whether you wish to create a control array, select yes. The
control array can be accessed via its index value, MyOtion(Index. In addition, we also
insert a shape control.
Figure 3.11
Private Sub MyOption_Click(Index
As Integer) If Index = 0 Then
MyShape.Shape = 0
ElseIf Index = 1 Then
MyShape.Shape = 1
ElseIf Index = 2 Then
MyShape.Shape = 2
ElseIf Index = 3 Then
MyShape.Shape = 3
ElseIf Index = 4 Then
MyShape.Shape = 4
ElseIf Index = 5 Then
MyShape.Shape = 5
End If
End Sub
Run the program and you can change the shape of the shape control by clicking one of the
option buttons. The output is shown in Figure 3.12.
The DriveListBox
The DriveListBox is for displaying a list of drives available in your computer.
When you place this control into the form and run the program, you will be able to select
different drives from your computer as shown in Figure 3.13
The DirListBox
The DirListBox means the Directory List Box.
It is for displaying a list of directories or folders in a selected drive.
When you place this control into the form and run the program, you will be able to select
different directories from a selected drive in your computer as shown in Figure 3.14
The FileListBox
You can coordinate the Drive List Box, the Directory List Box and the File List
Box to search for the files you want.
A control array
A control array is a group of controls that share the same name type and
the same event procedures. Adding controls with control arrays uses
fewer resources than adding multiple control of same type at design
time.
A control array can be created only at design time, and at the very minimum
at least one control must belong to it. You create a control array following
one of these three methods:
Controls that belong to the same control array share the same set of
event procedures; this often dramatically reduces the amount of code you
have to write to respond to a user's actions.
You can dynamically add new elements to a control array at run
time; in other words, you can effectively create new controls that didn't
exist at design time.
Elements of control arrays consume fewer resources than regular
controls and tend to produce smaller executables. Besides, Visual Basic
forms can host up to 256 different control names, but a control array counts
as one against this number. In other words, control arrays let you effectively
overcome this limit.
The importance of using control arrays as a means of dynamically creating
new controls at run time is somewhat reduced in Visual Basic 6, which has
introduced a new and more powerful capability.
Don't let the term array lead you to think control array is related to VBA
arrays; they're completely different objects. Control arrays can only be one-
dimensional. They don't need to be dimensioned: Each control you add
automatically extends the array. The Index property identifies the position of
each control in the control array it belongs to, but it's possible for a control
array to have holes in the index sequence. The lowest possible value for the
Index property is 0. You reference a control belonging to a control array as you
would reference a standard array item:
Text1(0).Text = ""
The fact that multiple controls can share the same set of event procedures is
often in itself a good reason to create a control array. For example, say that
you want to change the background color of each of your TextBox controls to
yellow when it receives the input focus and restore its background color to
white when the user clicks on another field:
End Sub
End Sub
End Sub
The following code is entered in the cmd_Click( ) (Control Array) event procedure
The following code is entered in the click events of the cmdPlus, cmdMinus,
cmdMultiply, cmdDevide controls respectively.
End Sub
End Sub
To print the result on the text box, the following code is entered in the cmdEqual_Click (
) event procedure.
Case "+"
End Select
Current = Result
End Sub
Save and run the project. On clicking digits of user's choice and an operator button, the
output appears.
Iterating on the Items of a Control Array
Control arrays often let you save many lines of code because you can execute
the same statement, or group of statements, for every control in the array
without having to duplicate the code for each distinct control. For example,
you can clear the contents of all the items in an array of TextBox controls as
follows:
Next
Here you're using the LBound and UBound methods exposed by the control
array object, which is an intermediate object used by Visual Basic to gather all
the controls in the array. In general, you shouldn't use this approach to iterate
over all the items in the array because if the array has holes in the Index
sequence an error will be raised. A better way to loop over all the items of a
control array is using the For Each statement:
Next
A third method exposed by the control array object, Count, returns the number
of elements it contains. It can be useful on several occasions (for example,
when removing all the controls that were added dynamically at run time):
conceptually similar to a regular control array, only you set the Index property
to a numeric (non-negative) value in the Menu Editor instead of in the
Properties window.
There are some limitations, though: All the items in an array of menu controls
must be adjacent and must belong to the same menu level, and their Index
properties must be in ascending order (even though holes in the sequence are
allowed). This set of requirements severely hinders your ability to create new
menu items at run time. In fact, you can create new menu items in well-
defined positions of your menu hierarchy— namely, where you put a menu
item with a nonzero Index value—but you can't create new submenus or new
top-level menus.