+ All Categories
Home > Documents > Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

Date post: 20-Dec-2015
Category:
View: 230 times
Download: 5 times
Share this document with a friend
33
Chapter 4 Chapter 4 Decisions and Decisions and Conditions Conditions Programming In Programming In Visual Basic .NET Visual Basic .NET
Transcript
Page 1: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

Chapter 4Chapter 4Decisions and Decisions and

ConditionsConditions

Programming InProgramming In

Visual Basic .NETVisual Basic .NET

Page 2: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 2

If StatementsIf Statements

• Used to make decisionsUsed to make decisions• If true, only the Then clause is executed, if false, only Else If true, only the Then clause is executed, if false, only Else

clause, if present, is executedclause, if present, is executed• Block If…Then…Else must always conclude with End IfBlock If…Then…Else must always conclude with End If• Then must be on same line as If or ElseIfThen must be on same line as If or ElseIf• End If and Else must appear alone on a lineEnd If and Else must appear alone on a line• Note: ElseIf is 1 word, End If is 2 wordsNote: ElseIf is 1 word, End If is 2 words

Page 3: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 3

If…Then…Else – General FormIf…Then…Else – General Form

If (condition) Thenstatement(s)

[ElseIf (condition) Thenstatement(s)]

[Elsestatement(s)]

End If

ConditionCondition TrueTrue

FalseFalse

StatementStatement StatementStatement

Page 4: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 4

If…Then…Else - ExampleIf…Then…Else - Example

unitsDecimal = Decimal.Parse(unitsTextBox.Text)unitsDecimal = Decimal.Parse(unitsTextBox.Text)If unitsDecimal < 32D ThenIf unitsDecimal < 32D Then

freshmanRadioButton.Checked = TruefreshmanRadioButton.Checked = TrueElseElse

freshmanRadioButton.Checked = FalsefreshmanRadioButton.Checked = FalseEnd IfEnd If

Page 5: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 5

ConditionsConditions

• Test in an If statement is based on a conditionTest in an If statement is based on a condition• Six relational operators are used for comparisonSix relational operators are used for comparison• Negative numbers are less than positive numbersNegative numbers are less than positive numbers• An equal sign is used to test for equalityAn equal sign is used to test for equality• Strings can be compared, enclose strings in quotes (see Strings can be compared, enclose strings in quotes (see

Page 142 for ANSI Chart, case matters)Page 142 for ANSI Chart, case matters)– JOAN is less than JOHNJOAN is less than JOHN– HOPE is less than HOPELESSHOPE is less than HOPELESS

• Numbers are always less than lettersNumbers are always less than letters– 300ZX is less than Porsche300ZX is less than Porsche

Page 6: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 6

The Six Relational Operators The Six Relational Operators

• Greater ThanGreater Than >>

• Less ThanLess Than <<

• Equal ToEqual To ==

• Not Equal ToNot Equal To <><>

• Greater Than or Equal ToGreater Than or Equal To >=>=

• Less Than or Equal toLess Than or Equal to <=<=

Page 7: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 7

ToUpper and ToLower MethodsToUpper and ToLower Methods

• Use ToUpper and ToLower methods of the String class to Use ToUpper and ToLower methods of the String class to return the uppercase or lowercase equivalent of a string, return the uppercase or lowercase equivalent of a string, respectivelyrespectively

If nameTextBox.Text.ToUpper( ) = "Basic" Then ' Do something.

End If

Page 8: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 8

Compound ConditionsCompound Conditions

• Join conditions using logical operatorsJoin conditions using logical operators

– OrOr If one or both conditions True, If one or both conditions True, entire condition is Trueentire condition is True

– AndAnd Both conditions must be True Both conditions must be True for entire condition to be Truefor entire condition to be True

– NotNot Reverses the condition, a Reverses the condition, a True condition will evaluate False True condition will evaluate False

and vice versaand vice versa

OR T F

T

F

T T

T F

Condition 1

Con

diti

on 2

AND T F

T

F

T F

F F

Condition 1

Con

diti

on 2

Page 9: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 9

Compound Condition ExamplesCompound Condition Examples

If maleRadioButton.Checked And _ Integer.Parse(ageTextBox.Text) < 21 Then

minorMaleCountInteger += 1End If

If juniorRadioButton.Checked Or seniorRadioButton.Checked ThenupperClassmanInteger += 1

End If

Page 10: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 10

Combining And and Or ExampleCombining 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

Page 11: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 11

If tempInteger > 32 ThenIf tempInteger > 80 Then

commentLabel.Text = "Hot"Else

commentLabel.Text = "Moderate"End If

ElsecommentLabel.Text = "Freezing"

End If

Nested If StatementsNested If Statements

Page 12: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 12

Using If Statements with Radio Buttons Using If Statements with Radio Buttons & Check Boxes& Check Boxes

• Instead of coding the CheckedChanged events, use If Instead of coding the CheckedChanged events, use If statements to see which are selectedstatements to see which are selected

• Place the If statement in the Click event for a Button, such Place the If statement in the Click event for a Button, such as an OK or Apply buttonas 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 ThenmessageLabel.Text = "Check box is checked"

End IfEnd Sub

Page 13: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 13

Enhancing Message BoxesEnhancing Message Boxes

• For longer, more complex messages, store the message For longer, more complex messages, store the message text in a String variable and use that variable as an text in a String variable and use that variable as an argument of the Show methodargument of the Show method

• VB will wrap longer messages to a second lineVB will wrap longer messages to a second line

• Include ControlChars to control the line length and Include ControlChars to control the line length and position of the line breakposition of the line break

Page 14: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 14

ControlChars ConstantsControlChars Constants(p 152)(p 152)

Constant DescriptionCR Carriage ReturnCRLF Carriage Return + Line FeedNewLine Carriage Return + Line FeedTab Tab CharacterNullChar Character with a Value of ZeroQuote Quotation Mark Character

Page 15: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 15

Message Box - Multiple Lines of OutputMessage Box - Multiple Lines of Output

ControlChars.NewLineUsed to force to next line

Page 16: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 16

Message String ExampleMessage String Example

Dim formattedTotalString As StringDim formattedAvgString As StringDim messageString As String

formattedTotalString = totalSalesDecimal.ToString("N")formattedAvgString = averageSalesDecimal.ToString("N")messageString = "Total Sales: " & formattedTotalString _ & ControlChars.NewLine & "Average Sale: " & _ formattedAvgStringMessageBox.Show(messageString, "Sales Summary", _ MessageBoxButtons.OK)

Page 17: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 17

Displaying Multiple ButtonsDisplaying Multiple Buttons

• Use MessageBoxButtons constants to display more than Use MessageBoxButtons constants to display more than one button in the Message Boxone button in the Message Box

• Message Box's Show method returns a Message Box's Show method returns a DialogResultDialogResult object that can be checked to see which button the user object that can be checked to see which button the user clickedclicked

• Declare a variable to hold an instance of the Declare a variable to hold an instance of the DialogResultDialogResult type to capture the outcome of the Show methodtype to capture the outcome of the Show method

Page 18: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 18

Message Box - Multiple ButtonsMessage Box - Multiple Buttons

MessageBoxButtons.YesNo

Page 19: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 19

Declaring a Variable for the Method Declaring a Variable for the Method ReturnReturn

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

Page 20: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 20

Specifying a Default Button and Specifying a Default Button and OptionsOptions

• Use a different signature for the Message Box Show Use a different signature for the Message Box Show method to specify a default buttonmethod to specify a default button

• Add the MessageBoxDefaultButton argument after the Add the MessageBoxDefaultButton argument after the MessageBoxIcons argumentMessageBoxIcons argument

• Set message alignment with MessageBoxOptions Set message alignment with MessageBoxOptions argumentargument

Page 21: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 21

Input ValidationInput Validation

• Check to see if valid values were entered by user before Check to see if valid values were entered by user before beginning calculationsbeginning calculations

• Check for a range of values (reasonableness)Check for a range of values (reasonableness)

– If Integer.Parse(hoursTextBox.Text) > 10 ThenIf Integer.Parse(hoursTextBox.Text) > 10 Then

MessageBox.Show("Too many hours")MessageBox.Show("Too many hours")

• Check for a required field (not blank)Check for a required field (not blank)

– If nameTextBox.Text <> "" Then ...If nameTextBox.Text <> "" Then ...

Page 22: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 22

Performing Multiple ValidationsPerforming Multiple Validations

• Use nested If statement to validate multiple values on a Use nested If statement to validate multiple values on a formform

– Examine example on Page 156Examine example on Page 156

• Use Case structure to validate multiple valuesUse Case structure to validate multiple values

– Simpler and clearer than nested IfSimpler and clearer than nested If

– No limit to number of statements that follow a Case No limit to number of statements that follow a Case statementstatement

– When using a relational operator must use the word When using a relational operator must use the word IsIs

– Use the word Use the word ToTo to indicate a range of constants to indicate a range of constants

Page 23: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 23

Sharing an Event ProcedureSharing an Event Procedure

• Add events to the Handles clause at the top of an event Add events to the Handles clause at the top of an event procedureprocedure

– Allows the procedure to respond to events of other Allows the procedure to respond to events of other controlscontrols

• Key to using a shared event procedure is the Key to using a shared event procedure is the sendersender argumentargument

– Cast (convert) Cast (convert) sendersender to a specific object type using the to a specific object type using the CType functionCType function

Page 24: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 24

Calling Event ProceduresCalling Event Procedures

• Reusable codeReusable code• General FormGeneral Form

– [Call] ProcedureName ( )[Call] ProcedureName ( )– Keyword Call is optional and rarely usedKeyword Call is optional and rarely used

• ExamplesExamples– Call clearButton_Click (sender, e)Call clearButton_Click (sender, e)OROR– clearButton_Click (sender, e)clearButton_Click (sender, e)

Page 25: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 25

Debugging (p 169)Debugging (p 169)

• Debug MenuDebug Menu

• Debug ToolbarDebug Toolbar

• Toggle BreakPoints on/off by clicking Editor's gray left Toggle BreakPoints on/off by clicking Editor's gray left margin indicatormargin indicator

• Step through Code, Step Into, Step OverStep through Code, Step Into, Step Over

• View the values of properties, variables, mathematical View the values of properties, variables, mathematical expressions, and conditionsexpressions, and conditions

Page 26: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 26

Debugging Debugging (cont.)(cont.)

• Output WindowOutput Window

• Locals WindowLocals Window

• Autos WindowAutos Window

Page 27: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 27

Debug Menu and ToolbarDebug Menu and Toolbar

Page 28: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 28

Writing to the Output WindowWriting to the Output Window

• Debug.WriteLine(Debug.WriteLine(TextStringTextString))

• Debug.WriteLine(Debug.WriteLine(ObjectObject))

Debug.WriteLine("calculateButton procedure entered")Debug.WriteLine(quantityTextBox)

Page 29: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 29

BreakpointsBreakpoints

Toggle Breakpoints On/Off by clicking Toggle Breakpoints On/Off by clicking in Editor's gray left margin indicatorin Editor's gray left margin indicator

Page 30: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 30

Checking the Current Value of Checking the Current Value of ExpressionsExpressions

Place mouse pointer over variable or property to view current value

Page 31: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 31

Locals WindowLocals Window

Shows values of local variables that are within scope of current statement

Page 32: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 32

Autos WindowAutos Window

Automatically adjusts to show variables and properties that appear in previous and next few lines

Page 33: Chapter 4 Decisions and Conditions Programming In Visual Basic.NET.

© 2005 by The McGraw-Hill Companies, Inc. All rights reserved.4- 33


Recommended