swt (iii) vb week 2 1 session 4 control structures

35
SWT (III) VB Week 2 1 Session 4 Control Structures

Upload: myah-shippen

Post on 31-Mar-2015

218 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 1

Session 4

Control Structures

Page 2: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 2

Event Driven Programming

Visual Basic Programmes are event driven.

Each object in VB has a pre-defined set of events it can respond to. These events are listed for each object in the procedure drop down list box in the Code window. You can write an event procedure for any of these events, and if that event occurs in the programme, VB will execute the event procedure that is associated with it.

Some of the events associated with the List object are shown on the right

Page 3: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 3

Using Conditional Expressions

Conditional expressions ask true or false questions. For example, the conditionalexpression

Price > 100

evaluates to True if the Price variable contains a value greater than 100, and False otherwise.

Comparison MeaningOperators

= Equal to<> Not equal to> Greater than< Less than>= Greater than or equal to<= Less than or equal to

Page 4: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 4

If .. Then Decision Structure (I/II)

If condition Then statement

Examples: If Score >= 20 Then Label1.Caption = “You Win”

Testing several conditions in an IF ... Then Decision Structure

If condition1 Thenstatement1 (executed if codition1 is true)

ElseIf condition2 Thenstatement2 (executed if codition1 is true)

[additional ElseIf clauses and statements can be placed here]

Else statements (executed if none of the conditions is True)End If

Page 5: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 5

If .. Then Decision Structure (II/II)

Exercise: Validate users by using If ... Then

1 Start VB and open a new standard .exe project2 Use CommandButton control to create a command button in the upper left corner of the form3 Set Caption property of the the command button to “Log In”4 Double click the Log In button and type the following statements in the procedure and save the project and run it.

Page 6: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 6

Using Logical Operators

Logical operators: And, Or, Not

Add password protection to previous project

Page 7: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 7

Select Case Decision Structure (I/IV)

Select Case structure base branching decisions on one key variable

Syntax:

Select Case variable

Case value 1programme statements (executed if value1 matches variable)

Case value 2programme statements (executed if value2 matches variable)

Case value 3programme statements (executed if value3 matches variable)

.

.

.End Select

Page 8: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 8

Select Case Decision Structure (II/IV)

Select Case Age

Case 16Label1.Caption = “You can drive now”

Case 18Label1.Caption = “You can vote now”

Case 21Label1.Caption = “You can drink wine with your meals”

Case 65Label1.Caption = “Time to retire and have fun”

End Select

Example

Page 9: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 9

Select Case Decision Structure (III/IV)

Using Comparison Operators with a Select Case Structure

Select Case Age

Case Is < 13Label1.Caption = “Enjoy your youth!”

Case 13 To 19Label1.Caption = “Enjoy your teens!”

Case 21Label1.Caption = “You can drink wine with your meals”

Case Is > 100 Label1.Caption = “Looking good”

Case Else Label1.Caption = “That’s a nice age to be”

End Select

Page 10: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 10

Select Case Decision Structure (IV/IV)

Exercise: Using a Select Case structure to process a list box

The ListIndex property contains the index of the list item selected. Find out more aboutListBox from Online help

Page 11: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 11

For ... Next loop (I/II)

For variable = start To endstatements to be repeated

Next variable

Syntax

ExampleFor i = 1 To 4

BeepNext i

BeepBeepBeepBeep

For i = 5 To 25 Step 5…..

Next i

For i = 1 To 2.5 Step 0.5…...

Next i

i increased by 5 after iteration i increased by 0.5 after iteration

i increased by 1 after iteration (default)

For i = 1 To 10InpName=InputBox(“Enter your name or type Done to quit”)If InpName = “Done” Then Exit ForPrint InpName

Next i

Exit For Statement

Page 12: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 12

For ... Next loop (II/II)

A simple counter program.The value of the counter isoutput via MsgBox. WhenOK is clicked, the For loopis executed and counter increasedby. If Cancel is clicked, the programexit from the For loop.

String concatenation

ButtClk = 1 2

Page 13: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 13

Do While Loop

Do loop execute code until a specific condition is met.

Syntax

Do While conditionblock of statements to be executed

Loop

Example:

Do While InpName <> “Done”InpName = InputBox(“Enter you name or type “Done” to quit”)If InpName <> “Done” Then Print InpName

Loop

Page 14: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 14

Example:

DoInpName = InputBox(“Enter you name or type “Done” to quit”)If InpName <> “Done” Then Print InpName

Loop While InpName <> “Done”

If you always want the loop to run at least once, put the condition test at thebottom of the loop.

Do Loop (I/II)

DoInpName = InputBox(“Enter your name or type Done to quit”)If InpName <> “Done” Then Print InpName

Loop Until InpName = “Done”

Using Until keyword in Do Loop

Page 15: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 15

Exercise: Convert Temperatures by using a Do Loop

1 Open a new project2 Open the properties window and set the form’s Visible property to False3 Double click the form and type the following code

Do Loop (II/II)

Page 16: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 16

Session 5

Add new forms to a program

Page 17: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 17

Adding New Forms to a Programme

Each new form has a unique name and its set of objects, properties, and event procedures

The first form in a programme is called Form1, sebsequent forms are named Form2, Form3, and so on.

You can create a new form by clicking the Add Form command on the Projectmenu.

Forms can be modal or nonmodal.

A form that must be used when it is displayed on the screen is a modal form -a form retains the focus until the user click OK, Cancel or otherwise dispatches it.

A form that user can switch away from is a nonmodal, or modeless form.

Page 18: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 18

Form Statements in Programme Code (I/II)

The Load statement brings a new form into memeory. Syntax of Load is

Load formname

After you have loaded a form, you can use it from any event procedure in the programme and you can access any property or method you want to use with it.e.g Form2.Caption = “Sorting Results”When you are ready to display a loaded form, you call it by using the Show methodand indicating whether it is modal or nonmodal. Syntax:

formname.Show mode

The default mode is nonmodal (mode = 0), it is modal when mode =1

You can you Hide method or Unload statement to hide form, e.g.Form2.HideUnload Firm2

Page 19: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 19

Form Statements in Programme Code (II/II)

You can minimise a form (place it on the taskbar) or maximise a form (expand it to fill the screen) by using WindowState property.

Form1.WindowState = 1 minimise

Form1.WindowState = 2 maximise

Form1.WindowState = 0 default view

Page 20: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 20

Example: Working with Multiple Forms (I/III)

The Italian Vocabulary Step by Step Program

There is only one form in this program. MsgBox functionused to display the definition of each word.

User InterfaceForm Design

Add items to list box

Definition output in MsgBox

Page 21: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 21

Now create a second form in the program to display the definition of words replacing MsgBox

1 On the project menu, click the add form command2 Click open to open a new blank form in the project3 Resize the second form so that it is about the size and shape of a small dialog box4 Click the image control to create a small image box on the left side of the form5 Click label control to create a label in the top middle area of the form6 Click TextBox control to create a text box7 Click the CommonButton control to create a command button8 Set the following properties

Image1 Stretch TruePicture “flgitaly.ico”

Label1 Font Times New Roman, Boad, 14 pointText1 TabStop FalseCommand1 Caption “Close”Form2 Caption “Definition”

Example: Working with Multiple Forms (II/III)

Page 22: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 22

9 Save Form2 to disk 10 Click the first form and then double click the List1 object on the form.11 Scroll to the bottom of the event procedure in the Code window delete the MsgBox function and add the following statements

Load Form2Form2.Label1=List1.TextForm2.Text1= DefForm2.Show

12 Close the code window and click form2, type the following statement in the Command1_Click event procedure

Form2.Hide13 Save the project and run the program.

Example: Working with Multiple Forms (III/III)

Practice using Hungarian Convention in Lab Exercises

Page 23: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 23

Session 6

Create Standard modules

Create your own public variables and procedures

Call public variables and procedures from event procedures

Page 24: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 24

Working with Standard Modules (I/II)

By default, variables are local to an event procedure, meaning that they can be read and changed only in the event procedure in which they are created.

Likewise, event procedures are local; to the form in which they are created, for example, you cannot call the x1 event procedure from form2 if theprocedure is associated with form1.

Form1Private Sub x1……End Sub

Private Sub x2……End Sub

Form2

Private Sub x2……End Sub

Private Sub x1……End Sub

Page 25: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 25

Working with Standard Modules (II/II)

To share variables and procedures among all the forms and event proceduresin a project, you need to declare them in one or more standard modules for thatproject

Form1Private Sub x1X =100……End Sub

Private Sub x2……End Sub

Form2

Private Sub x2……End Sub

Private Sub x1X=90……End Sub

Module1

Public X

A standard module is a special filehas the filename extension .basand contains variables and proceduresthat can be used anywhere in the program.

Just like form, standard modules are listed separately in the Project window,and can be saved to disk by using the Save Module As command on the file menu.

Standard module only contains code.

Page 26: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 26

Working with Standard Modules and Public Variables

Creating Standard Module

To create a new standard module in a program, you click the Add Modulecommand on the Project menu.

Practice: Create and Save a Standard Module

Working with Public Variables

Declaring a global, or public variable in a standard module is simple. The syntax is

Public variable

After you declare the variable, you can read it, change it or display it in any procedure in your programme.

Page 27: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 27

General - Purpose Procedures

There are three types of general-purpose procedures in a standard module;

Function Procedures. Function procedures are called by name from event procedures or other procedures. They can receive arguments, and they always return a value in the function name.

Sub procedures. Sub procedures are called by name from event procedure or other procedures. They can receive arguments, they also can be used to perform tasks in procedure and to return values. Unlike functions, Subs do not return values associated with their particular sub names (although they can return values through variable names). Sub procedures are typically used to receive or process input, display output, or set properties.

Property procedures. Property procedures are used to create and manipulate user define properties in a programme. You can find out more on this subject in MSDN Library online Help

Advantages of General Purpose Procedure

Eliminate repeated lines Make programmes easier to read Simplify programme development Can be re-used in other programmes

Page 28: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 28

Writing Function Procedures (I/II)

A Function Procedure is a group of statements located between a Function statement and an End Function statement in a standard module.

The statement in the function do meaningful work, processing text, handling input,or calculating numeric values.

Function Syntax:

Function FunctionName ([arguments]) [As Type] function statementsEnd Function

•FunctionName is the function you are creating in standard module.•Arguments is a list os optional arguments (separated by commas) to be used in the function•As Type is an option that specifies the function return type (the default is Variant)•function statements is a block of statements that accomplish the work of the function

Page 29: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 29

Writing Function Procedures (II/II)

Functions always return a value to the calling procedure in the function’s name(FunctionName).

The last statement of a function is often an assignment statement that places the final calculation of the function in FunctionName. E.g.

Function TotalTax (Cost)StateTax = Cost*0.5CityTax = Cost*0.015TotalTax = StateTax + CityTax

End Function

Calling a Function Procedure

Examples: lblTaxes.Caption = TotalTax (500)TotalTax = SalesPrice + TotalTax (SalsePrice)

Page 30: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 30

Writing Sub Procedures

A sub procedure is similar to a function procedure, except that a Sun doesn’t return a value associated with its name. Subs are typically used to get input from the user, display or print information, or manipulate several properties associated with a condition

Sub Procedure Syntax

Sub ProcedureName([arguments])procedure statement

End Sub

Page 31: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 31

Example: Writing Function Procedures

Revisit the Lucky Seven Program

Add a standard module

Two new labels:lblWinslblRate

Every time Spin button is pressedSpins increased by 1

When a 7 appearsWins increased by 1

String concatenation operator &

Call the general purpose function Rate

Page 32: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 32

Week 2 Lab Exercises (I/II)

Exercise 1Practice the examples on pages 5-6, 10, 12, 15, 20-22 and 31. Make sure you understand them and also remember to use Hungarian Convention in naming your objects.

Exercise 2Design a program to assign a class into two groups.The user interface may look like that on the right.There are two Label objects to hold the names of thegroups. Two Text objects to hold the names of themembers of the group. Three command buttons, two usedto add new member to the groups and a third used to terminate the program. You can use InputBox function to prompt the user to input new members names. The properties of the text boxes should be set as:Text = Empty; MultiLine = True; ScrollBar = VerticalLocked = True (Find out more about text object fromonline help). We can create a general purpose functionto add new names to both groups. The code may look like thatin the following page. But make sure you understand them.

Page 33: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 33

Week 2 Lab Exercises

Page 34: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 34

Lab Exercises (I/II)

3. Design an image annotation program withan user interface similar to that shown here.The program should be able to do the following:

A: Allow user to browse the system for graphical image files, such as *.gif, *.jpg etcB: The selected image will be displayed at specified area.C: An annotation button or similar allows user to enter brief text description of the image contents.D: The description text and the image file location will be held in a text object. One possible approach is to record the image file location and name in one line and the content description in the line immediately following the file location information.E: Use a general purpose function to process user input.F: Make sure to use Hungarian Convention in naming objects.

Page 35: SWT (III) VB Week 2 1 Session 4 Control Structures

SWT (III) VB Week 2 35