file=8-arrays.htm; updated
December 4, 2003
OBJECTIVES:
· Use a Select Case statement.
· Use one event procedure to handle multiple controls.
· Use arrays and array subscripts.
· Use the For Each-Next to traverse an array.
· Create structures for related data fields.
· Accumulate totals using arrays.
· Distinguish between direct access and indirect access of a table.
· Combine the advantages of list box controls with arrays.
· Store data in multidimensional arrays.
Select Case Structure
The Select Case or simply Case structure can be used in place of nested If statements when you need to test multiple conditions involving a single variable or expression where the variable or expression may take on many different values.
It is easier to read and code the Select Case structure. Example:
Select
Case expression
Case value1
[statements to execute
if expression matches value1]
Case value2
[statements to execute
if expression matches value2]
.
.
Case Else
[statements when no value is true]
End
Select
The value should match the expression in the Select Case clause of the code. You are testing the expression.
The value (value1, value2, etc.) may be a numeric or string constant or variable, a range of values, a relational condition, or a combination of these.
The Case Else branch is optional, but is usually included if the conditions (values) are not completely exhaustive of all possible values.
'Example #1 – the expression here is a variable to test
Select
Case intScore
Case Is >= 100
lblMessage.Text = "Excellent Score"
Case 80 To 99
lblMessage.Text = "Very Good"
Case 60 To 79
lblMessage.Text = "Passing
Grade"
Case Else
lblMessage.Text = "You Need Improvement"
End
Select
When using a relational operator such as >= or = or <=, etc., then the keyword Is must be used.
Use the keyword To in order to indicate a range of values.
Multiple individual values or constants may be separated by commas.
'Example #2
'The variable to test is txtTeamName
Select
Case txtTeamName.Text.ToUpper()
Case "RAMS", "PATRIOTS"
PrepareForSuperbowl() 'Calls procedure
Case "PACKERS"
PrepareForPlayoffs() 'Calls procedure
Case Else
PrepareForLongBreak() 'Calls procedure
End
Select
What if more than one Case condition is matched? Answer: The first Case condition matched is the only one to execute.
Sharing an Event Procedure
An event procedure, such as a click event, can be shared by more than one control.
In Figure 8.1, five radio buttons are shown inside a group box control. Normally each radio button will have its own name and own click event procedure.
Figure 8.1

You can add events to the Handles clause where an sub procedure is declared to make the procedure respond to the events of other controls. Example:
Private
Sub radBlue_CheckedChanged(By Val sender _
As System.Object, ByVal e As
System.EventArgs) _
Handles radBlue.CheckedChanged,
radBlack.CheckedChanged, _
radRed.CheckedChanged,
radWhite.CheckedChanged, _
radYellow.CheckedChanged
The radBlue_CheckedChanged event will fire whenever any of the radio buttons are clicked.
The key to using this approach is the sender argument that is passed to the CheckedChanged event as an object.
The sender object is generated at run time. It stores information about the object for the CheckedChanged event.
For example, sender has a Name property and the value of sender.Name is passed to the Private Sub when one of the radio buttons is changed. However, if you refer to sender.Name in your program code, an error will occur during compilation ( the Late binding not allowed error message) because the sender object is not created until run time.
You can avoid this error by casting (that is converting) the sender object to a specific object type by using the Ctype function to convert one object to another.
CType(ValueToConvert,
NewType)
Example – cast the sender object as a radio button:
Dim
radSelected As RadioButton
radSelected
= CType(sender, RadioButton)
You can now refer to the radSelected.Name object-property in a Select Case structure in order to determine which radio button is selected – this is because the new object to which sender was cast inherits the properties of sender.
In-Class Exercise
· Start a new project, Ch8InClass. Create a form like the one in Figure 8.1 (shown earlier). Name it frmColor.

· Place a group box on the form -- name the group box grpColor.
· Add five radio buttons with captions as shown. Name them radBlue, radBlack, radRed, radWhite, and radYellow.
· Add a button with the Text property value Change Color named btnChangeColor.
· Declare a module-level variable as the Color data type.
Public Class frmColor
Inherits System.Windows.Forms.Form
[Windows
Form Designer generated code]
Dim mColorNew As Color 'Module-level variable
· Create a shared CheckChanged event procedure with a SelectCase structure to evaluate the radio button selected.
Private Sub
radBlue_CheckedChanged(ByVal sender _
As System.Object, ByVal e As
System.EventArgs) _
Handles radBlue.CheckedChanged, _
radBlack.CheckedChanged, _
radRed.CheckedChanged, _
radWhite.CheckedChanged, _
radYellow.CheckedChanged
'Create radio button object
Dim radSelected As RadioButton
'Cast the sender object value
radSelected = CType(sender, RadioButton)
'Discover which is button is checked
Select Case radSelected.Name
Case "radBlue"
mColorNew = Color.Blue
Case "radBlack"
mColorNew = Color.Black
Case "radRed"
mColorNew = Color.Red
Case "radWhite"
mColorNew = Color.White
Case "radYellow"
mColorNew = Color.Yellow
Case Else
'All colors are identified. Nothing here.
End Select
End Sub
· Create a btnChangeColor_Click event procedure to assign the color selected (stored in the mColorNew module-level variable) to the BackColor property of the form.
Private Sub
btnChangeColor_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnChangeColor.Click
'Assign color selected to the BackColor
'property of the form
Me.BackColor = mColorNew
End
Sub
Single-Dimension Arrays
An Array is a list of values where all of the values in the group are referenced by using the same name. Like a list box without the box, but the list of values are all stored in memory. Arrays are also called tables.
The individual parts of an array are called elements.
Each element is
numbered beginning with the number zero, and the number is placed inside parentheses. This number is called a subscript. The subscript
refers to the element. Examples:
ArrayName(ElementNumber)
'Element 4 of the array named decAmount – remember
'that arrays start with 0 so the 4th element is number
3!
decAmount(3)
'Element 7 of an array named strStates
strStates(6)
Arrays can store both numeric and string data. Example array with names of states.
|
Element |
State Name |
|
0 |
|
|
1 |
|
|
2 |
|
|
3 |
|
|
. . . |
. . . |
The power of arrays comes with using a variable as the subscript. Example:
For
intIndex = 0 To intNumberOfStates
Debug.WriteLine( strStates(intIndex) )
Next
intIndex
Dimensioning an Array
In order to create an array in memory, it must be declared like any other variable.
Usually you will use the Dimension (Dim) statement to declare an array that is local to a procedure. You can also use Private and Public and Friend to declare arrays with different scope levels.
When an array is declared, storage space is allocated and the elements are initialized –numeric array elements to 0, and string array elements to the empty string.
Example array declaration statements:
'A String array with 26 elements
Dim strName(25) As String
'A decimal array of 11 elements
Private
decBalance(10) As Decimal
You can also declare arrays and store values to the elements. This Public declaration statement creates a string array with five elements. The values are placed inside braces (not parentheses). No number of elements is specified.
'A public string array with 5 elements
Public
mstrSchool( ) As String = {"Arts and Sciences", _
"Business", "Nursing",
"Engineering", "Education"}
Valid Subscripts
A subscript must always reference a valid, existing array element.
If an array contains 10 elements, then attempts to reference element -1 or element 11 will be invalid and result in an error message:
An unhandled exception of type 'System.IndexOutOfRangeException'
occurred in Ch8InClass.exe
For Each-Next Loops
Arrays are often processed in loops. The For-Next loops covered in earlier notes can be used – if you use For-Next loops, you must manipulate the array subscript as shown here:
Dim
intIndex As Integer
For
intIndex = 0 To 25
Debug.WriteLine(strName(intIndex))
Next
intIndex
VB.NET also provides the For Each-Next loop – the advantage of this coding construct is that you don't have to manipulate the index. The loop shown here is equivalent to the one shown above. The index for a string array should be a string index. The index for an integer array should be an integer, etc.
Dim
strSingleName As String
For
Each strSingleName In strName
Debug.WriteLine(strSingleName)
Next strSingleName
This loop sets all elements of an integer array named intTotal to zero to reinitialize them if the need arises. Remember a numeric array starts out with each element equal to zero, but if the array is used over and over within a program, it may need to be reinitialized.
Dim
intIndex As Integer
For
Each intIndex In intTotal
intIndex = 0
Next
intIndex
Structures
Thus far you've used integer, decimal, string, color, radio button and other data types.
You can combine fields of related data into something called a structure. This is like a new data type. Structures are public by default, but you can also declare private structures.
For example, suppose you want to track information about products sold by an organization such as Wal-Mart. Each product has a product identifier, product description, quantity on hand, and price. Here is the code to create a product structure.
Structure
Product
Dim strDescription As String
Dim strProductNumber As String
Dim intQuantity
As Integer
Dim decPrice
As Decimal
End
Structure
Note that structures have fields – strDescription, strProductNumber, etc.
Now that you have created the structure, you can declare variables of the structure just as you would any other data type. You can create your own prefix to use to identify the structure, such as prd for product.
Dim
Widget As Product
Dim
Inventory(100) As Product
You can now refer to a specific property of the Widget variable and the Inventory array.
Widget.strDescription
= "Walnut Chair"
Widget.intQuantity = 15
Inventory(3).strDescription = "Walnut Chair"
Inventory(4).strDescription = "Kitchen Chair"
Inventory(3).intQuantity = 15
Inventory(4).intQuantity = 22
Inventory(4).decPrice = 259.95
Structures can also include fields that are arrays. Here is an example that includes a field that is an array. This requires use of the ReDim statement because when the array is initially declared inside of the structure, you are not allowed to specify the number of elements.
'Module-level declaration
Private
Structure WeeklySalesAggregate
Dim intSalesID As Integer
Dim decSales() As Decimal
End
Structure
.
.
'later in the code
Dim
mSalesInfo As WeeklySalesAggregate
.
.
'Inside a procedure you would need to redim
the array
'attribute of the structure
Redim mSalesInfo.decSales(6)
.
.
'Later during processing.
mSalesInfo.intSalesID = 4
mSalesInfo.decSales(intIndex)
= decTodaysSalesAmount
Using Array Elements for Accumulators
You can use arrays as accumulators, for example, accumulating the total number of sales made by month or by week. Figure 8.2 shows a Sales Form. Each group sells raffle tickets. The group number and Sales $ figure are typed into text boxes. For each sale, the OK button is clicked.
Figure 8.2

The code to create the array and for the click event of the OK button is as follows:
'Declare
module-level array with 6 elements
Dim mdecTotalSales(5) As
Decimal
Private Sub
btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnOK.Click
Dim intGroup As Integer
Dim decSale As
Decimal
'Move values from text boxes to memory
intGroup = CInt(txtGroup.Text)
decSale = CDec(txtSales.Text)
'Accumulate sales amount to array
mdecTotalSales(intGroup) += decSale
'Clear textboxes and set focus
txtSales.Text = ""
txtGroup.Text = ""
txtGroup.Focus()
End
Sub
Values typed into the text box controls are stored to memory variables. Next the amount of the sale is added to the accumulator. Last, the text box contents are cleared and focus is set back to the first text box.
Your text use a subscript of intGroup -1 so that the sales for Group 4 are stored in the 4th memory array location that is numbered 3.
My technique is different. I just ignore the first memory location in the array that is numbered 0 – I just don't use it to store anything! It goes to waste, but it's such a small amount of wasted memory so – who cares!
We will build on the in-class exercise by adding accumulators.
In-Class Exercise
· Add a new form like the one shown in Figure 8.2 above to your project. Name it frmSales. Change the project startup object to frmSales.
· Name the text boxes txtGroup and txtSales.
· Add an OK button to the form named btnOK.
· Right after the Public Class statement, dimension a module-level decimal array named mdecTotalSales with elements numbered 0 to 5.
Dim
mdecTotalSales(5) As Decimal
· Add the code for the OK button shown above, but modify the code with a Try-Catch block and If statements to display an error message if the group number is invalid (the group number must be 1 to 5, inclusive).
Private Sub btnOK_Click(ByVal
sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
Dim intGroup As Integer
Dim decSale As
Decimal
Try 'Values may not have been entered in the text
boxes
'Move values from text
boxes to memory
intGroup = CInt(txtGroup.Text)
decSale = CDec(txtSales.Text)
'Check group number
If intGroup >= 1 And intGroup <=
5 Then
'Accumulate sales amount to array
mdecTotalSales(intGroup) += decSale
'Clear textboxes and set focus
txtSales.Text = ""
txtGroup.Text = ""
txtGroup.Focus()
Else
MessageBox.Show("Invalid Group
Number", _
"Data Entry Error", _
MessageBoxButtons.OK, _
MessageBoxIcon.Exclamation)
End If
Catch
MessageBox.Show("Enter Group and
Sales", _
"Data Entry Error", _
MessageBoxButtons.OK, _
MessageBoxIcon.Exclamation)
End Try
End
Sub
· Modify the form as shown in Figure 8.3 to add a list box named lstSales and a second button names btnDisplay.
Figure 8.3

· When btnDisplay is clicked, display the contents of mdecTotalSales to the list box.
Private Sub btnDisplay_Click(ByVal
sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
Dim intGroup As Integer
'Delete any values already in the list box
lstSales.Items.Clear()
'Display value to list box
For intGroup = 1 To 5
lstSales.Items.Add( _
"Group: " &
CStr(intGroup) & " - " & _
FormatCurrency(mdecTotalSales(intGroup)))
Next intGroup
End
Sub
Note that each element of the array is added to the list box inside a For-Next loop. We did not use a For Each-Next loop because we wanted to only process elements 1 through 5 ignoring element 0.
Work through the concatenation of sections to ensure you understand how each item to be added is constructed.
Table Lookup
Use this programming technique to search an array (table) that is located in memory to find a key value in order to use some other non-key value that is associated with the key for some type of processing.
Consider how you look up information in a telephone book. The telephone book is actually a very large table with the Name, Address, and Telephone Number columns.
The key value in the telephone book is the Name. The value you actually want to use is the Telephone Number.
An Example Table
Now consider the array shown below where we want to find the total number of students that are enrolled in a Course, or where we want to be able to accumulate the how many students are enrolled each time a new student enrolls in each course. Note that the key value that we will search for is strCourseNumber.
|
strCourseNumber |
intTotalEnrolled |
|
CMIS108 |
36 |
|
CMIS142 |
22 |
|
CMIS260 |
16 |
|
CMIS270 |
28 |
|
CMIS342 |
70 |
|
CMIS450 |
30 |
|
CMIS464 |
25 |
|
CMIS468 |
28 |
In-Class Exercise
· Add a new form like the one shown in Figure 8.4 to your project. Name it frmCourse. Change the project startup object to frmCourse.
Figure 8.4

· Add a textbox as shown named txtCourse.
· Add a label to display the actual number of students enrolled. Make this label have a "sunken" 3-D appearance by setting the Border Style. Name it lblTotal.
· Add two buttons named btnEnroll and btnDisplay as shown in the figure above.
· Add a list box named lstEnroll.
· Define a Structure in the general declarations section called CourseStructure. The structure must store course numbers and the total students enrolled in a course.
Structure
CourseStructure
Dim strCourseNumber As String
Dim intTotalEnrolled As Integer
End
Structure
· Next dimension a module-level table of type CourseStructure named mCourse (here the m denotes a module-level array).
Dim
mCourse(8) As CourseStructure
· Now load initial values into the array elements for the course numbers--place these statements in the form's Load procedure event for the frmCourse form. We will ignore array position 0.
Private Sub
frmCourse_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
mCourse(1).strCourseNumber =
"CMIS108"
mCourse(2).strCourseNumber =
"CMIS142"
mCourse(3).strCourseNumber =
"CMIS260"
mCourse(4).strCourseNumber =
"CMIS270"
mCourse(5).strCourseNumber =
"CMIS342"
mCourse(6).strCourseNumber =
"CMIS450"
mCourse(7).strCourseNumber =
"CMIS464"
mCourse(8).strCourseNumber =
"CMIS468"
End
Sub
· Add code to the btnEnroll command button click event that will search the table named mCourse, and if an element matches the Course Number typed into the txtCourse text box, add 1 to the total enrolled in the course. This will be accomplished by using a Do/Loop.
Private
Sub btnEnroll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnEnroll.Click
Dim strCourse As String
Dim intIndex As Integer
Dim blnFound As Boolean
'Set initial values for
the search.
blnFound = False
intIndex = 1
strCourse = txtCourse.Text.ToUpper()
'Begin the search
Do Until blnFound Or intIndex > 8
If strCourse = _
mCourse(intIndex).strCourseNumber Then
mCourse(intIndex).intTotalEnrolled += 1
blnFound = True
lblTotal.Text = _
CStr(mCourse(intIndex).intTotalEnrolled)
Else
intIndex += 1
End If
'Code to test if course number was ever matched
If blnFound = False Then 'No match found
MessageBox.Show("Invalid Course
Number", _
"Course Number Error", _
MessageBoxButtons.OK, _
MessageBoxIcon.Exclamation)
End If
End
Sub
· Add code to the btnDisplay button click event to list the total enrollments by course to the lstEnroll list box.
Private Sub
btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnDisplay.Click
Dim intIndex As Integer
'Delete any item in the list box
lstEnroll.Items.Clear()
'Display value to list box
For intIndex = 1 To 8
lstEnroll.Items.Add( _
mCourse(intIndex).strCourseNumber
& " - " & _
CStr(mCourse(intIndex).intTotalEnrolled))
Next intIndex
End
Sub
· Test the project to see if the system accumulates total enrollments by course.
Using List Boxes with Arrays
When the list of items to be stored in an array is small, such as with the course example above, it may be more efficient to provide the system user a list box instead of a text box – a list box can list the course numbers that are valid.
You can store the valid course numbers to the Items collection of the list box.
Remember, the current value of the SelectedIndex property of a list box tells you which item is currently selected.
You can use the SelectedIndex property as a subscript for an item selected from a list. This can be used to replace the more complex table lookup code.
In-Class Exercise
· Replace the txtCourse textbox with a list box named lstCourse.
· Delete the declaration of the CourseStructure data type and the declaration of the mCourse table.
·
Declare a module-level array mintTotal array as shown below. This time we will store the total enrollments
in positions 0 through 7 in the array, a total of 8 locations to accumulate
enrollments.
Dim
mintTotal(7) As Integer
· Delete the form's Load event code. Instead add the following courses to the Items collection for the lstCourse list box. Keep in mind that these will be numbered 0 through 7 in the list box.
CMIS108, CMIS142, CMIS260, CMIS270, CMIS342,
CMIS450, CMIS464, CMIS468
· Replace the code for the btnEnroll button with the following.
Private
Sub btnEnroll_Click()
Dim intCourse As Integer
'Store the index
position of the item currently
' selected in the
list. This is an index position
' in the list, not
the actual course number
intCourse = lstCourse.SelectedIndex
'Now accumulate the
enrollment
If intCourse >=
0 And intCourse <= 7 Then
mintTotal(intCourse) += 1
lblTotal.Text = CStr(mintTotal(intCourse))
'Now unselect the course in the listbox
lstCourse.SelectedIndex
= -1
Else 'give an error message
MessageBox.Show("Invalid Course
Number", _
"Course Number Error", _
MessageBoxButtons.OK, _
MessageBoxIcon.Exclamation)
End If
End
Sub
· Change the code for the btnDisplay command button click event to reflect the fact that now we display the values of the intTotal .
Private Sub
btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnDisplay.Click
Dim intIndex As Integer
'Clear the values displayed in the list box
if any
lstEnroll.Items.Clear()
'Display value to list box
For intIndex = 0 To 7
lstEnroll.Items.Add( _
CStr(lstCourse.Items(intIndex)) & " - " & _
CStr(mintTotal(intIndex)))
Next intIndex
End Sub
Multidimensional Arrays
Use this approach when you need a table with both rows and columns (a two-dimensional table).
An example of an application that uses a two-dimensional
table is the use of tax tables for computing personal income taxes to be paid
to the
Figure 8.5

The declaration statement to allocate memory for decTaxTable is:
Dim
decTaxTable (50, 3) As Decimal
The rows represent the income levels. The columns represent tax classifications such as single, married, and head of household).
Remember, numeric arrays are automatically initialized to zero.
When referencing the decTaxTable, the first subscript you use would represent the row. The second subscript would represent the column.
If you want to display the value of row 20, column 2 to a label, the code would look like this:
lblTaxAmount.Text
= CStr(decTaxTable(19,1)
A Two-Dimensional String Table
Figure 8.6 shows a table that stores string data. States are classified in columns according to their land mass size as Large, Middle, or Small sized.
Figure 8.6

The strStates table could be declared and filled with state names as follows:
Dim
strStates( , ) As String = { _
{"
{"
{"
{"
If the value intRow = 2 and intColumn = 1, the state "
lblState.Text
= strStates(introw, intColumn)
The strStates table can be printed to the output window for purposes to debugging code with nested For-Next loops. Each state will appear on a single line.
Private Sub
btnStates_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnStates.Click
Dim strStates(,) As String = { _
{"
{"
{"
{"
Dim intRow As Integer = 0
Dim intColumn As Integer = 0
For intRow = 0 To 3
For intColumn = 0 To 2
Debug.WriteLine(strStates(intRow,
intColumn))
Next
Next
End
Sub
Summing Values in a Two-Dimensional Array
Assume you have a 4000 by 50 two-dimensional array named lngProductsSold.
The array contains number of products sold (one row for each product) by region of the country (one column per region)
An individual cell in the array would represent the quantity sold of a product for a specific region.
Figure 8.7

Assume we also have a 4000 element single-dimensional array named lngTotalProducts. We want to sum the products sold for all regions and store the result to the lngTotalProductsarray. This is a total of each row.
Finally, assume we have a 50 element single-dimensional array named lngTotalRegion. We want to sum the total sales quantity for each region and store the result to the lngTotalRegion array. This is a total of each column.
Dim
lngProductsSold (4000, 50) As Long
Dim
lngTotalProducts (4000) As Long
Dim
lngTotalRegion (50) As Long
'
'Code would go here that accumulates the
' quantity sold to the lngProductsSold array.
'
Dim
intRow As Integer
Dim
intColumn As Integer
'Sum up the rows
For
intRow = 1 To 4000
For intColumn = 1 To 50
'Sum across the rows
lngTotalProducts(intRow) += _
lngProductsSold(intRow, intColumn)
'Sum down the columns
lngTotalRegion(intColumn) += _
lngProductsSold(intRow, intColumn)
Next
Next
Lookup Search for Two-Dimensional Tables
The technique for searching in two dimensions may involve having the system user enter values into two different textboxes.
One textbox would represent the row index; the other would represent the column index.
If you use this approach, then you must ensure that the values entered for the row and column do not exceed the limitations of the array.
If the row and column index values are valid, you can use them to directly reference a cell in the array, for example:
dblTaxTable(intRow,intColumn)
Another approach requires the system user to search for a value to be found in the array. This would require you to use a nested For-Next search or a Do-Loop search similar to those techniques shown above.
With this approach, the system user typically enters a value in a textbox, then you search a specific column in the array to try to find the value that was typed into the textbox. If the search succeeds, you return a value from a different column of the same array or from column in a different array.
The number of ways that arrays are used is practically limitless, and your ability to manipulate them will improve with practice over time.
In-Class Exercise
In this exercise we will conduct a table lookup for a two-dimensional array. The array will store Product Codes and the associated Product Names.
We wish to enter a product code into a textbox and display the product name. The product codes and product names are shown in the following table.
|
Product Name |
Product Code |
|
Lawn
Chair |
1144 |
|
Lawn
Table |
1166 |
|
Golf
Clubs |
4466 |
· Start a new project and name the form frmProduct. Make this form the project's startup object.
Figure 8.8

· Name the text box to store the product code txtProduct.
· The form needs a label named lblDescription for output where the system will display the product name.
· The form also needs a button named btnLookup to click to cause the system to lookup the product code that is entered into the textbox.
Write code to do the table lookup in the click event of btnLookup. The code is shown below. Note the following:
· First coding task. Declare the table named strProduct (string array) that is two dimensions with 3 rows and 2 columns. Assign values to the table as part of the declaration.
Dim
strProduct( , ) As String = { _
{"Lawn Chair", "1144"},
_
{"Lawn Table", "1166"},
_
{"Golf Clubs", "4466"}
}
· The intRow variable is used to track which row is currently being searched.
· The blnFound Boolean variable is used to track when the product number in the textbox matches the product number in the table (column 1).
o The value returned from the lookup procedure is from the associated row (intRow), column 0.
o If blnFound is still False after the lookup procedure, then the product number was never found.
· The UNTIL condition is a complex condition and terminates the loop when the match is either made (blnFound = True), or the number of rows in the table have been exhausted (the search is over and intRow is greater than the number of rows).
Private Sub
btnLookup_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles
btnLookup.Click
Dim intRow As Integer = 0
Dim blnFound As Boolean = False
Dim strProduct(,) As String = { _
{"Lawn Chair",
"1144"}, _
{"Lawn Table",
"1166"}, _
{"Golf Clubs",
"4466"}}
'Set the output label to blank
lblDescription.Text = ""
'Start the search - stop if we find the
value
' or
if we have looked at all of the rows
Do Until blnFound = True Or intRow > 2
'Compare the textbox value to intRow,
column 1
If txtProduct.Text = _
strProduct(intRow, 1) Then
blnFound = True
'Found it, display intRow, column 0
lblDescription.Text =
strProduct(intRow, 0)
Else
intRow += 1
End If
'Test if Product Number was Found
If blnFound = False Then
MessageBox.Show("Product Code Not
Found", _
"Product Code Error", _
MessageBoxButtons.OK, _
MessageBoxIcon.Exclamation)
lblDescription.Text = ""
txtProduct.Focus()
txtProduct.SelectAll()
End If
End Sub
Additional coding task.
· Add a column to display the Cost of products – it is okay to store this value as string.
· Modify the declaration of the table.
· Modify the form to provide a label named lblCost that will display the cost of the products.
· Modify the lookup procedure to display the correct cost to the label.
END OF NOTES