As I stated earlier in this chapter, a structure is a user-defined entity. In other words, you name it, define the variables that make it up, and then populate it, usually by creating an array based on the structure. Structures can be declared within a module or class but not within a procedure. A Structure begins with the keyword structure and ends with the End Structure statement. The basic syntax of a Structure is outlined below.
Structure StructureName Dim VariableName As DataType Dim VariableName As DataType . . . End Structure
Once defined, every variable defined within a structure is treated as a method. To see how to really work with structures, let's look at an example.
Create a new Visual Basic project.
Double-click on form1. The code editor will appear, displaying code for the form's Load event.
Enter the following statements just below the Public Class Form1 statement. These statements define a Structure that will hold employee data. The Structure is made up of two variables that store employee names and numbers.
Structure EmployeeNames Dim EmployeeName As String Dim EmployeeNumber As Integer End Structure
Enter the following statements inside the Load event procedure for the form. These statements declare two variables used later to control a For…Next loop and a display string.
Dim intCounter As Integer = 0 Dim strMessage As String = "Employee Name" & ControlChars.Tab & _ "Employee #" & ControlChars.CrLf
Create a small array based on the EmployeeNames structure that can hold information for three employees, as shown below.
Dim EmployeeDataArray(2) As EmployeeNames
Now populate the array with data for three employees, as shown below.
EmployeeDataArray(0).EmployeeName = "Alexander Ford" EmployeeDataArray(0).EmployeeNumber = 12345 EmployeeDataArray(1).EmployeeName = "William Ford" EmployeeDataArray(1).EmployeeNumber = 23456 EmployeeDataArray(2).EmployeeName = "Mollisa Ford" EmployeeDataArray(2).EmployeeNumber = 22335
Finally, add the following statements, which will loop through the EmployeeDataArray and display its contents.
For intCounter = 0 To UBound(EmployeeDataArray) strMessage = strMessage & _ EmployeeDataArray(intCounter).EmployeeName & ControlChars.Tab & _ EmployeeDataArray(intCounter).EmployeeNumber & ControlChars.CrLf
Next
MessageBox.Show(strMessage)
Trick | Ubound() is a built-in Visual Basic function that returns the upper limit of an array. |
Press F5 to run your application and you'll see, as demonstrated in Figure 5.10, that all of the employee names and numbers have been processed.
Figure 5.10: Managing large amounts of related data using an array based on a custom structure.