| Chapter 3- Data Types and Operators | Boolean Expressions Page 2 3 4 |
| The If Statement Page 2 3 4 5 6 7 8 9 | |
| Arithmetic Operations Page 2 3 4 5 6 | Boolean Operators and Nested If Statements Page 2 3 4 5 6 7 |
| Events and Sequential Processing Page 2 3 4 5 | More Examples Page 2 3 4 5 6 7 8 9 10 11 12 |
| Datatypes and Conversions Page 2 3 4 5 6 7 | Using Check Box and Option Controls Page 2 3 4 5 6 7 8 9 10 |
| Variable Declarations - Local and Global Page 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | Exercises Page 2 3 4 5 6 7 8 |
| Chapter 4- Selection Statements | Review Questions |
| Introduction | |
3-5: Variable Declarations (continued)
Declaring Global Variables
In cases like this Visual Basic allows for variables to be declared outside of any subprogram, but within the Form class. Usually you make such declarations at the very beginning of the program code but after the Public Class Form1 declaration. The syntax is slightly different - you should use the keyword Private rather than Dim as shown next:
Public Class Form1
Private year as
Integer
Private Sub btnNextYr_Click( ... )
year =
year + 1
txtYear.Text = year
End Sub
...
(etc)
End Class
Run this program and you should find that the value in the Year textbox increases as expected every time the button is clicked.
Unlike a local variable, the variable year, because it is declared outside any subprogram exists as long as the form object is active. Moreover, the variable is accessible inside any event procedure that is defined in the code. Thus in the example, although year is not declared inside the btnNextYr_Click event it is still possible to use the variable in an expression and to change its value within the event.
The calculation of the capital must be done in a similar fashion. The capital from the previous year must have the interest for the current year added to it, so the statement will be
capital = capital + interestAmount
Therefore the variable capital cannot be declared locally because its value will be initialised to 0 each time the event is executed. The code therefore becomes
Public Class Form1
Private year as
Integer
Private capital as Double
Private Sub btnNextYr_Click( ...
)
Dim interestAmount as Double
Dim interestRate As
Double
'
' Assign value to InterestRate variable from text
property
'
interestRate = CDbl(txtRate.Text)
'
' Calculate new
values for year, interest amount and capital
'
year = year +
1
interestAmount = capital * interestRate
capital = capital +
interestAmount
'
' Assign the values to the textboxes
'
txtYear.Text
= year
txtInterest.Text = interestAmount
txtCapital.Text =
capital
End Sub
... (etc)
End Class
where we have also declared the local variable interestAmount and assigned it the value
capital * interestRate
and assigned the calculated values to the Text properties of the textboxes.