Presentation is loading. Please wait.

Presentation is loading. Please wait.

Decisions and Conditions

Similar presentations


Presentation on theme: "Decisions and Conditions"— Presentation transcript:

1 Decisions and Conditions
Chapter 4 Decisions and Conditions

2 Decisions and Conditions
Block If statements Nested If statements Evaluating Conditions and Relational Operators Testing Values with option buttons & check boxes Validating input numeric fields Creating Message boxes Calling event procedures Debugging with breakpoints & stepping execution

3 Alternative courses of action are required in a program
Decision Making Alternative courses of action are required in a program The IF statement provides one of these structures There are two types of IF statements Single-line IF statement Multi-line IF statement Single-line IF statement example: If txtUserResponse = “Yes” Then curTaxableIncome = 0 Multi-line IF statement example: If intDependentNumber > 2 Then lblAnswer.caption = “Two Dependents” Else lblAnswer.cpation = “Not Two Dependents” End If

4 Symbol Meaning > Greater than < Less than = Equal to
Comparison Operators Symbol Meaning > Greater than < Less than = Equal to <= Less than or equal to >= Greater than or equal to <> Not equal to Expressions containing comparison operators always result in an answer that is either true or false. Example expressions using Visual Basic controls: txtName.text <> "Frockmeister" Val(txtAge.Text) > 25 optPrintForm.Value = True chkDiscardStyles.Value = False txtInterestRate.Text / 12 <= 0.05

5 IF Statement Structure (1)
Sleepy? Go to bed True False Form: If condition Then statement(s) End If

6 IF Statement Structure (2)
Is SAT > 600? Admit Do Not True False Form: If condition Then t-statement(s) Else f-statement(s) End If If Val(txtSat.text) > 600 Then Msgbox “Admit” Else Msgbox “Do Not Admit” End If

7 IF Statement Structure (3)
Form: If condition-1 Then If condition-2 Then t-statement-2 Else f-statement-2 End If f-statement-1 End If False Is SAT > 600? Do Not Admit True Is GPA > 3.75? Consider If Val(txtSat.text) > 600 Then If Val(txtGPA) > 3.75 Then Msgbox “Admit” Else Msgbox “Consider” End if Msgbox “Do Not Admit” End If

8 Comparing Numeric Variables & Constants Comparing Strings
Conditions Comparing Numeric Variables & Constants Comparing Strings Comparing text property of text boxes Uppercase and lowercase character comparisons Compound conditions When comparing values from text boxes with numeric values, be sure to first convert the text box data to a value. For example: If txtPrice.Text = curRetailPrice Then ... can result in an inaccurate comparison of a string and a currency value. Better to do this: If Val(txtPrice.Text) = curRetailPrice Then ... Also, if the text box is empty, then Val(textbox.text) is equal to zero. That can be very handy. It eliminates one possible error when you use a value in calculations When comparing strings, make sure you “negate” any potential problems with case not matching. Generally, you simply want the spelling to match. Compare these two slightly different conditions: If txtLastName.Text = “Smith” or If Lcase(txtLastName.Text) = “smith” You can use the logical operators of And, Or, and Not to form compound expressions such as: If (Ucase(txtLastName) = “SMITH” And Val(txtAge) > 25) Then... If (Val(txtAge.Text) = 0 Or txtLastName.Text = “”) Then ... Using parentheses around the conditional statement is optional but desirable

9 If & opt. buttons & check boxes
If chkFlag = True Then imgFlag.Visible = True If optDisplayForm Then frmSecond.Show When using option button controls, you don't have to compare it against True or False in a conditional expression. Because the value of 0 is considered False and all other values (1, for example) are considered True. So, instead of writing this: If optPrintSelection = True Then ··· you can write the following equivalent statement: If optPrintSelection Then ··· The preceding is an example of an implied condition This can work for check boxes also, except check boxes can also have the value of 2 (undefined) When comparing a literal string to a text box value, always compare “apples to apples” by converting both to either uppercase or lowercase. That way you avoid a mismatch based solely on capitalization an not spelling: If txtLastName.Text = "Smith" Then … will evaluate to false if the txtLastName contains SmITH or smith. Better way is to always do this type of operation: If Ucase(txtLastName.Text) = "SMITH" Then ··· or If Lcase(txtLastName.Text) = "smith" Then ...

10 If a1 <= a2 or a3 > a4 and a5 < a6 Then
Compound Conditions If a1 <= a2 or a3 > a4 and a5 < a6 Then And has precedence over Or All comparison operators have precedence over all logical operators Use parentheses to alter the order of evaluation Parentheses alter the order of evaluation and are good for explicitly documenting groupings or are good if you are unsure of precedence. If (curValue > 100) and (curValue < 200) Then lblMessage.Caption = "Value between 101 and 199" End If The following is a project called SimpleSample.vbp to illustrate the example on pages

11 "If" statement and option buttons

12 Displaying Messages in Message boxes
Special window displaying message to user Form: MsgBox “message” [,buttons][, “t.b. caption”] Example: MsgBox “Numeric ID only”, vbOkOnly, “Error” Buttons/Icons you can display: Intrinsic Name Value Description vbOKOnly 0 OK button only (default). vbOKCancel 1 OK and Cancel buttons. vbAbortRetryIgnore 2 Abort, Retry, and Ignore buttons. vbYesNoCancel 3 Yes, No, and Cancel buttons. vbYesNo 4 Yes and No buttons. vbRetryCancel 5 Retry and Cancel buttons. vbCritical 16 Critical message. vbQuestion 32 Warning query. vbExclamation 48 Warning message. vbInformation 64 Information message. vbDefaultButton1 0 First button is default (default). vbDefaultButton Second button is default. vbDefaultButton Third button is default. vbApplicationModal 0 Application modal message box vbSystemModal System modal message box.

13 Displaying a Message String
Use & to concatenate strings (“Concatenate” means join end to end) The VB intrinsic constant vbCRLF creates a new line in a string MsgBox stMessage, vbOKOnly, stTitle Dim stMessageString as String Dim stTitleBarString as String stMessageString = "The top salary is: " & vbCrLf & curTopSal & " for 2001" stTitleBarString = "Information for You" MsgBox stMessageString, vbOkOnly, stTitleBarString

14 Message box return values
Constant Value Description vbOK 1 OK button pressed. vbCancel 2 Cancel button pressed. vbAbort 3 Abort button pressed. vbRetry 4 Retry button pressed. vbIgnore 5 Ignore button pressed. vbYes 6 Yes button pressed. vbNo 7 No button pressed. When you use the function form of the message box, you can save the returned value like this: iReturnedValue = MessageBox("Click a Button", vbYesNoCancel,"Test")

15 Checking a data type: IsNumeric & IsDate
Input Validation Checking a data type: IsNumeric & IsDate IsNumeric checks & returns true or false If IsNumeric(txtQty.Text) Then lblDue.Caption = curPrice + Val(txtQty) Validating value ranges If Val(txtHours.Text) > 10 And _ Val(txtHours.Text) <= 80 Then ... Note that IsNumeric works on the Variant data type. The information in all text boxes is of type Variant—you can enter numbers of text values in a text box. Testing a text box with IsNumeric is always a good idea to prevent “surprises.”

16 Data Validation IsDate returns true or false depending on whether or not a value is a date If IsDate(txtData) Then … the VarType function return a number that corresponds to the data type stored in a variant. If VarType(varValue) = 0 Then... Here are the VarType values returned and each data type. Keep this for reference. Value Name Contents 0 Empty No data in the text box (.Text property is variant) 1 Null Variant has no value--not empty 2 Integer Whole number between and 32767 3 Long Whole number between -2Billion and +2Billion 4 Single Decimal number 5 Double Either a very big dec. numb. Or huge # dec. places 6 Currency Decimal number with 4 decimal places 7 Date/Time Value holding a particular date & time 8 String Text 9 OLE Object (ignore for now) 10 Error (ignore for now) 11 Boolean True or false value 12 Variant An array of variants 13 Object Code lump--a non-OLE object (ignore for now) 14 Decimal A power of 10 type number 17 Byte A binary value 8192 Array An ordered table of values

17 Using LostFocus to Validate
LostFocus is a way to validate check boxes before allowing user to go on. But is it a good way? Consider the code If txtUserName.Text = "" Then txtUserName.SetFocus Problem: some object gets focus and you cannot have allow both objects to be tested using the LostFocus event.

18 Calling Event Procedures
An event procedure is a subprocedure that reacts to a specific event such as a button click. You can call any given event procedure from multiple locations, as long as the procedure is in the same form or is public Example: Call cmdCalculate_Click Suffix is event, prefix is object name The word call is optional. You can call an event procedure (or any procedure for that matter) by simply using its name.

19 Hands on Programming Example

20 Debug projects by setting code breakpoints
Debugging VB Projects Debug projects by setting code breakpoints Run the project, Step through the code window at break time by pressing F8, Point to variables above executed code lines to view their current values (see program shot in Notes portion of this slide) breakpoint value of variable

21 You can choose "Step into" or "Step over"
Debugging continued You can choose "Step into" or "Step over" Step into traces all code execution, including traversing down into subprocedures Step over stays with current subprocedure only, not showing any called routines' code


Download ppt "Decisions and Conditions"

Similar presentations


Ads by Google