vb express 2008 overview chapters 5-8. summary so far we have talked about the basics of vb. how to...

52
VB Express 2008 Overview Chapters 5-8

Post on 19-Dec-2015

214 views

Category:

Documents


0 download

TRANSCRIPT

VB Express 2008 Overview Chapters 5-8

Summary So Far

• We have talked about the basics of VB. How to add controls on the form? Naming convention of controls and variables. How to change properties of the control. Three main control structures: Sequence, selection, and iteration. Loops – with while and until commands.

• We started the inventory application which we will build upon in this lecture.

Agenda for Today• Add event handler• Insert code into event handler• Access properties value using VB code• Assignment and multiplication operators. • Fixing errors/ breakpoints• Creating and using variables. • Text change events/ precedence rules of arithmetic operators• Problem solving techniques• Control structures in detail (if-then-else)• Checkboxes, dialogs boxes for messages, and logical

operators.

ProblemA college bookstore receives cartons of textbooks. In each shipment, cartons contain the same number of textbooks. The inventory manager wants to use a computer to calculate the total number of textbooks arriving at the bookstore for each shipment from the number of cartons and the number of textbooks in each carton. The inventory manager will enter the number of cartons received and the fixed number of textbooks in each carton for each shipment; then the application will calculate the total number of textbooks in the shipment.

Inventory App

• Label 1: cartons per shipment

• Label 2: Items per carton

• Label 3: total

• Label 4: 0 or blank, autosize false, size 50, 23, Fixed 3D border style

• Button: Calculate

• Run the app…nothing happens because we don’t have the code we need

Chapter 5

• Functionality – actions the application can execute

• Events – user actions

• Event handlers – code that is executed (called) when an event occurs

Chapter 5 : Inventory • Non visual part of the programming• Set the Text Editor to show line numbers.

Tools Options Text Editor Basic Editor Check checkbox for line number

Chapter 5

• Viewing code– Make sure form is open– Go to View->Code– This opens the Code Editor

Chapter 5• VB programs include “classes” to help with

organization• Classes contain groups of code statements

that perform task and return info when tasks are completed

• Code here defines your Inventory Application class – called a class definition

• Green text is a comment. Comments are preceded by a ‘ Comments improve readability of code and to hide chunks of code

Chapter 5

• “Class” keyword is followed by the class name “InventoryForm”

• The name of the class is an identifier. Cannot contain spaces and may not begin with a digit.

• Class definition ends with End Class keyword• Keywords are words with special meaning in

VB and reserved for specific uses. They appear in blue.

• Keywords and identifiers are not case sensitive in VB

Chapter 5

• Adding an event handler• Double click the Calc. Total Button. This generates an

event handlere.g. calculateButton_Click (Control: Button)ControlName – refers to the name of the control entered

in its Name Property• EventName – is the name of the event that triggers the

code to execute (i.e. click)

Event procedure

Line Continuation MarkName of the event the procedure responds to

Name of the control that owns the event procedure

Marks the beginning of this event procedure

Makes the control lblxyz visible:Assigns the value True to the Visible Propertyof the lblxyz control.

Event handled by this procedure

Private Sub btnCalculate_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles btnCalculate.Click' Make the directions visiblelblxyz.Visible = TruelblResults.text=val(lblInput1.text) * val(lblInput2.text)

End Sub

Chapter 5: Hints about VB code• The compiler thinks end of a line is the end

of the statement. To get around this use a _ at the end of a line to continue a line of code

• The compiler doesn’t see or executes comments you create using a ‘

Chapter 5: Hints about VB code• In VB we separate control names and

property names with a “.” this is called the dot operatortotalResultsLabel.text

• Once you type the “.” The Intellisense box will offer you a selection of the class’ members from which to choose (i.e. text). Click once for info about this member, twice to insert it in your code statement

Chapter 5: Hints about VB code• = is an assignment operator

• BobTextbox.text = 5 is an assignment statement

• Stuff on either side of the = are called operands

• An assignment statement and assigns the value on the right to the variable, textbox, etc., on the left

Chapter 5

• So what does the assignment statement for our button look like?

TotalResultsLabel.text = _Val(cartonsTextBox.text)*val(itemsTextbox.text)

Chapter 5

• This statement includes the Val function which keeps the program from crashing if a non number is entered. Fairly robust to GI in that it doesn’t crash but may give you GO.

• CartonsTextBox.text is an argument in the Val function and thus is in ( ), returns a 0 if the input is non-numeric

Val Function Examples

• Val(“16”) returns 16

• Val(“-8”) returns 8

• Val(“bob”) returns 0

• Val(“57bob”) returns 57

• Val(“8 + 7”) returns 8

• The Val function is very useful when you are using arithmetic expression. It makes sure that user provided inputs don’t crash your app. You don’t need to use it to return your results to your users…

Chapter 5

• The debugger– Compiles and runs the app– Errors in code appear in the Error List window– Two types of errors

• Syntax (compilation errors, must be fixed before the code may be executed)

• Logical

• Compile without executing Build->Build [project name]

VB Chapter 6

Enhancing Inventory ApplicationChapter 6

• Introduction to memory concepts using variables.

• Using precedence rules for arithmetic operators

• Set break points to debug applications

Inventory Application

The inventory manager notices a flaw in your Inventory application. Although the application calculates the correct result, that result continues to display even after new data is entered. The only timethe output changes is when the inventory manager clicks theCalculate Button again. You need to alter the Inventory applicationto clear the result as soon as the user enters new information intoeither of the TextBoxes, to avoid any confusion over the accuracy of your calculated result.

TextChanged Event (pg 107)

• We can add an event handler to the cartonsTextbox that clears the totalResultLabel.text every time someone enters a new value into the cartons text box

• Double click cartonsTextbox while in design view

• Creates a TextChanged Event that allows you to write code that will execute when text in the textbox is changed

Chapter 6

• Double click the text box and create an event (TextChanged) where you clear the totalResultLabel.text

• totalResultLabel.text = “ “

• But be careful with textchanged events, it just takes a single character change to execute them

Variables

• Variables – memory spaces - hold data for your application. Unlike text boxes, the values stored in a variable aren’t necessarily seen by users

• Variables must be declared– Dim keyword– Variable name can be any valid identifier– Must set a data type

Variables

• Variables all have– Name– Type– Size– Value

• If you reuse the same variable then original value will be overwritten

Primitive Variable Data Types

• Data types– Integer– Single– String– Boolean– Char– Decimal– Etc.

Back to app.• Add variables to the Calculate button event

handler 1 Public Class InventoryForm

2 ' handles Click event

3 Private Sub calculateButton_Click(ByVal sender As _

4 System.Object, ByVal e As System.EventArgs) _

5 Handles calculateButtton.Click

6

7 ' declare variables

8 Dim cartons As Integer

9 Dim items As Integer

10 Dim result As Integer

11

12 ' retrieve numbers from TextBoxes

13 cartons = Val(cartonsTextBox.Text)

14 items = Val(itemsTextBox.Text)

15

16 ' multiply two numbers

17 result = cartons * items

18

19 ' display result in Label

20 totalResultLabel.Text = result

21 End Sub ' calculateButton_Click

What’s going on in the Code?

• totalResultLabel.Text = “”

• This clears the calculated amount field when the user enters a new amount in the cartons per shipment field

• “” means empty string

• > starts debugger, square stops it

Debugger: Breakpoints

• Breakpoints is a marker set at any executable line of code

• Allows you to examine what your application is doing while running

• Application stops at breakpoint.• Good to debug logical errors• To insert click in the grey

margin or right click breakpoint insert breakpoint

Breakpoints

• Using breakpoints– Run debugger– When execution pauses, can place mouse over

variable to see value• Use Debug-> continue to move past a

breakpoint• Stop button to end debug• Disable breakpoint• Completed wage calculator contains breakpoints

you need to remove in order to test the app.

Chapter 7 – Wage Calculator

Gross earnings per week = hours worked * hourly wages

Assume a standard work week of 40 hours.

Any time worked over 40 hours in a week is considered “overtime” and earns time and a half (1.5)

What’s the pseudocode for this problem?

Wage CalculatorProblem: Input (Hours/wages) Calculate

(salary) Display (earnings)Pseudocode:

-Get hours worked and hourly wages from the textbox-If hours worked are less than or equal to 40

Gross earnings equals hours worked * hourly wages

-ElseGross earnings equals 40 * hourly wage plus

hours above 40 * wage and a half-Display gross earnings

Dim wage, gross As Decimal Dim hours As Double Const HOUR_LIMIT As Integer = 40

wage = Val(wageTextBox.Text) hours = Val(hoursTextBox.Text)

If hours <= HOUR_LIMIT Then gross = wage * hours Else gross = HOUR_LIMIT * wage gross += (hours - HOUR_LIMIT) * wage *

1.5 End If

earningsResultLabel.Text = gross

Assignment Operators

• Assignment operators– value = hours * wage– Value = value + 3– Value += 3

• Other operators– -= – *=– ^=

Formatting

• Formatting Text– Method String.Text

earningsResultLabel.Text = String.Format("{0:C}", earnings)

0: argument 0 is the first element following the formatting string should take on the format C (for currency)

Format Specifiers

• C : currency

• E : scientific notation

• F : fixed point

• G : VB picks either E or F for you

• D : Decimal

• N : number, commas and 2 decimal places

Alternative String Formatting

earningsResultLabel.Text= format(earnings, “c”)

Watch Window

• Debugger watch window– Available only in break mode– Can see contents of variables– Debug->windows->watch->type in name of

variable or an expression– Tells you variable value at that point of

execution and data type– Can use watch window to change var. values

to text program

Control Structures Review• Sequence

– E.g. A B C D– A transfer of control occurs when an executed

statement does not directly follow the previous statement

• Selection (IF…Then, IF…Then…Else, Select case)– If (income>expenses) THEN buy ipod ELSE wait– Returns boolean data type (True/False)

• Iteration (or repetition) – While…End While, Do While…Loop, Do…Loop While,

Do Until…Loop, Do…Loop Until, For…Next, and For Each…Next

Chapter 8

• Dialogs and CheckBoxes

• Dialogs: windows that display messages to users

• CheckBoxes: help control input from users and can make data entry faster

Chapter 8: Example

Dental Payment Application (Introducing checkboxes and message dialogs)

A dentist’s office administrator wishes to create an application that employees can use to bill patients. The application must allow users to enter the patient’s name and specify which services were performed during the visit. The application will then calculate the total charges.If a user attempts to calculate a bill before any services are specified, or before the patient’s name is entered, an error message informing the user of that necessary input is missing will be displayed.

How will it look

Dental Payment PseudocodeWhen user clicks calculate

Clear previous totalIf user has not entered name or selected a checkbox

Display error messageElse

Initialize the total to zeroIf “Cleaning” Checkbox is selected

Add cost of a cleaning to totalIf “Cavity filling” Checkbox is selected

Add cost of receiving filling to the totalIf “X-Ray” Checkbox is selected

Add cost of receiving X-Ray to the totalFormat total to display as currencyDisplay total

Dental Payment Actual Code Private Sub calculateButton_Click

totalResultLabel.Text = "" Dim total As Decimal If cleanCheckBox.Checked = True Then total += 35 End If If cavityCheckBox.Checked = True Then total += 150 End If If xrayCheckBox.Checked = True Then total += 85 End If totalResultLabel.Text = format(total, “c”) End Sub

Let’s stop and create the form

• …

Dialog boxes

• Message dialogs are defined by class MessageBox

• MessageBox.show

• Dialogs are a great way to warn the user that some input is wrong or missing and how to correct the error

Dialog Boxes

If nameTextBox.Text = "" Then

MessageBox.Show("please enter a name and check at least on item", _ "missing information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

Else

Dialog Boxes

• Because of sequence execution, program checks if name has been entered. If it has, then Else statement is skipped and total is calculated

• “Missing Information” goes in the title bar of the dialog box

• OK is a button• Exclamation is a warning icon that

something’s gone wrong

Logical Operators• AndAlso = both conditions must be true

If gender = Female AndAlso age>= 65 then

seniorFemales +=1

• OrElse = either or both are true

If gender = Female OrElse age>= 65 then

seniorFemales +=1

This increments counts if someone if that individual female, if he or she is >= 65 or both

Logical Operators

• Xor – is true only if one condition is true and the other is false…

• Not = enables the programmer to reverse the meaning of a condition

If not (grade = value) then…If (grade <> value)

Requiring check box entries

If (((nameTextBox.Text = "“)) OrElse _ ((cleanCheckBox.Checked = False AndAlso _ cavityCheckBox.Checked = False AndAlso_ xrayCheckBox.Checked = False))) Then

MessageBox.Show("Please enter patients name", _ "Missing Information", MessageBoxButtons.OK, _ MessageBoxIcon.Exclamation)

End if