Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "SWT (III) VB Week 2 1 Session 4 Control Structures."— Presentation transcript:

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

2 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

3 SWT (III) VB Week 2 3 Using Conditional Expressions Conditional expressions ask true or false questions. For example, the conditional expression Price > 100 evaluates to True if the Price variable contains a value greater than 100, and False otherwise. Comparison Meaning Operators =Equal to <>Not equal to >Greater than =Greater than or equal to <=Less than or equal to

4 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 Then statement1 (executed if codition1 is true) ElseIf condition2 Then statement2 (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

5 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 project 2 Use CommandButton control to create a command button in the upper left corner of the form 3 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.

6 SWT (III) VB Week 2 6 Using Logical Operators Logical operators: And, Or, Not Add password protection to previous project

7 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 1 programme statements (executed if value1 matches variable) Case value 2 programme statements (executed if value2 matches variable) Case value 3 programme statements (executed if value3 matches variable). End Select

8 SWT (III) VB Week 2 8 Select Case Decision Structure (II/IV) Select Case Age Case 16 Label1.Caption = “You can drive now” Case 18 Label1.Caption = “You can vote now” Case 21 Label1.Caption = “You can drink wine with your meals” Case 65 Label1.Caption = “Time to retire and have fun” End Select Example

9 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 < 13 Label1.Caption = “Enjoy your youth!” Case 13 To 19 Label1.Caption = “Enjoy your teens!” Case 21 Label1.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

10 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 about ListBox from Online help

11 SWT (III) VB Week 2 11 For... Next loop (I/II) For variable = start To end statements to be repeated Next variable Syntax Example For i = 1 To 4 Beep Next i Beep 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 iterationi increased by 0.5 after iteration i increased by 1 after iteration (default) For i = 1 To 10 InpName=InputBox(“Enter your name or type Done to quit”) If InpName = “Done” Then Exit For Print InpName Next i Exit For Statement

12 SWT (III) VB Week 2 12 For... Next loop (II/II) A simple counter program. The value of the counter is output via MsgBox. When OK is clicked, the For loop is executed and counter increased by. If Cancel is clicked, the program exit from the For loop. String concatenation ButtClk = 12

13 SWT (III) VB Week 2 13 Do While Loop Do loop execute code until a specific condition is met. Syntax Do While condition block 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

14 SWT (III) VB Week 2 14 Example: Do InpName = 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 the bottom of the loop. Do Loop (I/II) Do InpName = 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

15 SWT (III) VB Week 2 15 Exercise: Convert Temperatures by using a Do Loop 1 Open a new project 2 Open the properties window and set the form’s Visible property to False 3 Double click the form and type the following code Do Loop (II/II)

16 SWT (III) VB Week 2 16 Session 5 Add new forms to a program

17 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 Project menu. 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.

18 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 method and 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.Hide Unload Firm2

19 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 = 1minimise Form1.WindowState = 2maximise Form1.WindowState = 0default view

20 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 function used to display the definition of each word. User Interface Form Design Add items to list box Definition output in MsgBox

21 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 command 2 Click open to open a new blank form in the project 3 Resize the second form so that it is about the size and shape of a small dialog box 4 Click the image control to create a small image box on the left side of the form 5 Click label control to create a label in the top middle area of the form 6 Click TextBox control to create a text box 7 Click the CommonButton control to create a command button 8 Set the following properties Image1StretchTrue Picture“flgitaly.ico” Label1FontTimes New Roman, Boad, 14 point Text1TabStopFalse Command1Caption“Close” Form2Caption“Definition” Example: Working with Multiple Forms (II/III)

22 SWT (III) VB Week 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 Form2 Form2.Label1=List1.Text Form2.Text1= Def Form2.Show 12 Close the code window and click form2, type the following statement in the Command1_Click event procedure Form2.Hide 13 Save the project and run the program. Example: Working with Multiple Forms (III/III) Practice using Hungarian Convention in Lab Exercises

23 SWT (III) VB Week 2 23 Session 6 vCreate Standard modules vCreate your own public variables and procedures vCall public variables and procedures from event procedures

24 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 the procedure is associated with form1. Form1 Private Sub x1 …… End Sub Private Sub x2 …… End Sub Form2 Private Sub x2 …… End Sub Private Sub x1 …… End Sub

25 SWT (III) VB Week 2 25 Working with Standard Modules (II/II) To share variables and procedures among all the forms and event procedures in a project, you need to declare them in one or more standard modules for that project Form1 Private Sub x1 X =100 …… End Sub Private Sub x2 …… End Sub Form2 Private Sub x2 …… End Sub Private Sub x1 X=90 …… End Sub Module1 Public X A standard module is a special file has the filename extension.bas and contains variables and procedures that 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.

26 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 Module command 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 Publicvariable After you declare the variable, you can read it, change it or display it in any procedure in your programme.

27 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

28 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 statements End 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

29 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.5 CityTax = Cost*0.015 TotalTax = StateTax + CityTax End Function Calling a Function Procedure Examples:lblTaxes.Caption = TotalTax (500) TotalTax = SalesPrice + TotalTax (SalsePrice)

30 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

31 SWT (III) VB Week 2 31 Example: Writing Function Procedures Revisit the Lucky Seven Program Add a standard module Two new labels: lblWins lblRate Every time Spin button is pressed Spins increased by 1 When a 7 appears Wins increased by 1 String concatenation operator & Call the general purpose function Rate

32 SWT (III) VB Week 2 32 Week 2 Lab Exercises (I/II) Exercise 1 Practice the examples on pages 5-6, 10, 12, 15, and 31. Make sure you understand them and also remember to use Hungarian Convention in naming your objects. Exercise 2 Design 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 the groups. Two Text objects to hold the names of the members of the group. Three command buttons, two used to 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 = Vertical Locked = True (Find out more about text object from online help). We can create a general purpose function to add new names to both groups. The code may look like that in the following page. But make sure you understand them.

33 SWT (III) VB Week 2 33 Week 2 Lab Exercises

34 SWT (III) VB Week 2 34 Lab Exercises (I/II) 3. Design an image annotation program with an 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 etc B: 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.

35 SWT (III) VB Week 2 35


Download ppt "SWT (III) VB Week 2 1 Session 4 Control Structures."

Similar presentations


Ads by Google