| 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)
The form object itself has a New event which is executed automatically by Visual Basic whenever a form is first created. Often this event can be used to assign initial values to variables. However, in this case we cannot use it since at the time it is executed there is no value in the Text property of the Initial Capital textbox. The value we need is entered by the user at some later time.
What we need is a means of initialising the variable whenever the user has entered a value in the textbox and then interacts with some other object in the interface. For example, the user might enter the capital value and then next enter the interest rate. Alternatively the user might enter the capital value and then click the Next Yr. button. Note that we do not want to initialize the variable until after the user has finished changing it, as implied by the user beginning to interact with a different control object.
Visual Basic provides events that are executed whenever the user either begins interacting with an object or switches to interact with a different object. An object is said to "have focus" when a user interacts with it. Thus when a user begins interacting with an interface object the GotFocus event for that object is executed and when the user switches to interact with a different object the LostFocus event is executed. (The GotFocus event of the new object the user interacts with is also executed.)
In this case we should assume that whenever the Initial Capital textbox has lost focus it means the initial capital value has been changed and hence the value of the capital variable should be (re)initialized.
In the code tab select txtInitialCap from the Class Names list and then select the LostFocus event from the Method Name list. You should enter the following statements:
Private Sub txtInitialCap_ LostFocus( ... ) Handles
txtInitialCap.LostFocus
'
' reinitialise the capital
variable since probably it was changed
'
capital =
Convert.ToDouble(txtInitialCap.Text)
End Sub
Note that the capital variable can be used in this event because it has been declared globally. It should not be declared locally in this event.