At the moment our box1Array has only one element – box1Array(0). We are now ready to add some more elements to our box1Array. Typically this is done when a user enters data in the program. In our program this occurs when the user clicks the “Add” button.
The following code is in the “Add” button’s Action event:
//add to listBox1
listBox1.cell(listbox1.lastIndex,1) = TextField2.text
//add to box1Array
box1Array(gbox1Count) = new box1Data
box1Array(gbox1Count).firstName = TextField1.text
box1Array(gbox1Count).lastName = TextField2.text
gbox1Count = gbox1Count + 1
TextField1.text = “”
TextField2.text = “”
The data is first added to the Listbox and then to the array.
However, before we can add the data to the array we have to make sure that the array element exists. To ensure this is the case we first “redim” the array using the current value of “gBox1Count”. When you “dim” or “redim” and array the number in the parentheses determines the number of elements the array will have. Use “redim” if the array has been previously dimensioned (“dimmed”). If this is the first time the “Add” button is pressed gBox1Count will = 0.
Next we make this element, just added to the array, a box1Data object using “new box1data”.
We now assign values to the element’s firstName and lastName properties.
Finally we add 1 to the value of gBox1Count. If gBox1Count was = 0 it will now = 1.
Each time the “Add” button is pressed a new element is added to both the Listbox and the array and gBox1Count is incremented by 1.
Let’s take another look at this diagram from the previous page:
Summary of the Process
1. Create a class with the desired properties
2. Create a module and add the array and a counter for the array as properties
3. Populate the Array
– A. Input the data
– B. Redimension the array to add a new element
– C. Create an instance of the class (NEW) for the new element
– D. Assign data values to the new element’s properties
– D.Increment the counter
Thanks to Greg Moore for the idea of this concise summary.
One of the beauties of using this type of data structure is that you can modify it easily. Suppose you now want to store and manage client email addresses as well as thier first and last names.
Just add a new property to the box1Data class like this: “emailAddress as string”.
Add a corresponding column to the Listbox and a field for the user to enter the email address on the Data Entry window.
Finally adjust the code in the “Save” and “Open” buttons to accommodate the email data and you’re set.
To see how to save and open the data in the box1Array array download the project and examine the “Save” and “Open button Action events code.
Be sure to read the Notes section in the Window1 and Window2 code editors.