Title: Decision Making
1Chapter 4
2Objectives
- Create constants to improve the readability of
code - Learn about the DateTime data type and perform
operations on dates - Create instances of check boxes, scroll bars,
group boxes and radio buttons - Group control instances
- Understand the Boolean data type
- Use If statements and Select Case statements to
make decisions
3Constants (1)
- User-defined constants like variables store a
value while the solution runs - Value of a constant does not change
- Similar to a literal value in that regard
- SyntaxPrivate Const constantname As type
initexpr - Const statement declares a constant
- As type clause defines the data type of the
constant - Required when Option Strict is enabled
- Initexpr defines the value of the constant
- You must assign a value to a constant when
declaring it
4Constants (2)
- Use constants to improve the readability of code
- Constants make a program more maintainable
because a constants value can be changed in one
place rather than many - Use standard prefixes for the constants you
declare to further improve readability
5Constants (Example)
- Declare a constant named csngPI having a data
type of Single and a value of 3.14159 - Private Const csngPI As Single 3.14159
- Declare a constant named csng2PI having a data
type of Single. The value uses another constant
and multiplied by the literal value 2 - Private Const csng2PI As Single csngPI 2
6Constants (Errors)
- Constants cannot be declared using variables
because a variable's value does not exist until
run time - The following constant declaration is illegal
because the declaration uses a variable - Private msngPI As Single 3.14159
- Private Const csng2PI As Single msngPI 2
7Importing a Class
- The Imports statement allows you to call the
methods of a class without specifying the full
namespace hierarchy - The following statement imports the
System.Convert namespace - Imports System.Convert
- Having imported the System.Convert namespace,
both of the following statements will work - mdatCurrent System.Convert.ToDateTime(txtDate.T
ext) - mdatCurrent ToDateTime(txtDate.Text)
8Working with Dates
- The DateTime data type stores date values
- Literal date values are surrounded by pound signs
() - The standard prefix for the DateTime data type is
"dat" - Remember to use IsDate to determine whether a
value can be converted to a date - Declaration examplePrivate mdatCurrent As
DateTime 3/22/2002 - Type conversion example
- mdatCurrent _ System.Convert.ToDateTime(txtDat
e.Text)
9DateTime Structure (Properties)
- Now - returns current date and time
- Today - returns current date
- Day, Month, Year - returns day, month, and year,
respectively - These properties store Integer values
- Hour, Minute, Second - returns time values
- These properties store Integer values
- DayOfWeek, DayOfYear - returns an Integer
containing the day of the week and the day of the
year respectively
10DateTime Structure (Example)
- Declare a DateTime variable
- Private mdatCurrent As DateTime
- Store the current date in the variable
- mdatCurrent System.DateTime.Today
- Store the current date and time in the variable
- mdatCurrent System.DateTime.Now
11DateTime Structure (Methods)
- AddHourse, AddMinutes, and AddSeconds adds fixed
time intervals to a date - Methods return a DateTime structure
- AddYears, AddMonths, and AddDays adds fixed date
intervals - Methods return a DateTime structure
- ToString converts a date to string
- ToLongDateString and ToShortDateString converts a
DateTime structure to a formatted date - ToLongTimeString and ToShortTimeString converts
time to formatted time - Subtract subtracts a date from another date
- Returns a DateTime structure containing the time
difference
12DateTime Structure (Example)
- Convert the current date to a string
- lblDate.text Today.ToLongDateString
- Add one day to the current date
- Private datNextDay As DateTime
Today.AddDays(1) - Add one month to the current date
- Private datNextMonth As DateTime _
- Today.AddMonths(1)
- Subtract one day from the current date
- Private datLastDay As DateTime
Today.AddDays(-1)
13When VB .NET Loads a Form (Constructors)
- When VB.NET initializes a form, or any class, the
New procedure executes - The New procedure is called a constructor
- The Win Form Designer places code to initialize
control instances in the New procedure - By calling the procedure named InitializeComponent
- Add your own code to perform custom
initialization after the call to
InitializeComponent
14Constructor (Example)
- The following shows a constructor with a
statement added (shown in bold) - Remember to add code after InitializeComponent()
- Public Sub New()
- MyBase.New()
- InitializeComponent()
- lblDate.Text Today.ToShortDateString
- End Sub
15Performing Calculations on Dates (1)
- The DateDiff function computes number of
intervals between two dates - Syntax
- Result DateDiff( interval, date1, date2 ,
firstdayofweek ,firstweekofyear )
16Performing Calculations on Dates (2)
- Interval argument is an enumeration
- Day, DayOfYear, Hour, Minute, Month, Quarter,
Second, Weekday, WeekOfYear, and Year - date1 and date2 arguments contain the two dates
used in the calculation - If date1 is greater than date2, then the result
is negative - Optional firstdayofweek argument specifies which
day of the week that VB .NET considers the first
day of the week - Optional firstweekofyear argument defines which
week is the first week of the year
17DateDiff Function (Example)
- Calculate the number of elapsed months and years
between two dates. Result is 22 months and 1
year - Private mdatStart, mdatEnd As DateTime
- Private mdblElapsed As Double
- mdatStart System.DateTime.Today
- mdatEnd System.DateTime.Today.AddMonths(22)
- mdblElapsed DateDiff(DateInterval.Month,
mdatStart, _ - mdatEnd,FirstDayOfWeek.Monday,FirstWeekOfYear.
Jan1) - mdblElapsed DateDiff(DateInterval.Year,
mdatStart, _ - mdatEnd,FirstDayOfWeek.Monday,FirstWeekOfYear.
Jan1)
18The DateTimePicker Control
- Allows the user to select date from calendar
DateTimePicker control
19The DateTimePicker Control (Properties)
- Font - controls the font appearing in the
control's list portion - CalendarFont - controls the font appearing in the
drop-down calendar - CalendarForeColor - controls the foreground color
of the drop-down calendar - Format - stores an enumeration defining the
appearance of the date - MaxDate, MinDate - defines the minimum and
maximum user-selectable dates - Value - stores current date and time
20DateTimePicker Control (Events)
- CloseUp event fires when user closes drop-down
calendar - ValueChanged event fires when the user changes
the Value property at run time
21Storing Values in a DateTimePicker
- Store the current date value and the maximum date
value in two DateTimePicker control instances - dtpStartDate.Value Today.AddDays(-1)
- dtpStartDate.MaxDate Today
- dtpEndDate.Value Today
- dtpEndDate.MaxDate Today
22The CheckBox Control
- Allows the user to select a yes / no response
- Also allows the user to select from a third
choice called indeterminate - Indeterminate usually indicates that no choice
has been made - CheckBox displays textual description along with
a box that can be checked or unchecked (or
indeterminate)
23CheckBox Control (Properties)
- CheckAlign - controls position of box within the
visible region of the control instance - CheckState - defines whether the box is checked,
not checked, or indeterminate - Text - defines the text the appearing in visible
region - TextAlign - defines the alignment of text within
the visible region - ThreeState - allows the CheckBox to store three
possible values instead of just two
24CheckBox Control (Events)
- CheckedChanged event fires whenever value of
Checked property changes - Example Setting the CheckState property
- chkInsurance.CheckState CheckState.Checked
- chkInsurance.CheckState CheckState.Unchecked
- chkInsurance.CheckState CheckState.Indeterminate
25ScrollBar Controls
- Used to select a value from a range of values
- Often used to represent a percentage
- Values are always integers
- Two controls work the same way
- HScrollBar appears horizontally
- Standard prefix is "hsb"
- VScrollBar appears vertically
- Standard prefix is "vsb"
- Value grows as scroll bar is moved downward
26ScrollBar Controls (Properties and Events)
- Properties
- Maximum and Minimum - defines the valid range
- Default values are 100 and 0 respectively
- Value - contains current value between the
defined range - Value must be between Minimum and Maximum
- SmallChange and LargeChange - controls amount of
change to Value property as user clicks control
instance region - Events
- ValueChanged event fires when user changes value
property.
27ScrollBar Behavior
Click here to change the Value property by
SmallChange
Click here to change the Value property by
LargeChange
Relative indicator of Value Property
28ScrollBar (ValueChanged Example)
- Store the scroll bar's value into the Label named
lblFuel when the value changes - Private Sub hsbFuel_ValueChanged(. . .)
- lblFuel.Text hsbFuel.Value.ToString
- End Sub
29The NumericUpDown Control
- Similar to scroll bars
- Displays a value within a range of values
- Displays an adjacent label containing the current
value - Supports same fundamental properties as scroll
bars - Maximum, Minimum, Value properties
- ValueChanged event
- Standard prefix is "nud"
30The GroupBox Control
- Acts as a container for other control instances
such as RadioButton control instances - Other control instances can be grouped in a
GroupBox too - Properties
- BackColor and ForeColor define colors
- Text property defines text appearing at the top
of the visible region - Replaces the Frame control found in VB 6
31The RadioButton Control
- User selects one radio button from a group of
buttons - called a button group
- Button group contained by a GroupBox control
instance - To create multiple button groups, create multiple
GroupBox control instances
32The RadioButton Control (Caveats)
- Be careful when creating a button group
- Create RadioButtons inside of a group box
- Test by moving group box. Contained radio buttons
should move with the group box - If copying and pasting radio buttons, select
GroupBox before pasting radio button
33RadioButton Control (Properties and Events)
- Properties
- Text - contains text appearing next to radio
button - Checked - indicates whether radio button is
checked or not - Events
- CheckedChanged event fires when user clicks radio
button - Standard prefix is "rad"
34RadioButtons (Example)
RadioButtons in a ButtonGroup
35An Introduction to Boolean Data
- Boolean data operates similar to an on/off switch
- Standard prefix is "bln"
- Stores the values True and False
- Note that True and False are reserved words
- Most frequently used in decision making
statements - Declare a Boolean variable named mblnValid and
store the values True and False in the variable - Private mblnValid As Boolean
- mblnValid True
- mblnValid False
36Decision Making
- Group of statements called decision making
statements execute different blocks of code in
different circumstances - If some condition is True then
- Execute one group of statements.
- Otherwise
- Execute a different group of statements
- End of If statement.
37Comparison Operators (1)
- Conditional statements execute one group of
statements when a condition is True and another
group of statements when the condition is False - Conditional statements apply the following
comparison operators to test conditions - Equal to ()
- Not equal to (ltgt)
- Less than (lt)
- Greater than (gt)
- Less than or equal to (lt)
- Greater than or equal to (gt)
38Comparison Operators (2)
- Always produce a Boolean value as the result
- Comparison operators all have the same precedence
- Note that arithmetic operations are performed
before comparison operators are evaluated - Comparison operators are evaluated from left to
right - Comparison operators are evaluated after any
arithmetic operations are performed - Use parenthesis to override the default precedence
39Comparison Operators (Example)
mintResult ( mintValue1 2 ) lt ( mintValue2
1 )
mintResult ( 3 2 ) lt ( 5 1 )
mintResult ( 5 ) lt ( 5 1 )
Evaluate arithmetic expressions from left to right
mintResult ( 5 ) lt ( 4 )
Evaluate condition
mintResult False
5 is not less than 4 so the result is False
40The If Statement
- Conditional operators seldom used alone
- Conditions typically appear in a decision-making
statement (If statement) - Execute one group of statements only when
condition is True - Called a one-way If statement
- Statements executed in an If statement are called
a statement block
41One-Way If Statement (Syntax)
- If condition Then
- statements
- End If
- If statement tests value of condition
- statements execute only if condition is true
42One-Way If Statement (Example)
- Execute statements when the variable
mblnCondition is True - Note that the ( True ) is optional
- Private mblnCondition As Boolean
- mblnCondition True
- If mblnCondition True Then
- ' Statements
- End If
43One-Way If Statement (Logic Flow)
If condition Then Statements End
If Statements following the End If
condition
True
False
44Two-Way If Statement
- Executes one statement block when a condition is
True and another statement block when condition
is False - Also called an If Then Else statement
45Two-Way If Statement (Syntax)
- If condition Then
- statements (true)
- Else
- statements (false)
- End If
- The If statement tests the value of some
condition - statements (true) execute only if the condition
is true - statements (false) execute otherwise
- Execution continues at the statement following
the End If statement
46Two-Way If Statement (Example)
- Based on the contents of the check box named
chkInsurance, store values in a Label control
instance - If chkInsurance.CheckState CheckState.Checked
Then - lblInsuranceRate.Text cdblInsuranceRate.ToSt
ring - Else
- lblInsuranceRate.Text ""
- End If
47Two-Way If Statement (Logic Flow)
If condition Then Statements (true) Else
Statement (false) End If Statements following
the End If
condition
True
False
48Multi-Way If Statement
- Provides decision-making based on three or more
outcomes
49Multi-Way If Statement (Syntax)
- If condition1 Then
- statements
- ElseIf condition2 Then
- statements
- Else
- statements
- End If
50Multi-Way If Statement (Syntax Dissection)
- The If statement tests the value of some
condition - If condition1 is True the statements between the
If and the first ElseIf statements execute - If condition1 is False, then condition2 is tested
- If condition2 is True the statements following
the Else If execute - If no condition is True, the statements following
the Else execute - Execution continues at the statement following
the End If statement
51Multi-Way If Statement (Example)
If mintGrade gt 90 Then mstrLetterGrade
"A" ElseIf mintGrade gt 80 Then
mstrLetterGrade "B" ElseIf mintGrade gt 70 Then
mstrLetterGrade "C" ElseIf mintGrade gt 60
Then mstrLetterGrade "D" Else
mstrLetterGrade "F" End If
52Multi-Way If Statement (Logic Flow)
If condition1 Then statements ElseIf
condition2 Then elseifstatements
Else elsestatements End If Statements
following the End If
True
condition1
False
True
condition2
False
53Nested If Statements
- If statements can be nested inside each other as
shown in the following
If mintGrade gt 90 Then mstrLetterGrade "A"
If mintGrade gt 95 Then mstrNote
"Excellent" End If ElseIf mintGrade gt 80
Then mstrLetterGrade "B" ElseIf mintGrade gt
70 Then mstrLetterGrade "C" ElseIf
mintGrade gt 60 Then mstrLetterGrade
"D" Else mstrLetterGrade "F" End If
54The Select Case Statement (1)
- Limited form of If statement
- Use the Select Case statement when multiple cases
test against the same expression - Select Case testexpression
- Case expressionlist-1
- statement-block1
- Case expressionlist-2
- statement-block2
- Case expressionlist-n
- statement-blockn
- Case Else
- statements
- End Select
55The Select Case Statement (2)
- The testexpression is evaluated once when the
Select Case statement first starts - Testexpression is compared with expressionlist-1.
If the condition is true then statement-block1
executes - If the condition is not true expressionlist-2 is
tested - The process continues until no more conditions
remain to be tested - The statements after the optional Case Else
execute only if no conditions match the test
expression
56The Select Case Statement (Example)
- Assign a letter grade based on a numeric grade
- Select Case mintGrade
- Case 90 To 100
- mstrLetterGrade "A"
- Case 80 To 89
- mstrLetterGrade "B"
- Case 70 To 79
- mstrLetterGrade "C"
- Case 60 To 69
- mstrLetterGrade "D"
- Case Else
- mstrLetterGrade "F"
- End Select
57The Select Case Statement (Variations)
- Select Case statements can be written in
different ways using other comparison operators - Case Is comparisonoperator value
- Case Is gt 90
- A Case may contain a comma separated list of
values - Case 1, 3, 4
- A Case may contain a range of values
- Case 5 To 10
58The Select Case Statement (Example)
- The following Select Case statement illustrates a
comma separated list and a range of values - Select Case mintTest
- Case 1, 3, 4
- ' The value is 1, 3 or 4
- Case 5 To 10
- ' The value is 5, 6, 7, 8, 9
- ' or 10
- End Select
59Logical Operators (1)
- Purpose is to perform conjunction (and) and
disjunction (or) in an If statement - Meaning similar to meaning in English
- Logical operators have precedence
- Arithmetic operators are evaluated first
- Comparison operators are evaluated next
- Logical operators are evaluated last from left to
right in the following order - Not, And, Or, Xor
60Logical Operators (List)
- Not Unary operator to perform negation
- And Conjunction. Both conditions must be true
for the expression to be true - Or Disjunction. One or both conditions can be
true fro the expression to be true - Xor One condition must be true for the
expression to be true. If both conditions are
true then the condition is false