Chapter 4 Decisions and Conditions Programming In

Chapter 4
Decisions and
Conditions
Programming In
Visual Basic .NET
If Statements
• Used to make decisions
• If true, only the Then clause is executed, if false, only Else
clause, if present, is executed
• Block If…Then…Else must always conclude with End If
• Then must be on same line as If or ElseIf
• End If and Else must appear alone on a line
• Note: ElseIf is 1 word, End If is 2 words
4- 2
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
If…Then…Else – General Form
If (condition) Then
statement(s)
[ElseIf (condition) Then
statement(s)]
[Else
statement(s)]
End If
4- 3
Condition True
False
Statement
Statement
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
If…Then…Else - Example
unitsDecimal = Decimal.Parse(unitsTextBox.Text)
If unitsDecimal < 32D Then
freshmanRadioButton.Checked = True
Else
freshmanRadioButton.Checked = False
End If
4- 4
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Conditions
•
•
•
•
•
Test in an If statement is based on a condition
Six relational operators are used for comparison
Negative numbers are less than positive numbers
An equal sign is used to test for equality
Strings can be compared, enclose strings in quotes (see
Page 142 for ANSI Chart, case matters)
– JOAN is less than JOHN
– HOPE is less than HOPELESS
• Numbers are always less than letters
– 300ZX is less than Porsche
4- 5
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
The Six Relational Operators
•
•
•
•
•
•
4- 6
Greater Than
Less Than
Equal To
Not Equal To
Greater Than or Equal To
Less Than or Equal to
>
<
=
<>
>=
<=
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
ToUpper and ToLower Methods
• Use ToUpper and ToLower methods of the String class to
return the uppercase or lowercase equivalent of a string,
respectively
If nameTextBox.Text.ToUpper( ) = "Basic" Then
' Do something.
End If
4- 7
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Compound Conditions
Condition 1
Condition 2
Condition 2
• Join conditions using logical operators
OR T
F
– Or
If one or both conditions True,
T
T
T
entire condition is True
– And Both conditions must be True
F
T
F
for entire condition to be True
– Not
Reverses the condition, a
Condition 1
True condition will evaluate False
AND T
F
and vice versa
T
T
F
4- 8
F
F
F
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Compound Condition Examples
If maleRadioButton.Checked And _
Integer.Parse(ageTextBox.Text) < 21 Then
minorMaleCountInteger += 1
End If
If juniorRadioButton.Checked Or seniorRadioButton.Checked Then
upperClassmanInteger += 1
End If
4- 9
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Combining And and Or Example
If saleDecimal > 1000.0 Or discountRadioButton.Checked _
And stateTextBox.Text.ToUpper( ) <> "CA" Then
' Code here to calculate the discount.
End If
4- 10
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Nested If Statements
If tempInteger > 32 Then
If tempInteger > 80 Then
commentLabel.Text = "Hot"
Else
commentLabel.Text = "Moderate"
End If
Else
commentLabel.Text = "Freezing"
End If
4- 11
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Using If Statements with Radio Buttons
& Check Boxes
• Instead of coding the CheckedChanged events, use If
statements to see which are selected
• Place the If statement in the Click event for a Button, such
as an OK or Apply button
Private Sub testButton_Click(ByVal sender As System.Object, _
By Val e As System.EventArgs) Handles testButton.Click
' Test the value of the check box.
If testCheckBox.Checked Then
messageLabel.Text = "Check box is checked"
End If
End Sub
4- 12
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Enhancing Message Boxes
• For longer, more complex messages, store the message text
in a String variable and use that variable as an argument of
the Show method
• VB will wrap longer messages to a second line
• Include ControlChars to control the line length and
position of the line break
4- 13
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
ControlChars Constants
(p 152)
Constant
CR
CRLF
NewLine
Tab
NullChar
Quote
4- 14
Description
Carriage Return
Carriage Return + Line Feed
Carriage Return + Line Feed
Tab Character
Character with a Value of Zero
Quotation Mark Character
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Message Box - Multiple Lines of Output
ControlChars.NewLine
Used to force to next line
4- 15
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Message String Example
Dim formattedTotalString As String
Dim formattedAvgString As String
Dim messageString As String
formattedTotalString = totalSalesDecimal.ToString("N")
formattedAvgString = averageSalesDecimal.ToString("N")
messageString = "Total Sales: " & formattedTotalString _
& ControlChars.NewLine & "Average Sale: " & _
formattedAvgString
MessageBox.Show(messageString, "Sales Summary", _
MessageBoxButtons.OK)
4- 16
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Displaying Multiple Buttons
• Use MessageBoxButtons constants to display more than
one button in the Message Box
• Message Box's Show method returns a DialogResult
object that can be checked to see which button the user
clicked
• Declare a variable to hold an instance of the DialogResult
type to capture the outcome of the Show method
4- 17
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Message Box - Multiple Buttons
MessageBoxButtons.YesNo
4- 18
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Declaring a Variable for the Method
Return
Dim whichButtonDialogResult As DialogResult
whichButtonDialogResult = MessageBox.Show _
("Clear the current order figures?", "Clear Order", _
MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If whichButtonDialogResult = DialogResult.Yes Then
' Code to clear the order.
End If
4- 19
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Specifying a Default Button and
Options
• Use a different signature for the Message Box Show
method to specify a default button
• Add the MessageBoxDefaultButton argument after the
MessageBoxIcons argument
• Set message alignment with MessageBoxOptions argument
4- 20
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Input Validation
• Check to see if valid values were entered by user before
beginning calculations
• Check for a range of values (reasonableness)
– If Integer.Parse(hoursTextBox.Text) > 10 Then
MessageBox.Show("Too many hours")
• Check for a required field (not blank)
– If nameTextBox.Text <> "" Then ...
4- 21
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Performing Multiple Validations
• Use nested If statement to validate multiple values on a
form
– Examine example on Page 156
• Use Case structure to validate multiple values
– Simpler and clearer than nested If
– No limit to number of statements that follow a Case
statement
– When using a relational operator must use the word Is
– Use the word To to indicate a range of constants
4- 22
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Sharing an Event Procedure
• Add events to the Handles clause at the top of an event
procedure
– Allows the procedure to respond to events of other
controls
• Key to using a shared event procedure is the sender
argument
– Cast (convert) sender to a specific object type using the
CType function
4- 23
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Calling Event Procedures
• Reusable code
• General Form
– [Call] ProcedureName ( )
– Keyword Call is optional and rarely used
• Examples
– Call clearButton_Click (sender, e)
OR
– clearButton_Click (sender, e)
4- 24
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Debugging (p 169)
• Debug Menu
• Debug Toolbar
• Toggle BreakPoints on/off by clicking Editor's gray left
margin indicator
• Step through Code, Step Into, Step Over
• View the values of properties, variables, mathematical
expressions, and conditions
4- 25
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Debugging (cont.)
• Output Window
• Locals Window
• Autos Window
4- 26
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Debug Menu and Toolbar
4- 27
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Writing to the Output Window
• Debug.WriteLine(TextString)
• Debug.WriteLine(Object)
Debug.WriteLine("calculateButton procedure entered")
Debug.WriteLine(quantityTextBox)
4- 28
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Breakpoints
Toggle Breakpoints On/Off by clicking
in Editor's gray left margin indicator
4- 29
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Checking the Current Value of
Expressions
Place mouse pointer over variable or
property to view current value
4- 30
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Locals Window
Shows values of local variables that are
within scope of current statement
4- 31
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
Autos Window
Automatically adjusts to show variables
and properties that appear in previous
and next few lines
4- 32
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.
4- 33
© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.