chapter 4 decisions and conditions

Upload: vikrantkumarsrivastava

Post on 30-May-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/14/2019 Chapter 4 Decisions and Conditions

    1/33

    Chapter 4Chapter 4

    Decisions andDecisions and

    ConditionsConditions

    Programming InProgramming InVisual Basic .NETVisual Basic .NET

  • 8/14/2019 Chapter 4 Decisions and Conditions

    2/33

    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 ElseIf true, only the Then clause is executed, if false, only Elseclause, if present, is executedclause, if present, is executed

    Block IfThenElse must always conclude with End IfBlock IfThenElse 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

  • 8/14/2019 Chapter 4 Decisions and Conditions

    3/33

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

    IfThenElse General FormIfThenElse General Form

    If(condition) Then

    statement(s)

    [ElseIf(condition) Then

    statement(s)][Else

    statement(s)]

    End If

    ConditionConditionTrueTrue

    FalseFalse

    StatementStatement StatementStatement

  • 8/14/2019 Chapter 4 Decisions and Conditions

    4/33

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

    IfThenElse - ExampleIfThenElse - Example

    unitsDecimal = Decimal.Parse(unitsTextBox.Text)unitsDecimal = Decimal.Parse(unitsTextBox.Text)

    If unitsDecimal < 32D ThenIf unitsDecimal < 32D Then

    freshmanRadioButton.Checked = TruefreshmanRadioButton.Checked = True

    ElseElse

    freshmanRadioButton.Checked = FalsefreshmanRadioButton.Checked = False

    End IfEnd If

  • 8/14/2019 Chapter 4 Decisions and Conditions

    5/33

    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 (seeStrings can be compared, enclose strings in quotes (seePage 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

  • 8/14/2019 Chapter 4 Decisions and Conditions

    6/33

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

    The Six Relational OperatorsThe Six Relational Operators

    Greater ThanGreater Than >>

    Less ThanLess Than =>=

    Less Than or Equal toLess Than or Equal to

  • 8/14/2019 Chapter 4 Decisions and Conditions

    7/33 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 toUse 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

    IfnameTextBox.Text.ToUpper( ) = "Basic" Then

    ' Do something.

    EndIf

  • 8/14/2019 Chapter 4 Decisions and Conditions

    8/33 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 TrueBoth conditions must be True

    for entire condition to be Truefor entire condition to be True

    NotNot Reverses the condition, aReverses the condition, a

    True condition will evaluate FalseTrue condition will evaluate False

    and vice versaand vice versa

    OR T F

    T

    F

    T T

    T F

    Condition 1

    Condi t

    ion2

    AND T F

    T

    F

    T F

    F F

    Condition 1

    C

    ondi t

    ion2

  • 8/14/2019 Chapter 4 Decisions and Conditions

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

    Compound Condition ExamplesCompound Condition Examples

    IfmaleRadioButton.Checked And_

    Integer.Parse(ageTextBox.Text) < 21 Then

    minorMaleCountInteger += 1

    End If

    IfjuniorRadioButton.Checked Or seniorRadioButton.Checked Then

    upperClassmanInteger += 1

    End If

  • 8/14/2019 Chapter 4 Decisions and Conditions

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

    Combining And and Or ExampleCombining And and Or Example

    IfsaleDecimal > 1000.0 Or discountRadioButton.Checked _

    And stateTextBox.Text.ToUpper( ) "CA" Then

    ' Code here to calculate the discount.End If

  • 8/14/2019 Chapter 4 Decisions and Conditions

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

    IftempInteger > 32 Then

    IftempInteger > 80 Then

    commentLabel.Text = "Hot"

    Else

    commentLabel.Text = "Moderate"

    EndIf

    ElsecommentLabel.Text = "Freezing"

    End If

    Nested If StatementsNested If Statements

  • 8/14/2019 Chapter 4 Decisions and Conditions

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

    Using If Statements with Radio ButtonsUsing If Statements with Radio Buttons

    & Check Boxes& Check Boxes

    Instead of coding the CheckedChanged events, use IfInstead 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, suchPlace 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.IftestCheckBox.Checked Then

    messageLabel.Text = "Check box is checked"

    End If

    End Sub

  • 8/14/2019 Chapter 4 Decisions and Conditions

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

    Enhancing Message BoxesEnhancing Message Boxes

    For longer, more complex messages, store the messageFor longer, more complex messages, store the message

    text in a String variable and use that variable as antext 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 andInclude ControlChars to control the line length and

    position of the line breakposition of the line break

  • 8/14/2019 Chapter 4 Decisions and Conditions

    14/33

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

    ControlChars ConstantsControlChars Constants

    (p 152)(p 152)

    Constant Description

    CR Carriage Return

    CRLF Carriage Return + Line Feed

    NewLine Carriage Return + Line Feed

    Tab Tab Character

    NullChar Character with a Value of ZeroQuote Quotation Mark Character

  • 8/14/2019 Chapter 4 Decisions and Conditions

    15/33

    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

  • 8/14/2019 Chapter 4 Decisions and Conditions

    16/33

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

    Message String ExampleMessage 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)

  • 8/14/2019 Chapter 4 Decisions and Conditions

    17/33

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

    Displaying Multiple ButtonsDisplaying Multiple Buttons

    Use MessageBoxButtons constants to display more thanUse MessageBoxButtons constants to display more than

    one button in the Message Boxone button in the Message Box

    Message Box's Show method returns aMessage Box's Show method returns a DialogResultDialogResult

    object that can be checked to see which button the userobject that can be checked to see which button the user

    clickedclicked

    Declare a variable to hold an instance of theDeclare 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

  • 8/14/2019 Chapter 4 Decisions and Conditions

    18/33

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

    Message Box - Multiple ButtonsMessage Box - Multiple Buttons

    MessageBoxButtons.YesNo

  • 8/14/2019 Chapter 4 Decisions and Conditions

    19/33

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

    Declaring a Variable for the MethodDeclaring a Variable for the Method

    ReturnReturn

    Dim whichButtonDialogResult As DialogResult

    whichButtonDialogResult = MessageBox.Show _("Clear the current order figures?", "Clear Order", _

    MessageBoxButtons.YesNo, MessageBoxIcon.Question)

    IfwhichButtonDialogResult = DialogResult.Yes Then

    ' Code to clear the order.End If

  • 8/14/2019 Chapter 4 Decisions and Conditions

    20/33

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

    Specifying a Default Button andSpecifying a Default Button and

    OptionsOptions

    Use a different signature for the Message Box ShowUse a different signature for the Message Box Show

    method to specify a default buttonmethod to specify a default button

    Add the MessageBoxDefaultButton argument after theAdd the MessageBoxDefaultButton argument after the

    MessageBoxIcons argumentMessageBoxIcons argument Set message alignment with MessageBoxOptionsSet message alignment with MessageBoxOptions

    argumentargument

  • 8/14/2019 Chapter 4 Decisions and Conditions

    21/33

    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 beforeCheck 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 ...

  • 8/14/2019 Chapter 4 Decisions and Conditions

    22/33

    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 aUse 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 CaseNo limit to number of statements that follow a Case

    statementstatement

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

    Use the wordUse the word ToTo to indicate a range of constantsto indicate a range of constants

  • 8/14/2019 Chapter 4 Decisions and Conditions

    23/33

    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 eventAdd events to the Handles clause at the top of an event

    procedureprocedure

    Allows the procedure to respond to events of otherAllows the procedure to respond to events of other

    controlscontrols

    Key to using a shared event procedure is theKey to using a shared event procedure is the sendersender

    argumentargument

    Cast (convert)Cast (convert)sendersenderto a specific object type using theto a specific object type using the

    CType functionCType function

  • 8/14/2019 Chapter 4 Decisions and Conditions

    24/33

    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)

  • 8/14/2019 Chapter 4 Decisions and Conditions

    25/33

    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 leftToggle BreakPoints on/off by clicking Editor's gray leftmargin indicatormargin indicator

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

    View the values of properties, variables, mathematicalView the values of properties, variables, mathematical

    expressions, and conditionsexpressions, and conditions

  • 8/14/2019 Chapter 4 Decisions and Conditions

    26/33

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

    DebuggingDebugging (cont.)(cont.)

    Output WindowOutput Window

    Locals WindowLocals Window

    Autos WindowAutos Window

  • 8/14/2019 Chapter 4 Decisions and Conditions

    27/33

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

    Debug Menu and ToolbarDebug Menu and Toolbar

  • 8/14/2019 Chapter 4 Decisions and Conditions

    28/33

  • 8/14/2019 Chapter 4 Decisions and Conditions

    29/33

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

    BreakpointsBreakpoints

    Toggle Breakpoints On/Off by clickingToggle Breakpoints On/Off by clicking

    in Editor's gray left margin indicatorin Editor's gray left margin indicator

  • 8/14/2019 Chapter 4 Decisions and Conditions

    30/33

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

    Checking the Current Value ofChecking the Current Value of

    ExpressionsExpressions

    Place mouse pointer over variable or

    property to view current value

  • 8/14/2019 Chapter 4 Decisions and Conditions

    31/33

    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

  • 8/14/2019 Chapter 4 Decisions and Conditions

    32/33

    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

  • 8/14/2019 Chapter 4 Decisions and Conditions

    33/33

    4 33