Visual Basic 2008 Programming: Business Applications with a Design Perspective
Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9
Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Appendix A Appendix B Appendix C Home
Loading
Last change: February 13 2016 18:48:19.

 Chapter in PDF

Table of Contents

Chapter 8: Arrays and Their Uses
Last change: February 13 2016 18:48:01.
<<PreviousNext>>

8.3   Control Arrays

This section discusses issues pertaining to handling controls as an array. You may encounter situations in which the visual interface design of your application requires the flexibility of control arrays. For example, consider the data entry screen for a program that evaluates the merits of an investment project. The user will enter the project life in years and then enter the cash flow for each year. The cash flows should be entered in text boxes, the number of which should vary based on the project life. A sample visual interface is shown in Figure 8-1. As you can see, the number of text boxes for the cash flows and their related labels depend on the number of years specified in the text box for the project life. The text boxes for cash flows should appear when the user clicks the Ready button or presses the Enter key in the text box for the project life (“how many years”). There are at least two challenges:

Before considering these challenges, take a look at the controls drawn to the form at design time in the following table first:

Control Name Remark
Label Label1 To display the text “How many periods”
Text box txtPeriods To enter number of periods (project life in years)
Button btnReady To invoke the procedure to add labels and text boxes
Button btnCompute To invoke the computation routine

Figure 8-1
Visual interface for the Cashflow Entry Form

Adding Controls to the Form by Code

VB controls are objects. They can be added to the form similar to other objects such as the stream reader. The main difference is that controls should be visible in the form; therefore, in the code, you must specify those properties that pertain to the visual elements—for example, size, location, and text properties. Also, the form has a Controls collection, as explained in Chapter 7. A newly added control must also be added to that collection, using the Add method. The following code should add a label to a form.

Dim lblSample As Label LblSample = New Label With lblSample .Text = “This is a sample” .Location = New Point(5, 20) ‘Set Left at 5 and Top at 20 .AutoSize = True ‘So that I don’t have to specify its size End With Me.Controls.Add(lblSample)

The Dim statement declares that lblSample is of the Label type.  The next statement creates a new label. The statements within the With … End With block set up the visual properties for the label. Its Location property is assigned a Point object at (5, 20), which is five pixels from the left margin, and 20 pixels from the top margin of its container (the form). This statement is equivalent to assigning 5 to the label’s Left property, and 20 to its Top property. The last statement adds lblSample to the form’s Controls collection.

Tip
If you have more than one control to add to the form, you can use the AddRange method that expects a collection of controls as its parameter. A collection of controls can be created with the following syntax:
New Control(){Control1, Control2, …}
The following statement will add Label1 and Label2 to the form.
Me.Controls.AddRange(New Control() {Label1, Label2})

You may wonder why you use a separate statement to create a new label, instead of using the New keyword in the Dim statement. In this case, either way will produce the same result; however, keep in mind that there is some difference between the two approaches. When a new label is created using an assignment statement with the New keyword, as in you code, each time this statement is executed, a new label is created. If it is placed in a loop, many labels can be created. If you use the New keyword in the Dim statement, you create the label at that time. Only when that statement is invoked again will another label be created.

Creating a Specified Number of Text Boxes

Back to the cash flow project, assume that the number of periods specified is N. You will then need to generate N + 1 text boxes (period 0 for initial investment). You can use a For loop in which a text box is created. The code can appear as follows:

Dim txtCashflow() As TextBox Dim I as Integer Dim N as Integer
For I = 0 To N txtCashflow(I) = New TextBox ‘Create a new text box With txtCashflow(I) .Size = New Size(80, 20) 'Width=80; Height=20 .Location = New Point(95, 50 + I * 25) .TabIndex = 1 + I 'Set the tabindex .TextAlign = HorizontalAlignment.Right 'Align the text on the right End With Me.Controls.Add(txtCashflow(I)) Next I

With this code, you are able to generate the desired number of text boxes. Note that each element of the text box array is created by the first statement within the For loop. This is the way to create a control array in VB 2008, which does not support the use of the New keyword to create a control array.

Complete Code to Create the Project Interface

You are now ready to develop the code to create the visual interface for your cash flow project. You will place the code in a sub procedure for the reason to be explained later. The procedure appears as follows:

Dim txtCashflow() As TextBox Dim lblCashflow As Label Private Sub ShowBoxes() Dim I As Integer Dim N As Integer Dim LL, LT As Integer Dim Top As Integer
N = CInt(Val(txtPeriods.Text)) If N = 0 Then Exit Sub 'Do nothing if N is zero ReDim txtCashflow(N) LL = lblPeriods.Left LT = txtPeriods.Left Top = lblPeriods.Top + 25 For I = 0 To N lblCashflow = New Label With lblCashflow If I = 0 Then .Text = "Initial investment" Else .Text = "Period " & I End If .AutoSize = True .Location = New Point(LL, Top + I * 25) End With txtCashflow(I) = New TextBox 'Create a new textbox With txtCashflow(I) .Size = New Size(80, 20) 'Width=80; Height=20 .Location = New Point(LT, Top + I * 25) .TabIndex = 1 + I 'Set the tabindex .TextAlign = HorizontalAlignment.Right 'Align the text on the right End With Me.Controls.AddRange(New Control() {lblCashflow, txtCashflow(I)}) Next I btnReady.TabIndex = N + 2 btnCompute.TabIndex = N + 3 End Sub

Notice the last statement within the loop. The two newly created controls (the label and text box) are now added to the form’s Controls collection, using the AddRange method instead of the Add method. The AddRange method expects a control array as its parameter. The control array is created with exactly the same syntax as creating any data array as explained in Section 8.1. Notice also the two statements below the loop. They set the TabIndex properties for the two buttons that were drawn on the form at design time so that the user can tab through the text boxes before running into the buttons.

Invoking the ShowBoxes Sub

The ShowBoxes sub can be invoked in two different events: when the user clicks on the Ready button, or when the user presses the Enter key in the text box named txtPeriods. These two event procedures can be coded as follows:

Private Sub btnReady_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReady.Click ShowBoxes() End Sub Private Sub txtPeriods_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtPeriods.KeyPress If e.KeyChar = ControlChars.Cr Then ShowBoxes() e.Handled = True 'No further process needed End If End Sub

Referencing Elements in a Control Array

As you may have already noticed in the preceding example, elements in a control array are referenced by an index, just like any variables. For example, txtCashFlow(I) refers to the i+1th element in the array. Suppose the user clicks the Compute button after entering relevant data in the cash flow boxes. You obtain the values entered in the text boxes and then assign them to an array with the following code:

Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click Dim I As Integer Dim CashFlow() As Double Dim N As Integer N = cllCashflow.Count - 1 ReDim CashFlow(N) For I = 0 To N CashFlow(I) = Val(txtCashflow.Text) Next I ‘Other statements End Sub

Additional Note

The labels and text boxes that you created in the preceding examples are not capable of handling events. This capability can be important. For example, you may want to use the KeyPress event to ensure that keys entered in the text boxes are numeric only. With minor modifications, you can add this capability. This topic is discussed in Chapter 12, “Object-Based Programming.”

Last change: February 13 2016 18:48:02.
  1. Simplified Selection
  2. Table Look Up
  3. Tracking Random Occurrences
  4. Simulation
  5. Random Sampling Without Replacement
  6. Sorting and Searching
  • 8.3 Control Arrays
  • 8.4 Two-Dimensional Arrays
    1. Tables
    2. Matrices
    3. Game Boards
    4. <<PreviousNext>>