Unit - IV
List Boxes
A list box displays a list of items from which the user can select one or more items. If the number
of items exceeds the number that can be displayed, a scrollbar is automatically added.
List Box Properties:
Appearance Selects 3-D or flat appearance.
List Array of items in list box.
ListCount Number of items in list.
ListIndex The number of the most recently selected item in list.If no item is selected, ListIndex =
-1.
MultiSelect Controls how items may be selected (0-no multiple selection allowed, 1-multiple
selection
allowed, 2- group selection allowed).
Selected Array with elements set equal to True or False,depending on whether corresponding
list
item is selected.
Sorted True means items are sorted in 'Ascii' order, else items appear in order added.
Text Text of most recently selected item.
List Box Events:
Click Event triggered when item in list is clicked.
DblClick Event triggered when item in list is double-clicked. Primary way used to process
selection.
List Box Methods:
AddItem Allows you to insert item in list.
Clear Removes all items from list box.
RemoveItem Removes item from list box, as identified by index of item to remove.
Examples
lstExample.AddItem "This is an added item" ' adds text string to list
lstExample.Clear ' clears the list box
lstExample.RemoveItem 4 ' removes lstExample.List(4) from list box
Items in a list box are usually initialized in a Form_Load procedure. It's always a good idea to Clear a
list box before initializing it.
You've seen list boxes before. In the standard 'Open File' window, the Directory box is a list box with
MultiSelect equal to zero.
Combo Boxes
The combo box is similar to the list box. The differences are a combo box includes a text box on top
of a list box and only allows selection of one item. In some cases, the user can type in an alternate
response.
Combo Box Properties:
Combo box properties are nearly identical to those of the list box, with the deletion of the MultiSelect
property and the addition of a Style property.
Appearance Selects 3-D or flat appearance.
List Array of items in list box portion.
ListCount Number of items in list.
ListIndex The number of the most recently selected item in list.If no item is selected, ListIndex =
-1.
Sorted True means items are sorted in 'Ascii' order, else items appear in order added.
Style Selects the combo box form.
Style = 0, Dropdown combo; user can change selection.
Style = 1, Simple combo; user can change selection.
Style = 2, Dropdown combo; user cannot change selection.
1
Text Text of most recently selected item.
List Box Events:
Click Event triggered when item in list is clicked.
DblClick Event triggered when item in list is double-clicked. Primary way used to process
selection.
List Box Methods:
AddItem Allows you to insert item in list.
Clear Removes all items from list box.
RemoveItem Removes item from list box, as identified by index of item to remove.
Examples
cboExample.AddItem "This is an added item" ' adds text string to list
cboExample.Clear ' clears the combo box
cboExample.RemoveItem 4 ' removes cboExample.List(4) from list box
Visual Basic Looping
Looping is done with the Do/Loop format. Loops are used for operations are to be repeated some
number of times. The loop repeats until some specified condition at the beginning or end of the loop
is met.
Do While/Loop
Example:
Counter = 1
Do While Counter <= 1000
Print Counter
Counter = Counter + 1
Loop
This loop repeats as long as (While) the variable Counter is less than or equal to 1000. Note a Do
While/Loop structure will not execute even once if the While condition is violated (False) the first
time through. Also note the Print statement. What this does is print the value Counter in the Visual
Basic Debug window. We'll learn more about this window later in the course.
Do Until/Loop
Example:
Counter = 1
Do Until Counter > 1000
Print Counter
Counter = Counter + 1
Loop
This loop repeats Until the Counter variable exceeds 1000. Note a Do Until/Loop structure will not
be entered if the Until condition is already True on the first encounter.
Do/Loop While
Example:
Sum = 1
Do
Print Sum
Sum = Sum + 3
Loop While Sum <= 50
2
This loop repeats While the Variable Sum is less than or equal to 50. Note, since the While check is
at the end of the loop, a Do/Loop While structure is always executed at least once.
Do/Loop Until
Example:
Sum = 1
Do
Debug.Print Sum
Sum = Sum + 3
Loop Until Sum > 50
This loop repeats Until Sum is greater than 50. And, like the previous example , a Do/Loop Until
structure always executes at least once.
Make sure you can always get out of a loop! Infinite loops are never nice. If you get into one, try
Ctrl+Break. That sometimes works - other times the only way out is rebooting your machine! The
statement Exit Do will get you out of a loop and transfer program control to the statement following
the Loop statement.
Counting is accomplished using the For/Next loop.
Example
For I = 1 to 50 Step 2
A=I*2
Print A
Next I
In this example, the variable I initializes at 1 and, with each iteration of the For/Next loop, is
incremented by 2 (Step). This looping continues until I becomes greater than or equal to its final
value (50). If Step is not included, the default value is 1. Negative values of Step are allowed.
You may exit a For/Next loop using an Exit For statement. This will transfer program control to the
statement following the Next statement.
String Functions
we shall learn how to manipulate string using functions like Len, Right, Left, Mid, Trim, Ltrim, Rtrim,
Ucase, Lcase, Instr, Val, Str ,Chr and Asc.
1. The Len Function
The Len function returns an integer value which is the length of a phrase or a sentence, including the
empty spaces. The syntax is
Len (Phrase)
For example,
Len (“VisualBasic”) = 11 and Len (“welcome to VB tutorial”) = 22
The Len function can also return the number of digits or memory locations of a number that is
stored in the computer. For example,
2. The Right Function
The Right function extracts a substring from a phrase, starting from the Right. The syntax is
Right (Phrase, n)
where n indicates the number of characters that you wish to extract starting from the right-most
character. For example,
3
Right(“Visual Basic”, 4) = asic
3. The Left Function
The Left function extracts a substring from a phrase, starting from the left. The syntax is
Left(Phrase, n)
where n indicates the number of characters that you wish to extract starting from the left-most
character.. For example,
Left (“Visual Basic”, 4) = Visu
4. The Ltrim Function
The Ltrim function trims the empty spaces of the left portion of the phrase. The syntax is
Ltrim(Phrase)
For example,
Ltrim (“ Visual Basic”, 4)= Visual basic
5. The Rtrim Function
The Rtrim function trims the empty spaces of the right portion of the phrase. The syntax is
Rtrim(Phrase)
For example,
Rtrim (“Visual Basic ”, 4) = Visual basic
6. The Trim function
The Trim function trims the empty spaces on both side of the phrase. The syntax is
Trim(Phrase)
For example,
Trim (“ Visual Basic ”) = Visual basic
7. The Mid Function
The Mid function extracts a substring from the original phrase or string. The syntax is:
Mid(phrase, position, n)
Where position is the starting position of the phrase from which the extraction process will start and
n is the number of characters to be extracted. For example,
Mid(“Visual Basic”, 3, 6) = ual Bas
8. The InStr function
The InStr function looks for a phrase that is embedded within the original phrase and returns the
starting position of the embedded phrase. The syntax is
Instr (n, original phase, embedded phrase)
Where n is the position where the Instr function will begin to look for the embedded phrase. For
example
Instr(1, “Visual Basic”,” Basic”)=8
9. The Ucase and the Lcase functions
The Ucase function converts all the characters of a string to capital letters. On the other hand,
the Lcase function converts all the characters of a string to small letters. For example,
Ucase(“Visual Basic”) =VISUAL BASIC
Lcase(“Visual Basic”) =visual basic
10. The Str and Val functions
The Str is the function that converts a number to a string while the Val function converts a string to a
number. The two functions are important when we need to perform mathematical operations.
11. The Chr and the Asc functions
4
The Chr function returns the string that corresponds to an ASCII code while the Asc function
converts an ASCII character or symbol to the corresponding ASCII code. ASCII stands for “American
Standard Code for Information Interchange”. Altogether there are 255 ASCII codes and as many
ASCII characters. Some of the characters may not be displayed as they may represent some actions
such as the pressing of a key or produce a beep sound. The syntax of the Chr function is
Chr(charcode)
and the syntax of the Asc function is
Asc(Character)
The following are some examples:
Chr(65)=A, Chr(122)=z, Chr(37)=% , Asc(“B”)=66, Asc(“&”)=38
We can create a Asc to Chr and Chr to Asc converter in the following Example:
In this example, we create two buttons, label one of them as ASC and the other one as CHR. Insert
two textboxes, one for the user to enter an ASC code and the other one to enter the CHR character.
When the user enter an ASC code, he or she can check for the corresponding character by clicking
the CHR button. Likewise, he or she can check the corresponding ASC code after entering a
character.
12. The String function
The String function has two arguments, a number and a single-character string, and returns a string
consisting of the specified character repeated the specified number of times. The syntax of the String
function is:
String(n,"Character")
For example, String(30, "#") will return the # sign 30 times, as shown in the program below:
###############################
Arrays
By definition, an array is a variable with a single name that represents many different items.
For example, if we need to enter one hundred names, it is difficult to declare 100 different names.
So, instead of declaring one hundred different variables, we need to declare only one array. We
differentiate each item in the array by using subscript, the index value of each item, for example,
name(1), name(2), name(3) .......etc. , makes declaring variables more streamline.
An array can be one-dimensional or multidimensional. A one-dimensional array is like a list of items
or a table that consists of one row of items or one column of items.
A two-dimensional array is a table of items that make up of rows and columns. The format for a one-
dimensional array is ArrayName(x), the format for a two dimensional array is ArrayName(x,y) and a
three-dimensional array is ArrayName(x,y,z) . Normally it is sufficient to use a one-dimensional and
two-dimensional array, you only need to use higher dimensional arrays if you need to deal with
more complex problems. Let me illustrate the arrays with tables
Table 16.1. One dimensional Array
Student Name Name(1) Name(2) Name(3) Name(4)
<
Table 16.2 Two Dimensional Array
Name(1,1) Name(1,2) Name(1,3) Name(1,4)
5
Name(2,1) Name(2,2) Name(2,3) Name(2,4)
Name(3,1) Name(3,2) Name(3,3) Name(3,4)
Declaring one dimensional Array
The general syntax to declare a one dimensional array is as follow:
Dim arrayName(subscript) as dataType
where subs indicates the last subscript in the array.
When you declare an array, you need to be aware of the number of elements created by the Dim
keyword. In the Dim arrayName(subscript) statement, subscript actually is a constant that defines
the maximum number of elements allowed. More importantly, subs start with 0 instead of 1.
Therefore, the Dim arrangeName(10) statement creates 11 elements numbered 0 to 11. There are
two ways to overcome this problem, the first way is by using the keyword Option Base 1, as shown in
Example 16.1.
Example 1
Option Base 1
Dim CusName(10) as String
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), as shown in Table 6.3
Table 6.3
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
Dim arrayName(lowerbound To upperbound) As dataType
Example 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)
Multi-Dimensional Arrays
Declaring two dimensional Array
The general syntax to declare a two dimensional array is as follow:
Dim ArrayName(Sub1,Sub2) as dataType
Example 1
If you wish to compute a summary of students involve in games according to different year in a high
school, you need to declare a two dimensional array. In this example, let's say we have 4 games,
6
football, basketball, tennis and hockey and the classes are from year 7 to year 12. We can create an
array as follows:
Dim Games(1 to 4,7 to 12 ) As Integer
will create an array of four rows and six columns, as shown in table 16.4.
Table 16.4
Year 7 8 9 10 11 12
Games(1,8
Football Games(1,7) Games(1,9) Games(1,10) Games(1,11) Games(1,12)
)
Basketbal Games(2,8
Games(2,7) Games(2,9) Games(2,10) Games(2,11) Games(2,12)
l )
Games(3,8
Tennis Games(3,7) Games(3,9) Games(3,10) Games(3,11) Games(3,12)
)
Games(4,8
Hockey Games(4,7) Games(4,9) Games(4,10) Games(4,11) Games(4,12)
)
Declaring three dimensional Array
The general syntax to declare a three dimensional array is as follow:
Dim ArrayName(Sub1,Sub2,Sub3) as dataType
Example
Dim threeDIntArray(10, 10, 10) As Integer
Control Arrays
With some controls, it is very useful to define control arrays - it depends on the application. For
example, option buttons are almost always grouped in control arrays.
Control arrays are a convenient way to handle groups of controls that perform a similar function. All
of the events available to the single control are still available to the array of controls, the only
difference being an argument indicating the index of the selected array element is passed to the
event. Hence, instead of writing individual procedures for each control (i.e. not using control arrays),
you only have
to write one procedure for each array.
Another advantage to control arrays is that you can add or delete array elements at run-time. You
cannot do that with controls (objects) not in arrays. Refer to the Load and Unload statements in on-
line help for the proper way to add and delete control array elements at run-time.
Two ways to create a control array:
1. Create an individual control and set desired properties. Copy the control using the editor, then
paste it on the form. Visual Basic will pop-up a dialog box that will ask you if you wish to create a
control array. Respond yes and the array is created.
2. Create all the controls you wish to have in the array. Assign the desired control array name to the
first control. Then, try to name the second control with the same name. Visual Basic will prompt you,
7
asking if you want to create a control array. Answer yes. Once the array is created, rename all
remaining
controls with that name.
Once a control array has been created and named, elements of the array are referred to by their
name and index. For example, to set the Caption property of element 6 of a label box array named
lblExample, we would use:
lblExample(6).Caption = “This is an example”
For...Next
Do...Loop is useful when a block of statements are to be executed for unknown number of times.
But if a block of statements are to be executed for specific number of times then a For…Next loop is
a better choice. Unlike a Do loop, a For loop uses a variable called a counter that increases or
decreases in value during each repetition of the loop.
Syntax
For counter = start To end [Step increment]
statements
Next [counter]
The arguments counter, start, end, and increment are all numeric.
The increment argument can be either positive or negative. If increment is positive, start must be
less than or equal to end or the statements in the loop will not execute. If increment is negative,
start must be greater than or equal to end for the body of the loop to execute. If Step isn't set, then
increment defaults to 1.
In executing the For loop, Visual Basic:
1. Sets counter equal to start.
2. Tests to see if counter is greater than end. If so, Visual Basic exits the loop.
(If increment is negative, Visual Basic tests to see if counter is less than end.)
3. Executes the statements.
4. Increments counter by 1 or by increment, if it's specified.
5. Repeats steps 2 through 4.
Example
Dim i as integer
For i = 1 to 10 step 2
Print i
Next i
Output
1
3
5
7
9
8
For Each...Next Statement
A For Each...Next loop is similar to a For...Next loop, but it repeats a group of statements for each
element in a collection of objects or in an array instead of repeating the statements a specified
number of times. This is especially helpful when the number of elements of a collection is not
known.
Syntax
For Each element In group
statements
Next element
Example
This example prints the contents of array Names.
Dim Age(10) as integer
Dim Item ‘ Must be variant when used with arrays
----------------------------
----------------------------
For Each Item In Age()
Print Item
Next item
User-Defined Data Types In Visual Basic 6
Variables of different data types when combined as a single variable to hold several related
informations 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 in standard modules 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
ProdID 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 of 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(10) as ProductDetails ' An array of 11 records
A User-Defined data 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
9
TextBox namely text1 is to be assigned the name of the electronic good, the statement can be
written as given below.
ElectronicGoods.ProdName = Text1.Text
10