Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Chapter 4 Decisions and Conditions Programming In Visual Basic.NET."— Presentation transcript:

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

2 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 2 If Statements Used to make decisionsUsed to make decisions If true, only the Then clause is executed, if false, only Else clause, if present, is executedIf 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 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

3 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 3 If…Then…Else – General Form If (condition) Then statement(s) [ElseIf (condition) Then statement(s)] [Else statement(s)] End If Condition True False StatementStatement

4 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 4 If…Then…Else - Example unitsDecimal = Decimal.Parse(unitsTextBox.Text) If unitsDecimal < 32D Then freshmanRadioButton.Checked = True Else freshmanRadioButton.Checked = False End If

5 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 5 Conditions 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 Page 142 for ANSI Chart, case matters)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 lettersNumbers are always less than letters –300ZX is less than Porsche

6 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 6 The Six Relational Operators Greater Than>Greater Than> Less Than<Less Than< Equal To=Equal To= Not Equal To<>Not Equal To<> Greater Than or Equal To>=Greater Than or Equal To>= Less Than or Equal to<=Less Than or Equal to<=

7 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 7 ToUpper and ToLower Methods Use ToUpper and ToLower methods of the String class to return the uppercase or lowercase equivalent of a string, respectivelyUse 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

8 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 8 Compound Conditions Join conditions using logical operatorsJoin conditions using logical operators –OrIf one or both conditions True, entire condition is True –AndBoth conditions must be True for entire condition to be True –NotReverses the condition, a True condition will evaluate False and vice versa ORTF T F TT TF Condition 1 Condition 2 ANDTF T F TF FF Condition 1 Condition 2

9 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 9 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

10 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 10 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

11 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 11 If tempInteger > 32 Then If tempInteger > 80 Then commentLabel.Text = "Hot" Else commentLabel.Text = "Moderate" End If Else commentLabel.Text = "Freezing" End If Nested If Statements

12 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 12 Using If Statements with Radio Buttons & Check Boxes Instead of coding the CheckedChanged events, use If statements to see which are selectedInstead 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 buttonPlace 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

13 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 13 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 methodFor 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 lineVB will wrap longer messages to a second line Include ControlChars to control the line length and position of the line breakInclude ControlChars to control the line length and position of the line break

14 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 14 ControlChars Constants (p 152) ConstantDescription CRCarriage Return CRLFCarriage Return + Line Feed NewLineCarriage Return + Line Feed TabTab Character NullCharCharacter with a Value of Zero QuoteQuotation Mark Character

15 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 15 Message Box - Multiple Lines of Output ControlChars.NewLine Used to force to next line

16 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 16 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)

17 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 17 Displaying Multiple Buttons Use MessageBoxButtons constants to display more than one button in the Message BoxUse 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 clickedMessage 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 methodDeclare a variable to hold an instance of the DialogResult type to capture the outcome of the Show method

18 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 18 Message Box - Multiple Buttons MessageBoxButtons.YesNo

19 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 19 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

20 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 20 Specifying a Default Button and Options Use a different signature for the Message Box Show method to specify a default buttonUse a different signature for the Message Box Show method to specify a default button Add the MessageBoxDefaultButton argument after the MessageBoxIcons argumentAdd the MessageBoxDefaultButton argument after the MessageBoxIcons argument Set message alignment with MessageBoxOptions argumentSet message alignment with MessageBoxOptions argument

21 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 21 Input Validation Check to see if valid values were entered by user before beginning calculationsCheck to see if valid values were entered by user before beginning calculations Check for a range of values (reasonableness)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)Check for a required field (not blank) –If nameTextBox.Text <> "" Then...

22 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 22 Performing Multiple Validations Use nested If statement to validate multiple values on a formUse nested If statement to validate multiple values on a form –Examine example on Page 156 Use Case structure to validate multiple valuesUse 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

23 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 23 Sharing an Event Procedure Add events to the Handles clause at the top of an event procedureAdd 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 argumentKey to using a shared event procedure is the sender argument –Cast (convert) sender to a specific object type using the CType function

24 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 24 Calling Event Procedures Reusable codeReusable code General FormGeneral Form –[Call] ProcedureName ( ) –Keyword Call is optional and rarely used ExamplesExamples –Call clearButton_Click (sender, e) OR –clearButton_Click (sender, e)

25 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 25 Debugging (p 169) Debug MenuDebug Menu Debug ToolbarDebug Toolbar Toggle BreakPoints on/off by clicking Editor's gray left margin indicatorToggle BreakPoints on/off by clicking Editor's gray left margin indicator Step through Code, Step Into, Step OverStep through Code, Step Into, Step Over View the values of properties, variables, mathematical expressions, and conditionsView the values of properties, variables, mathematical expressions, and conditions

26 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 26 Debugging (cont.) Output WindowOutput Window Locals WindowLocals Window Autos WindowAutos Window

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

28 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 28 Writing to the Output Window Debug.WriteLine(TextString)Debug.WriteLine(TextString) Debug.WriteLine(Object)Debug.WriteLine(Object) Debug.WriteLine("calculateButton procedure entered") Debug.WriteLine(quantityTextBox)

29 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 29 Breakpoints Toggle Breakpoints On/Off by clicking in Editor's gray left margin indicator

30 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 30 Checking the Current Value of Expressions Place mouse pointer over variable or property to view current value

31 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 31 Locals Window Shows values of local variables that are within scope of current statement

32 © 2005 by The McGraw-Hill Companies, Inc. All rights reserved. 4- 32 Autos Window Automatically adjusts to show variables and properties that appear in previous and next few lines

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


Download ppt "Chapter 4 Decisions and Conditions Programming In Visual Basic.NET."

Similar presentations


Ads by Google