VB.Net Introduction - 2
Counter Example: Keep track the number of times a user clicks a button Need to declare a variable: Dim Counter As Integer Need to increase the counter by 1 Counter = Counter + 1 Question: Where to declare this variable?
Variable Scope Block-level scope: declared within a block of code terminated by an end, loop or next statement. –If city = “Rome” then Dim message as string = “the city is in Italy” MessageBox.Show(message) –End if Procedural-level scope: declared in a procedure Class-level, module-level scope: declared in a class or module but outside any procedure with either Dim or Private keyword. Project-level scope: a module variable declared with the Public keyword.
Sum Example: Create a form with one textbox to enter number, and a button to add the number to a variable Sum to compute the total of all numbers, and button to show the Sum: Dim Sum As Double Sum = Sum + textbox1.text Interface issue: Should we clear the textbox after adding the number to Sum? TextBox1.Clear() Data conversion issue: What if data entered is not numeric?
Error Handling with the Try Statement Try Sum = Sum + TextBox1.Text TextBox1.Clear() Catch MessageBox.Show("Pls enter a number") End Try
Display Error Message with the Try Statement Try Sum = Sum + TextBox1.Text TextBox1.Clear() Catch ex As Exception MessageBox.Show(ex.Message) End Try
Simple Calculator Create a form with two textboxes to enter numbers and buttons to do +, -, *, / and Mod.
Format C, F, N, P toString(“C”)
Multiple Forms To open a form: formName.Show, formName.ShowDialog Two forms: Form1, Form2 To Open Form2 from Form1: Form2.ShowDialog.
Modeless form: Other forms can receive input focus while this form remains active. –FormName.Show() Modal form: No other form can receive focus while this form remains active. –FormName.ShowDialog()
Configure VB Project Project property page –Application –Compile –References Tools/Options –Environment –Projects and Solutions »VB defaults
VB Defaults Option Explicit: –On --- must declare variables before use Option Strict: –Off --- VB will convert the data Option Compare: –Binary --- case sensitive –Text --- case insensitive Option Infer –On --- When you set Option Infer to On, you can declare variables without explicitly stating a data type. The compiler infers the data type of a variable from the type of its initialization expression.
Decision Structure
Decision: Action based on condition Examples Simple condition: –If total sales exceeds $300 then applies 5% discount; otherwise, no discount. More than one condition: Taxable Income < =3000 no tax 3000 < taxable income <= % tax Taxable income > % tax Complex condition: –If an applicant’s GPA > 3.0 and SAT > 1200: admitted
Relational Operators Test Conditions Usually a condition is formed using a relational operator A relational operator determines if a specific relationship exists between two values >Greater than <Less than =Equal to <>Not equal to >=Greater than or equal to <=Less than or equal to
The If … Then Statement If condition Then Statements End If If condition Then Statements Else Statements End If Note: The If and the Then must be on the same line
If…Then Examples ‘Bonus awarded if sales greater than If sales > Then getsBonus = True End If ‘Bonus, 12% commission rate, and a day off ‘awarded if sales greater than If sales > Then getsBonus = True commissionRate = 0.12 daysOff = daysOff + 1 End If
Example: If total sales is larger than 1000, then give 5% discount totalSales=textbox1.text disCount=0 If totalSales > 1000 Then discount=0.05 End if totalSales=textbox1.text If totalSales > 1000 Then discount=0.05 Else discount=0 End if
Example: If with a block of statements If totalSales > 1000 Then discountRate=0.05 NetPay=totalSales*(1-discountRate) MessageBox.Show(“Thank you very much”) Else discountRate=0 NetPay=totalSales MessageBox.Show(“Thank you”) End if
More than one condition Rules for bonus: JobCode = 1300 JobCode = 2500 JobCode = 3700 JobCode = 41000
IF Statement with ElseIf IF condition THEN statements [ELSEIF condition-n THEN [elseifstatements] [ELSE [elsestatements]]] End If
Code Example If JobCode = 1 Then Bonus = 300 ElseIf JobCode = 2 Then Bonus = 500 ElseIf JobCode = 3 Then Bonus = 700 Else : Bonus = 1000 End If If JobCode = 1 Then Bonus = 300 ElseIf JobCode = 2 Then Bonus = 500 ElseIf JobCode = 3 Then Bonus = 700 ElseIf JobCode = 4 Then Bonus = 1000 End If
Example of ElseIf Usage If sngAverage < 60 Then lblGrade.Text = "F" ElseIf sngAverage < 70 Then lblGrade.Text = "D" ElseIf sngAverage < 80 Then lblGrade.Text = "C" ElseIf sngAverage < 90 Then lblGrade.Text = "B" ElseIf sngAverage <= 100 Then lblGrade.Text = "A" End If Does the order of these conditions matter? What happens if we reverse the order?
Slide The Same Rules Without ElseIf If sngAverage < 60 Then lblGrade.Text = "F" End If If sngAverage < 70 Then lblGrade.Text = "D" End If If sngAverage < 80 Then lblGrade.Text = "C" End If If sngAverage < 90 Then lblGrade.Text = "B" End If If sngAverage <= 100 Then lblGrade.Text = "A" End If Does this code function correctly? What is assigned to lblGrade for a 65 average? 75?
Bonus Example If JobCode = 1 Then Bonus = 300 End If If JobCode = 2 Then Bonus = 500 End If If JobCode = 3 Then Bonus = 700 End If If JobCode = 4 Then Bonus = 1000 End If If JobCode = 1 Then Bonus = 300 ElseIf JobCode = 2 Then Bonus = 500 ElseIf JobCode = 3 Then Bonus = 700 ElseIf JobCode = 4 Then Bonus = 1000 End If
Use of a Trailing Else If sngAverage < 60 Then lblGrade.Text = "F" ElseIf sngAverage < 70 Then lblGrade.Text = "D" ElseIf sngAverage < 80 Then lblGrade.Text = "C" ElseIf sngAverage < 90 Then lblGrade.Text = "B" ElseIf sngAverage <= 100 Then lblGrade.Text = "A" Else lblGrade.Text = "Invalid" End If If average is greater than 100, lblGrade is assigned the text “Invalid”
Nested IF State University calculates students tuition based on the following rules: –State residents: Total units taken <=12, tuition = 1200 Total units taken > 12, tuition = per additional unit. –Non residents: Total units taken <= 9, tuition = 3000 Total units taken > 9, tuition = per additional unit.
Decision Tree Residen t or Not Units <= 12 or Not Units <= 9 or Not
Nested If Example If sngSalary > Then If intYearsOnJob > 2 Then lblMessage.Text = “Applicant qualifies." Else lblMessage.Text = “Applicant does not qualify." End If Else If intYearsOnJob > 5 Then lblMessage.Text = “Applicant qualifies." Else lblMessage.Text = “Applicant does not qualify." End If Note how the convention of indentations emphasizes the structure of nested Ifs. A bank customer qualifies for a special loan if: –Earns over & on the job more than 2 years –Or been on the job more than 5 years
Select Case Structure SELECT CASE testexpression [CASE expressionlist-n [Statements] [CASE ELSE [elsestatements] END SELECT
Select Case Example SELECT CASE temperature CASE <40 Text1.text=“cold” CASE < 60 Text1.text=“cool” CASE 60 to 80 Text1.text=“warm” CASE ELSE Text1.text=“Hot” End Select
The Expression list can contain multiple expressions, separated by commas. Select Case number Case 1, 3, 5, 7, 9 textBox1.text=“Odd number” Case 2, 4, 6, 8, 10 textBox1.text=“Even number” Case Else End Select
Complex Condition Examples: –A theater charges admission fee based on customer’s age: 12 <= Age <= 65:Fee = $5 Otherwise: Fee = $3 –X University admission rules: If GPA > 3.5 or SAT > 1500: Admitted –Y University admission rules: If GPA > 3.0 and SAT > 1200: Admitted
Logical Operators: AND, OR, NOT AND Cond1Cond2Cond1 AND Cond2T TF FTF OR Cond1Cond2Cond1 OR Cond2T TF FTF NOT CondNOT Cond T F
Examples Write a complex condition for: 12 <= Age <= 65 Use a complex condition to describe age not between 12 and 65. X <= 15 is equivalent to: X<15 AND X =15? (T/F) This complex condition is always false: –X 10 This complex condition is always true: –X >= 5 OR X <= 10
Example Electric Company charges customers based on KiloWatt-Hour used. The rules are: –First 100 KH,20 cents per KH –Each of the next 200 KH ( up to 300 KH), 15 cents per KH –All KH over 300, 10 cents per KH
Complex Condition University admission rules: Applicants will be admitted if meet one of the following rules: –1. Income >= 100,000 –2. GPA > 2.5 AND SAT > 900 An applicant’s Income is 150,000, GPA is 2.9 and SAT is 800. Admitted? –Income >= 100,000 OR GPA > 2.5 AND SAT >900 How to evaluate this complex condition?
Scholarship: Business students with GPA at least 3.2 and major in Accounting or CIS qualified to apply: –1. GPA >= 3.2 –2. Major in Accounting OR CIS Is a CIS student with GPA = 2.0 qualified? –GPA >= 3.2 AND Major = “Acct” OR Major = “CIS” Is this complex condition correct?
NOT Set 1: Young: Age < 30 Set 2: Rich: Income >= 100,000 YoungRich
Condition with Not University admission rules: Applicants will be admitted if meet all the rules: –1. SAT > 900 OR Income >= 50,000 –2. Not GPA < 2.5 Condition: –SAT > 900 OR Income >= 50,000 AND Not GPA < 2.5 –Correct?
Order of Evaluation 1. () 2. Not 3. AND 4. OR