| 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 | |
4-7: Exercises
Exercise 4-9 (continued)
In the code window select the first Age: textbox
window and then select the Validating event. (Forget
how -
) The following
subprogram skeleton will appear:
Private Sub txtAge1_Validating( _
ByVal sender As Object, _
ByVal e As
System.ComponentModel.CancelEventArgs) _
Handles
txtAge1_Validating
End
Sub
This event has two arguments, namely the variable sender which is declared as Object and e which is declared as System.ComponentModel.CancelEventArgs. We're only concerend with the second argument, e.
e is an object of the CancelEventArgs class. It has only one property (you'll see it when you start typing the code), which is named Cancel. If the data typed by the user is invalid the code you write should assign the value True to the Cancel property of e. This means that the attempt by the user to enter data in the textbox is cancelled. The value of the Cancel property is used internally by Visual Basic to prevent the user from leaving (shifting focus from) the textbox.
By default the value of the e.Cancel property is False, meaning that the data entry should not be cancelled.
The Validating event code for the Age1 textbox will therefore implement steps such as these ...
If the text is not the null string
If the text is not numeric then
display a
message box advising of the error
assign True to the Cancel
variable
otherwise (i.e. the text is a number)
convert the text to an integer part
if the number <=
0
display a message box advising that the value must be
> 0
assign True to the Cancel variable
otherwise if the Junior
event is selected and the age > 15
display a message
box advising that the value must be < 16
assign True to the Cancel
variable
Notice that if the text is the null string the if statements would not be executed and the event processing would end immediately without any error message.
Notice also that if the text is numeric the value might possibly have a fractional part, 16.7 for example, and the code would truncate such a value, i.e. convert 16.7 to 16 for example.
If the value is valid (i.e. the null string or a valid number) no message box is displayed, and the default value of the Cancel variable (i.e. False) is left unchanged.
We leave it to you to implement this event and also the Validating event for the second Age: textbox.