itp student workbook - basilissachin [licensed for non...

123
LEVEL 3 Introduction to Programming Student Workbook

Upload: dinhnguyet

Post on 12-Apr-2018

229 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

LEVEL 3

Introduction to Programming

Student Workbook

Page 2: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 2 of 123

ITP Student Workbook v2 1.docx

Modification History

Version Date Revision Description

V1.0 April 2009 For issue

V2 June 2012 Reviewed. Overview and formatting updated

V2.1 February 2013 Update

© NCC Education Limited, 2012

All Rights Reserved

The copyright in this document is vested in NCC Education Limited. The document must not be reproduced by any means, in whole or in part, or used for manufacturing purposes, except with the

prior written permission of NCC Education Limited and then only on condition that this notice is included in any such reproduction.

Published by: NCC Education Limited, The Towers, Towers Business Park, Wilmslow Road, Didsbury, Manchester M20 2EZ, UK

Tel: +44 (0) 161 438 6200 Fax: +44 (0) 161 438 6240 Email: [email protected] http://www.nccedu.com

Page 3: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 3 of 123

ITP Student Workbook v2 1.docx

CONTENTS

1. Overview and Objectives .................................................................................................... 5 2. Learning Outcomes and Assessment Criteria ................................................................... 5 3. Syllabus ............................................................................................................................... 7 4. Related National Occupational Standards ......................................................................... 8 5. Teaching and Learning ....................................................................................................... 8

5.1 Lectures ....................................................................................................................... 9 5.2 Laboratory Sessions ..................................................................................................... 9 5.3 Private Study ................................................................................................................ 9

6. Assessment ......................................................................................................................... 9 7. Suggested Further Reading List ........................................................................................ 9 Topic 1: Introduction to the Programming Constructs of Sequencing and Iteration ...... 11

1.1 Learning Outcomes .................................................................................................... 11 1.2 Notes to Teachers and Students ................................................................................ 11 1.3 Timings ....................................................................................................................... 13 1.4 Student Manual .......................................................................................................... 14

1.4.1 Dim Statements ............................................................................................ 32 1.4.2 Variable Names ............................................................................................ 32 1.4.3 Assignment Statements ................................................................................ 32

1.5 Private Study Exercises .............................................................................................. 39 Topic 2: Introduction to the Programming Construct of Selection .................................. 41

2.1 Learning Outcomes .................................................................................................... 41 2.2 Notes to Teachers and Students ................................................................................ 41 2.3 Timings ....................................................................................................................... 42 2.4 Student Manual .......................................................................................................... 43 2.5 Private Study Exercises .............................................................................................. 50

Topic 3: Programming the Graphical User Interface ......................................................... 51 3.1 Learning Outcomes .................................................................................................... 51 3.2 Notes to Teachers and Students ................................................................................ 51 3.3 Timings ....................................................................................................................... 53 3.4 Student Manual .......................................................................................................... 54

3.4.1 Programming Screen Controls ...................................................................... 54 3.4.2 More Looping (Iteration) ................................................................................ 56 3.4.3 The InputBox ................................................................................................ 58 3.4.4 Scope of variables ........................................................................................ 60 3.4.5 The Enabled Property ................................................................................... 62 3.4.6 A Simulation Exercise ................................................................................... 63

3.5 Private Study Exercises .............................................................................................. 67 Topic 4: Project Definition and Design ............................................................................... 69

4.1 Learning Outcomes .................................................................................................... 69 4.2 Notes to Teachers and Students ................................................................................ 69 4.3 Timings ....................................................................................................................... 69 4.4 Student Manual .......................................................................................................... 70

4.4.1 The Immediate Window ................................................................................ 70 4.4.2 The Locals Window ...................................................................................... 72 4.4.3 Multiline Text Boxes ...................................................................................... 73 4.4.4 More than One Form..................................................................................... 74 4.4.5 An Important Worked Example ..................................................................... 76

4.5 Private Study Exercises .............................................................................................. 81 4.6 Sample Midcourse Assignment .................................................................................. 83

Topic 5: Programming More Complex User Interfaces ..................................................... 85 5.1 Learning Outcomes .................................................................................................... 85 5.2 Notes to Teachers and Students ................................................................................ 85 5.3 Timings ....................................................................................................................... 85 5.4 Student Manual .......................................................................................................... 86

Page 4: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 4 of 123

ITP Student Workbook v2 1.docx

5.4.1 Radio (Option) Buttons ................................................................................. 86 5.4.2 Check Box .................................................................................................... 89 5.4.3 Arrays ........................................................................................................... 89 5.4.3.1 A Physical Experiment .................................................................................. 89 5.4.3.2 Programmed Simulation of this Experiment .................................................. 89 5.4.4 Lists of Data Items ........................................................................................ 91 5.4.5 Sorting .......................................................................................................... 92 5.4.6 Combo Boxes ............................................................................................... 93 5.4.7 Menus ........................................................................................................... 95

5.5 Private Study Exercises .............................................................................................. 99 Topic 6: Programming Serial File Processing ................................................................. 100

6.1 Learning Outcomes .................................................................................................. 100 6.2 Notes to Teachers and Students .............................................................................. 100 6.3 Timings ..................................................................................................................... 101 6.4 Student Manual ........................................................................................................ 102

6.4.1 Working with File Streams .......................................................................... 102 6.4.2 Data Capture and Data Validation............................................................... 105 6.4.3 ‘Fixed’ Length Strings ................................................................................. 106 6.4.4 Common Dialog Controls ............................................................................ 107

6.5 Private Study Exercises ............................................................................................ 111 Topic 7: Programming the Range and Type of Procedures ............................................ 114

7.1 Learning Outcomes .................................................................................................. 114 7.2 Notes to Teachers and Students .............................................................................. 114 7.3 Timings ..................................................................................................................... 115 7.4 Student Manual ........................................................................................................ 116

7.4.1 Module-Level Procedures ........................................................................... 116 7.4.2 Form Class-Level Procedures ..................................................................... 116 7.4.3 Scope of Variables ...................................................................................... 116 7.4.4 Communication between procedures .......................................................... 116 7.4.5 Functions .................................................................................................... 119

7.5 Private Study ............................................................................................................ 122

Page 5: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Overview

Page 5 of 123

ITP Student Workbook v2 1.docx

1. Overview and Objectives

This module makes extensive practical use of the modern programming language Visual Basic Express to illustrate the classic programming principles of Sequencing, Selection and Iteration in the context of object oriented computer programming.

2. Learning Outcomes and Assessment Criteria

Learning Outcomes;

The Learner will:

Assessment Criteria;

The Learner can:

1. Understand the Visual Basic (VB) Integrated Development Environment (IDE) and development framework.

1.1 Describe the fundamental facilities of the Visual Basic (VB) Integrated Development Environment (IDE)

1.2 Describe the concept of variables and scope

1.3 Explain the use of debugging facilities provided by the VB IDE

1.4 Explain the communication process between procedures and functions

1.5 Explain the difference between Modal and Non-Modal forms

1.6 Explain the concept of forms and modules

2. Understand the programming constructs of sequence and iteration.

2.1 Describe the ‘For – Next’ construct

2.2 Explain the purpose of the ‘For – Next’ construct

2.3 Describe the ‘If – Then – Else – End If’ construct

2.4 Explain the purpose of the ‘If – Then – Else – End If’ construct

3. Understand the concept of project documentation.

3.1 Explain why the design, implementation and testing of program should be supported by appropriate documentation

3.2 Describe the Project Control Object Definition Sheet

4. Understand data capture and validation.

4.1 Describe how data is captured in a VB programme

4.2 Describe the approach to serial handling used by VB

4.3 Explain what data validation is and why it is important.

Page 6: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 6 of 123

ITP Student Workbook v2 1.docx

5. Implement a program that uses iteration and sequence constructs.

5.1 Write code for either a ‘Form_Paint’ or ‘Form_Load’ procedure that uses the ‘For – Next’ construct

5.2 Write code for either a ‘Form_Paint’ or ‘Form_Load’ procedure that uses the ‘If – Then – Else – End’ If construct

5.3 Write code for either a ‘Form_Paint’ or ‘Form_Load’ procedure that uses the For – Next construct and the If – Then – Else – End If construct

5.4 Identify and document appropriate testing

2. Implement a program that uses screen controls

6.1 Write code that demonstrates the use of a range of screen controls

6.2 Write code that demonstrates the use of the TextBox control

6.3 Write code that demonstrates the use of the ListBox control

6.4 Write code that demonstrates the use of the InputBox control in conjunction with the Rnd and Randomize functions

6.5 Demonstrate programming of arrays to select and search

6.6 Demonstrate programming of a range of controls, the Sort Method and programme menus

6.7 Identify and document appropriate testing

7. Implement a program that uses serial files

7.1 Identify ‘Data’, ‘Items’, ‘Records’ and ‘Files

7.2 Design and implement a data capture form

7.3 Demonstrate programming of the Common Dialog control, StreamWriter and StreamReader objects

7.4 Identify and document appropriate testing

8. Implement a program that uses arrays

8.1 Write code that demonstrates how to declare an array

8.2 Write code that demonstrates how to sort an array

8.3 Identify and document appropriate testing

Page 7: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 7 of 123

ITP Student Workbook v2 1.docx

3. Syllabus

Syllabus

Topic No

Title Proportion Content

1 Introduction to the Programming Constructs of Sequencing and Iteration

10%

1 hour of lectures

5 hours of laboratory

4 hours of private study

Introduction to programming

Introduction to objects

Introduction to variables

Assignment statements

From specification to code

The VB Integrated Development Environment (IDE)

VB forms, basic graphics facilities and statements

Learning Outcome: 1

2 Introduction to the Programming Construct of Selection.

10%

1 hour of lectures

5 hours of laboratory

4 hours of private study

Further data types

Simple expressions

String manipulation

VB-specific constructs for the above

Learning Outcome: 2

3 Programming the Graphical User Interface

10%

1 hour of lectures

5 hours of laboratory

4 hours of private study

Variable scope

VB screen controls

Learning Outcome: 1

4 Project Definition and Design

20%

2 hours of lectures

8 hours of laboratory

10 hours of private study

Multiple forms

Specification, design, implementation, test cycle

VB debugging and testing

Student mid-course assignment

Learning Outcomes: 1, 3, 5

5 Programming More Complex User Interfaces

10%

1 hour of lectures

5 hours of laboratory

4 hours of private study

Arrays and their manipulation

More VB screen controls

Learning Outcome: 6

Page 8: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 8 of 123

ITP Student Workbook v2 1.docx

6 Programming Serial File Processing

10%

1 hour of lectures

5 hours of laboratory

4 hours of private study

Files and records

Data validation

File handling in VB

Learning Outcome: 4, 7

7 Programming the Range and Type of Procedures.

30%

1 hour of lectures

9 hours of laboratory

20 hours of private study

Procedures, functions and scope

Parameter passing

Collections

Learning Outcome: 5

4. Related National Occupational Standards

The UK National Occupational Standards describe the skills that professionals are expected to demonstrate in their jobs in order to carry them out effectively. They are developed by employers and this information can be helpful in explaining the practical skills that students have covered in this module.

Related National Occupational Standards (NOS)

Sector Subject Area: 6.1 ICT for Practitioners

Related NOS: 5.1.A.1 - Carry out system development activities under direction;

5.1.P.1 - Perform systems development activities; 5.1.P.2 - Contribute to the management of systems development; 5.2.J.1 - Perform specified software development activities; 5.2.P.2 - Perform software development activities; 5.3.A.1 - Carry out IT/Technology solution testing activities under direction;

5.3.P.1 - Carry out IT/Technology solution testing

5. Teaching and Learning

Suggested Learning Hours

Lectures: Tutorial: Seminar: Laboratory: Private Study: Total:

8 - - 42- 50 100

The classtime for this module is mostly made up of laboratory sessions. This is because the module has a very practical focus. Each topic will also have an introductory lecture session. All lessons will take place in the computer laboratory.

You should keep a reasonably detailed record of your progress through the student workbook. This record should include all details of your solutions of all the set exercises and the private study work.

You should test even the most trivial solutions by writing down what you expect from a particular test and reporting as to whether the solution produced the expected result. If the answer is no, then there should be some record of the remedial action you had to take. These records are not for assessment but it is important that you learn that it is good practice to record the actions taken.

Page 9: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 9 of 123

ITP Student Workbook v2 1.docx

5.1 Lectures

Your teacher will be presenting the basic knowledge required for the topic during this time. You will be expected to take notes.

5.2 Laboratory Sessions

During these sessions, you are required to work through practical tutorials and various exercises. The details of these are provided in this guide. You must bring this guide to all the lessons for this module. You will be expected to keep written records of your investigations and solutions to the problems set.

5.3 Private Study

This Student Workbook also contains details of the Private Study exercises. You are expected to revise the content of classes and complete these exercises to improve your understanding. Your teacher will set deadlines for the completion of exercises and go over the suggested answers with you.

6. Assessment

You will be required to complete 1 assignment and 1 examination during this module. Both of these will count towards your final mark for the module.

7. Suggested Further Reading List

A selection of sources of further reading around the content of this topic must be available in the Accredited Partner Centre’s library. The following is a suggestion of a suitable source:

Gaddis, T. and Irvine, K. (2009). Starting Out with Visual Basic 2008 Update. 4th Edition. London: Pearson Addison-Wesley.

ISBN-10: 0136076955 ISBN-13: 978- 0136076957

The companion website for this book can be found at: www.aw.com/gaddisvb

Page 10: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 10 of 123

ITP Student Workbook v2 1.docx

Page 11: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Topic 1

Page 11 of 123

ITP Student Workbook v2 1.docx

Topic 1: Introduction to the Programming Constructs of Sequencing and Iteration

1.1 Learning Outcomes

On completion of this topic, you will be able to:

Use the fundamental facilities of the VB 2008 IDE;

Understand the nature of the Form_Paint event;

Understand the nature of the Form_Paint event Procedure;

Use the Integer data type;

Use the graphics class;

Design, Implement and Test solutions to simple graphics problems;

Use the For – Next structure;

Recognise and use a procedure;

Recognise and use a function.

1.2 Notes to Teachers and Students

This topic introduces several fundamental object oriented programming constructs by way of the facilities afforded by the VB 2008 IDE and language.

Concepts introduced in Topic 1 include:

The VB Integrated Development Environment (IDE)

How to locate a project on the filing system

The context sensitive editor

A VB form

The form_Paint event procedure

Using simple graphics facilities of VB 2008 to illustrate:

- The nature of an object - Properties of an object - Methods that can be applied to an object - Integer data type - Variable - Declaration of variables with associated data type - Graphics class - Pen object - The nature of an event - An assignment statement - The nature of a program code procedure - Looping within a program procedure (For --- Next) - Functions in program code - The use of appropriate variable names - Specific VB graphics statements - Transforming simple specifications into working programmed solutions

Page 12: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 12 of 123

ITP Student Workbook v2 1.docx

In order that these introductory Tasks and Exercises can be done in the Visual Basic environment we use the somewhat artificial technique of placing the whole code in the Form_Paint event, of the single form used. The form itself is used as a display medium.

We are NOT concerned with data input at this stage.

VB 2008 provides the programmer with an Integrated Development Environment (IDE). This consists of a number of windows as shown below.

Five important windows are displayed:

The Menu Bar and Toolbar window

The Toolbox window

The Properties window

The Solution Explorer window

The Initial Form window

To see such a screen:

Load up VB 2008 Express.

Close the Start Window.

Go to the top menu.

File – New Project.

Page 13: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 13 of 123

ITP Student Workbook v2 1.docx

It may be a little difficult to arrange your screen as shown above. The example shown has been achieved by using Floating windows for the Solutions and Properties. To make a Window float, right click its banner then check the Floating option.

1.3 Timings

The approximate amount of time that you can expect to spend on each type of activity in this topic is as follows:

Lectures: 1 hour

Laboratory Sessions: 5 hours

Private Study: 4 hours

Page 14: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 14 of 123

ITP Student Workbook v2 1.docx

1.4 Student Manual

We are going to create a simple Visual Basic project that will draw some lines, rectangles and circles.

Step 1: Set where your projects are to be saved

1. Restart VB and close the start-up window, giving:

2. Go to top menu; Tools – Options – Projects and Solutions, giving:

Page 15: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 15 of 123

ITP Student Workbook v2 1.docx

3. Select Project and Solutions, giving:

4. Note the Visual Studio projects location. In the example above, we have typed D:\VB2008Expts. You type the location where you want your projects to be saved. (If you are working on more than one computer it is wise to save your work on a Flash (USB) drive.)

Step 2: Name a new project

1. Back to the top menu; File – New Project, giving:

Page 16: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 16 of 123

ITP Student Workbook v2 1.docx

2. Make sure that Windows Forms Application is selected and name the project thus:

3. Click on OK, giving:

Page 17: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 17 of 123

ITP Student Workbook v2 1.docx

Step 3: Change the name of the form

A form has two distinct lists of properties.

The System Properties that refer to properties used within the program code of any solution.

The File Properties that refer to the properties used by the Filing commands in the computer’s Operating System.

To change the System name of the form:

1. Scroll to the Name Property in the Properties window and type a new name, giving:

Page 18: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 18 of 123

ITP Student Workbook v2 1.docx

You will notice the name of the form in the Solution Explorer window has not changed. This is because that name is the File name of the form.

2. To change the File name, right click the name in the Solution Explorer window, select Rename and type the new name, giving:

3. Finally we should change the heading of the form.

Click once on the form. Go back to the Properties window, scroll to Text and type a new heading, giving:

Page 19: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 19 of 123

ITP Student Workbook v2 1.docx

Step 4: Set start up object

Each project must have a Start Up Object. For our example, this must be set to frmDrawing1.

1. Right-click MyDrawingProject1 in the Solution Explorer and select Properties giving:

Page 20: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 20 of 123

ITP Student Workbook v2 1.docx

2. Make sure that the Start up form is shown as frmDrawing1. If for any reason it is not, click the down arrow and select frmDrawing1.

Step 5: Save all components

Although VB 2008 will have by now saved all the components of this solution, it’s comforting just to make sure.

Top Menu – File – Save All.

IMPORTANT NOTES

Always give Solutions, Projects and Forms unique names before you start any other processes. If you don't you may destroy previous work.

As soon as you have named forms and projects save them before you start programming.

Once you have chosen the directory where you want to save your work DO NOT move to another directory. If you do change directory you might find that all the components of your solution are not in the same directory.

Page 21: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 21 of 123

ITP Student Workbook v2 1.docx

Your screen should now look like this:

All the actions that we are interested in this topic will take place in the form.

The specification of our first task is:

When the Solution is run then a line will be drawn from the top left-hand corner of the form to a point that we define in the program.

To achieve our specification we have to put some program code in the Form_Paint event procedure of the form.

1. Double click anywhere on the form. This procedure template should appear:

Page 22: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 22 of 123

ITP Student Workbook v2 1.docx

2. This is not quite what we want. What is Form1 doing there? We don’t have a Form1.

Let’s not worry about this, just select the offending area, thus:

3. Press Delete, giving:

Page 23: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 23 of 123

ITP Student Workbook v2 1.docx

4. Click the down arrow for the box to the right of frmDrawing1. Select (frmDrawing1 Events), giving:

5. Click the down arrow to the right of (Declarations) and select Paint, giving:

6. Now we have the template where we shall put our program code:

Page 24: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 24 of 123

ITP Student Workbook v2 1.docx

7. Now add three lines of program code thus: (You need not copy the comment lines. A comment line starts with ‘ .The IDE colours the line green.)

8. We are now ready to test the project.

Run it by pressing F5.

Page 25: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 25 of 123

ITP Student Workbook v2 1.docx

The form should now appear as:

(To exit any program that is running in the IDE click on the ‘Stop Debugging’ icon on the menu bar. It’s a small black square right of the middle of the menu.)

Page 26: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 26 of 123

ITP Student Workbook v2 1.docx

It’s now time to explain the program code.

MyGraphicsClass.DrawLine(BlackPen, 0, 0, 250, 350)

To draw a line we have to apply the 'DrawLine' method of the Graphics Class.

A line is drawn between two points.

Each point is determined by a pair of numbers.

The pair (0,0) refers to the top left-hand corner of the form. So the line starts to draw form that point.

The pair (250,350) refers to the other end of the line.

Note the first number of the pair is the distance in pixels from the left of the window and the second number of the pair is the distance in pixels from the top of the window.

Now you edit the program to draw a line like:

Just in case you did not get it; the line of program that did the drawing was:

MyGraphicsClass.DrawLine(BlackPen, 0, 400, 300, 400)

If you look at the properties of the form you will notice that it has a Width and a Height property.

So what should we expect if we execute the program line?:

MyGraphicsClass.DrawLine(BlackPen, 0, 0, Me.Width, Me.Height)

(The Active Form is always referred to as Me).

Page 27: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 27 of 123

ITP Student Workbook v2 1.docx

We actually get:

We might have expected that the second pair of numbers Width, Height would give us the pair of pixel values such that the line would be drawn to the bottom right hand corner of the form.

In fact, the form properties Width and Height are a measure of the total screen resource used by the form including such things as borders. Thus Width and Height are not an accurate measure of the area available for drawing.

To get over this problem we have to use a property of the form called ClientSize.

ClientSize will return its own values of Width and Height, which are the pixel values that we want.

Therefore we need to declare two integer (whole number) variables thus: (More about variables a little later.)

Dim WidthForGraphics, HeightForGraphics As Integer

Then get their values by adding the program statements:

WidthForGraphics = Me.ClientSize.Width HeightForGraphics = Me.ClientSize.Height

Our program will now be:

Page 28: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 28 of 123

ITP Student Workbook v2 1.docx

Running the program gives us:

Page 29: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 29 of 123

ITP Student Workbook v2 1.docx

Task 1

As ClientSize sets the values of its Width and its Height properties automatically, then no matter the dimensions of the form the line will always be plotted correctly.

Show that this is true by resizing the form and then running the project again.

Task 2

Add one more line of program code to draw a second line from the bottom left hand corner to the top right hand corner.

Task 3

Produce the following outputs:

(a)

(b)

Page 30: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 30 of 123

ITP Student Workbook v2 1.docx

Task 4

1. Start a new project. Test the program code:

Private Sub frmDrawing2_Paint(ByVal sender As Object, _ ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint

Dim k As Integer Dim Tenth As Integer Dim MyGraphicsClass As Graphics = e.Graphics Dim BlackPen As New Pen(Color.Black) Dim WidthForGraphics, HeightForGraphics As Integer WidthForGraphics = Me.ClientSize.Width HeightForGraphics = Me.ClientSize.Height Tenth = HeightForGraphics / 10 For k = 1 To 10 Step 1

MyGraphicsClass.DrawLine(BlackPen, 0, 0, WidthForGraphics, k * Tenth) Next k

End Sub

NOTE:

To split a line of program over two or more lines you can use the continuation mechanism at the end of a typed line. This is: space followed by _

You can see this an example of this in the top line of the above program code.

When you run this code you should get the form looking like:

There are several new ideas in this program.

Page 31: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 31 of 123

ITP Student Workbook v2 1.docx

We still have just one program statement that does the drawing:

MyGraphicsClass.DrawLine(BlackPen, 0, 0, WidthForGraphics, k * Tenth)

but we are executing this statement 10 times.

For k = 1 To 10 Step 1 MyGraphicsClass.DrawLine(BlackPen, 0, 0, WidthForGraphics, k * Tenth)

Next k

Here we have an example of using a loop structure.

One end of the loop is the For statement and the other end is the Next statement. Any statements that are in between are executed each time the loop goes round. So how many times does the loop go round? This is set by the rest of the For statement.

In this example k is used to control how many times the loop is executed. k is given an initial value of 1. When the Next statement is executed, then Step 1 adds one to k and the new value of k is tested to see if it is greater than 10. If k is NOT greater than 10, the program statements in the loop are executed again.

The For – Next loop structure is ideal when it is possible for the program to work out how many times the loop needs to be executed. Not all loops are like this. For example, suppose we want a program to add up a series of numbers until a negative number is found. To do this VB provides a Do – Loop structure that keeps going until some condition is met, but more of this in a later topic.

Task 5

Edit the program so just the first 5 lines are drawn.

Page 32: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 32 of 123

ITP Student Workbook v2 1.docx

1.4.1 Dim Statements

Look back at the program code for Tasks 4 and 5. At the top of this program code there are the lines:

Dim k As Integer Dim Tenth As Integer

These are called Dim statements.

Dim is short for the word DIMENSION.

A Dim statement tells the computer to set up a place in the memory with the right dimensions to store a single piece of data that has a certain data type or a complex object of a certain class.

Dim k As Integer sets up a place (location in memory) with the name k and enough space to hold a whole number.

Dim Tenth As Integer also sets up a place (location in memory) with the name Tenth and enough space to hold a whole number.

Tenth and k are called simple variables because the values that these locations hold can vary.

To be more precise, a variable like k or Tenth corresponds to actual physical locations of memory in the computer.

The Dim statements have set up these memory locations to store any whole number within a certain range of numbers. Now, for example whereas the value k changes (varies), the position of the location where k is stored in the computer does NOT change. However, because the value of k can vary to be any whole number, then we say that k is an integer variable.

As well as setting up the right size of space for a variable, a Dim statement sets up all the things that can be done with the variable according to its data type or class. In the cases of k and Tenth, it sets up all the arithmetic operations that could be done to whole numbers.

1.4.2 Variable Names

Stick to just letters (upper or lower case), numbers and the under line character. No spaces. The first character must be a letter.

1.4.3 Assignment Statements

The program line:

Tenth = HeightForGraphics / 10

is called an assignment statement because it assigns a value to the variable Tenth.

When this statement is executed, the right hand side is worked out first by dividing the current value stored in the variable HeightForGraphics by 10. The answer might be something like 45.3. Then the result is put in the store location that has been allocated to the variable Tenth, BUT as Tenth can only hold integers (whole numbers) then the actual value stored would be 45.

Page 33: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 33 of 123

ITP Student Workbook v2 1.docx

Task 6

Start a new project. Write a program to produce an output that looks like this:

Page 34: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 34 of 123

ITP Student Workbook v2 1.docx

Task 7

We can change the colour of the lines drawn by declaring another Pen.

Dim RedPen As New Pen(Color.Red)

Try it.

Task 8

Try the code:

Private Sub frmDrawing2_Paint(ByVal sender As Object, _ ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint

Dim MyGraphicsClass As Graphics = e.Graphics im GreenPen As New Pen(Color.Green) Dim WidthForGraphics, HeightForGraphics As Integer Dim k As Integer Dim WidthOfRectangle, HeightOfRectangle As Integer WidthForGraphics = Me.ClientSize.Width HeightForGraphics = Me.ClientSize.Height GreenPen.Width = 4 WidthOfRectangle = (WidthForGraphics / 2) HeightOfRectangle = (HeightForGraphics /2 MyGraphicsClass.DrawRectangle(GreenPen, 1, , WidthOfRectangle, _ HeightOfRectangle)

End Sub

You should have got the outline of a green rectangle occupying the top left quarter of the form.

Now try:

Private Sub frmDrawing2_Paint(ByVal sender As Object, _ ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint

Dim MyGraphicsClass As Graphics = e.Graphics Dim RedBrush As New SolidBrush(Color.Red) Dim WidthForGraphics, HeightForGraphics As Integer Dim k As Integer Dim WidthOfRectangle, HeightOfRectangle As Integer WidthForGraphics = Me.ClientSize.Width HeightForGraphics = Me.ClientSize.Height WidthOfRectangle = (WidthForGraphics / 2) HeightOfRectangle = (HeightForGraphics / 2) MyGraphicsClass.FillRectangle(RedBrush, 0, 0, _ WidthOfRectangle, HeightOfRectangle)

End Sub

This time you should see that the rectangle has been filled with the colour red.

Notice that whereas we need a Pen for drawing lines we need a Brush for filling with colour.

Also note the method FillRectangle.

Page 35: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 35 of 123

ITP Student Workbook v2 1.docx

Task 9

Write a program that will paint a similar rectangle but this time it will appear in the centre of the form.

Task 10

Start a new project. Size the form to be almost as big as the screen. Test the following program:

Private Sub frmDrawing2_Paint(ByVal sender As Object, _ ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint

Dim MyGraphicsClass As Graphics = e.Graphics Dim WidthForGraphics, HeightForGraphics As Integer Dim BlackPen As New Pen(Color.Black) Dim k As Integer Dim X_Top_Left As Integer Dim Y_Top_Left As Integer Dim WidthOfRectangle As Integer Dim HeightOfRectangle As Integer Dim IncrementX As Integer Dim IncrementY As Integer Dim Number_Of_Rectangles As Integer BlackPen.Width = 2 WidthForGraphics = Me.ClientSize.Width HeightForGraphics = Me.ClientSize.Height X_Top_Left = 5 Y_Top_Left = 5 WidthOfRectangle = WidthForGraphics - 10 HeightOfRectangle = HeightForGraphics - 10 Number_Of_Rectangles = 20 IncrementX = 10 IncrementY = 10

For k = 1 To Number_Of_Rectangles Step 1 MyGraphicsClass.DrawRectangle(BlackPen, X_Top_Left, _

Y_Top_Left, WidthOfRectangle, HeightOfRectangle) X_Top_Left = X_Top_Left + IncrementX Y_Top_Left = Y_Top_Left + IncrementY WidthOfRectangle = WidthOfRectangle - 2 * IncrementX HeightOfRectangle = HeightOfRectangle - 2 * IncrementY

Next k End Sub

Page 36: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 36 of 123

ITP Student Workbook v2 1.docx

The output should look like this:

Although this program looks much more complicated, its central statement is still one that draws a rectangle:

MyGraphicsClass.DrawRectangle(BlackPen, X_Top_Left, _ Y_Top_Left, WidthOfRectangle, HeightOfRectangle)

There are several things to notice about this program:

1. There are several variables including:

Dim X_Top_Left As Integer Dim Y_Top_Left As Integer Dim WidthOfRectangle As Integer Dim HeightOfRectangle As Integer Dim IncrementX As Integer Dim IncrementY As Ineger Dim Number_Of_Rectangles As Integer

The names of the variables are such that they try to describe for what each variable is used. Get in the habit of using meaningful variable names, it makes it much easier to understand the program and the time spent in the initial typing is more than saved when you start to debug your program.

2. Note how long statements of program code can be split to make them easier to see without having to scroll the window horizontally.

3. Some values have been assigned to variables:

Page 37: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 37 of 123

ITP Student Workbook v2 1.docx

X_Top_Left = 5 Y_Top_Left = 5 WidthOfRectangle = WidthForGraphics - 10 HeightOfRectangle = HeightForGraphics - 10 Number_Of_Rectangles = 20 IncrementX = 10 IncrementY = 10

This is a sensible technique because if we want to change any of the values we can just change it at one point in the program without having to search to find every place where it is used.

Task 11

Start a new project. Make sure that the width of the form is bigger than the height. Try the following code:

Private Sub frmdrawing2_Paint(ByVal sender As Object, _ ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint

Dim MyGraphicsClass As Graphics = e.Graphics Dim WidthForGraphics, HeightForGraphics As Integer Dim BlackPen As New Pen(Color.Black) Dim LeftOffSet, TopOffSet As Integer Dim Diameter As Integer BlackPen.Width = 10 WidthForGraphics = Me.ClientSize.Width HeightForGraphics = Me.ClientSize.Height LeftOffSet = (WidthForGraphics - HeightForGraphics) / 2 TopOffSet = 5 'This value found by experiment. Diameter = HeightForGraphics - 2 * TopOffSet MyGraphicsClass.DrawEllipse _ (BlackPen, LeftOffSet, TopOffSet, Diameter, Diameter)

End Sub

The result should be:

Note that the Circle is drawn by inscribing it in a bounding rectangle.

Page 38: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 38 of 123

ITP Student Workbook v2 1.docx

Thus the points in the parameter list of the DrawEllipse method are the same as for a rectangle.

Now add more statements to the program code thus:

Private Sub frmdrawing11_Paint(ByVal sender As Object, _ ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint

Dim MyGraphicsClass As Graphics = e.Graphics Dim WidthForGraphics, HeightForGraphics As Integer Dim GreenPen As New Pen(Color.Green) Dim RedBrush As New SolidBrush(Color.Red) Dim LeftOffSetOfTyre, LeftOffSetOfWheel As Integer Dim TopOffSetOfTyre, TopOffSetOfWheel As Integer Dim DiameterOfTyre, DiameterOfWheel As Integer GreenPen.Width = 10 WidthForGraphics = Me.ClientSize.Width HeightForGraphics = Me.ClientSize.Height LeftOffSetOfTyre = (WidthForGraphics - HeightForGraphics) / 2 TopOffSetOfTyre = 5 'This value found by experiment. LeftOffSetOfWheel = LeftOffSetOfTyre + GreenPen.Width TopOffSetOfWheel = TopOffSetOfTyre + GreenPen.Width DiameterOfTyre = HeightForGraphics - 2 * TopOffSetOfTyre DiameterOfWheel = DiameterOfTyre - 2 * GreenPen.Width MyGraphicsClass.DrawEllipse (GreenPen, LeftOffSetOfTyre, _ TopOffSetOfTyre, DiameterOfTyre, DiameterOfTyre) MyGraphicsClass.FillEllipse(RedBrush, LeftOffSetOfWheel, _ TopOffSetOfWheel, DiameterOfWheel, DiameterOfWheel)

End Sub

The program should now produce a solid red wheel with green tyre.

Page 39: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 39 of 123

ITP Student Workbook v2 1.docx

1.5 Private Study Exercises

Exercises 1- 6

Write and test Form_Paint event procedures for each of the following outputs:

Page 40: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 40 of 123

ITP Student Workbook v2 1.docx

Exercise 7

Distinguish between a Property and a Method giving examples.

Exercise 8

Distinguish between the name of a variable and the contents of a variable.

Exercise 9

Describe in detail the Visual Basic loop structure For – Next.

Exercise 10

Early versions of Basic only allowed very short variable names. Explain why this would have been a disadvantage to programmers.

Page 41: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Topic 2

Page 41 of 123

ITP Student Workbook v2 1.docx

Topic 2: Introduction to the Programming Construct of Selection

2.1 Learning Outcomes

On completion of this topic, you will be able to:

Understand the Form_Load event;

Understand the Form_Load event procedure;

Use the MessageBox class;

Use the string data type;

Understand the Length and Substring methods;

Use the Format function;

Design, Implement and Test solutions to simple numeric and string manipulation problems;

2.2 Notes to Teachers and Students

Topic 2 moves away from graphics but does revisit some of the techniques used in Topic 1.

We shall now use the Form_Load event as a means to execute and display the results of the Tasks.

Many of the tasks involve copying program code and observing the output it generates. It is essential that time is taken to carefully relate each line of program code to the outcome of its execution.

Additional concepts introduced in Topic 2 are:

The MessageBox class

The String Data Type

Simple computations in assignment statements

The Single Data Type

The String Operation &

The Length method

The SubString method

The simple Format function

The Functions Asc() and Chr()

In Topic 1, the output was always a graphical image made of lines and/or curves.

In Topic 2, we shall need to output characters that make up conventional words and numbers i.e. traditional output.

To make things simple, we will confine ourselves to using the MessageBox.Show method.

Page 42: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 42 of 123

ITP Student Workbook v2 1.docx

2.3 Timings

The approximate amount of time that you can expect to spend on each type of activity in this topic is as follows:

Lectures: 1 hour

Laboratory Sessions: 5 hours

Private Study: 4 hours

Page 43: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 43 of 123

ITP Student Workbook v2 1.docx

2.4 Student Manual

Task 1

Start a new project. Name the form frmTopic2Task1.vb

Double click on the form to bring up the frmTopic2Task1_Load template.

1. In the frmPart2Task1_Load event procedure, place the single statement:

MessageBox.Show("This will show in a Message Box")

Running the project would produce a little output window thus:

2. MessageBox.Show requires a string as the message it needs to output. We just gave it the literal string "This will show in a MessageBox".

BUT we could have given it a string variable.

Demonstrate that this is the case by testing the following program code:

(again in the frmPart2Task1_Load event procedure)

Dim MyOutput As String MyOutput = "This will show in a Message Box" MessageBox.Show(MyOutput)

3. As MessageBox.Show only displays one string, if we want a more complex output like:

X Y 712 349

then we will have to construct that whole output as a single string.

There are some problems to be overcome:

How can we include in the output string the code to drive the output stream of characters to a new line?

If the numbers are integer variables how do we turn them into strings?

How do we make the numbers appear in the correct locations?

Try this code:

Page 44: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 44 of 123

ITP Student Workbook v2 1.docx

Dim MyOutput As String Dim x, y As Integer x = 712 y = 349 MyOutput = "_X___Y__" & vbCrLf & Format(x, "000") & " " & Format(y, "000") MessageBox.Show(MyOutput)

This should produce:

Note:

The & operator joins strings together.

vbCrLf generates new line. Cr is short for Carriage return, equivalent to moving the cursor to the far left. Lf is short for Line feed, equivalent to moving the cursor to the next line.

The Format function ensures that there are at least three numeric characters displayed.

The Single data type can hold numbers with fractional parts e.g. 12.7894, -0.007632.

A variable that is dimensioned as Single cannot only store this more complex data type but is set up to do the more complex arithmetic that is associated with non-whole numbers. Single Arithmetic puts a greater load on the computer system than Integer Arithmetic.

Page 45: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 45 of 123

ITP Student Workbook v2 1.docx

Task 2

Start a new project.

Test the following code. (You need not copy the lines of comment.)

' Generally it is good style to declare all the variables at the top ' of a procedure or module Dim MyOutput As String Dim Price As Single, Vat As Single, TotalPrice As Single ' We now perform a simple calculation Price = 100 Vat = (17.5 / 100) * Price TotalPrice = Price + Vat ' The results have been computed but now we have to build the output string MyOutput = "BASE PRICE__VAT TAX__WHAT YOU PAY" & vbCrLf MyOutput = MyOutput & " " & Format(Price, "000.00") _ & " " & Format(Vat, "00.00") _ & " " & Format(TotalPrice, "000.00") MessageBox.Show(MyOutput)

This should produce:

Note the Format functions and how they relate to the layout of the output.

Task 3

Start a new project.

Write and test a program to convert a distance in Miles to an equivalent distance in Kilometres. [ 5 Miles = 8 Kilometres ]

Task 4

Start a new project.

Test the following code.

Dim MyOutPut As String Dim Price As Single, Vat As Single, TotalPrice As Single Dim StartPrice As Integer, LastPrice As Integer Dim IncrementPrice As Integer StartPrice = 10

Page 46: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 46 of 123

ITP Student Workbook v2 1.docx

LastPrice = 80 IncrementPrice = 5 MyOutPut = "BASE PRICE__VAT TAX__WHAT YOU PAY" & vbCrLf ' Use a FOR - NEXT loop when you have a known number of iterations For Price = StartPrice To LastPrice Step IncrementPrice

Vat = (17.5 / 100) * Price TotalPrice = Price + Vat MyOutPut = MyOutPut & " " & Format(Price, "000.00") _ & " " & Format(Vat, "00.00") _ & " " & Format(TotalPrice, "000.00") & vbCrLf

Next Price MessageBox.Show(MyOutPut)

The output should be:

Task 5

Modify Task 4 to give a price range from 0.5 to 1.5 in increments of 0.1.

(Beware there is a ‘catch’ here!)

Page 47: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 47 of 123

ITP Student Workbook v2 1.docx

Task 6

Make a new project that will produce a table showing miles to kilometres from 20 miles to 30 miles in increments of 0.5 miles.

Task 7

1. Read the program code below paying particular attention to the embedded comments. This code is all about manipulation of data strings. A string is any group of characters. Several string functions/methods are introduced.

2. Take some time to try to predict the output that this code would produce.

3. THEN run the code and see how the actual output relates to your prediction.

Dim MyOutPut As String Dim Test_Message, A_Bit_Of_It As String Dim K, L As Integer Dim Temp As String Test_Message = "THIS IS A String Exercise" ' Find out the length of the string L = Test_Message.Length ' Use the SubString method to get the 6 character ' substring from position 10 {counting from zero} A_Bit_Of_It = Test_Message.Substring(10, 6) ' Have a look at what we have done MyOutPut = "Length of '" & Test_Message & "' = " & Format(L, "0") MessageBox.Show(MyOutPut) MyOutPut = "The substring = '" & A_Bit_Of_It & "'" MessageBox.Show(MyOutPut) ' Take the string, less the last 9 characters, one character at a time ' Display each character on a new line UNLESS ' it is a space when we shall display the message SPACE MyOutPut = "" For K = 0 To L – 10 Step 1

Temp = Test_Message.Substring(K, 1) If Temp = " " Then 'Note the space between the quotes

MyOutPut = MyOutPut & "SPACE" & vbCrLf Else

MyOutPut = MyOutPut & Temp & vbCrLf End If

Next K MessageBox.Show(MyOutPut)

4. Look at the programme output. The following knowledge that can be gained by observing the outputs of this program is as follows:

Page 48: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 48 of 123

ITP Student Workbook v2 1.docx

The number of characters in a string is given by applying the Length method to the string in question. The method returns an integer value, which has been stored in the integer variable L.

L = Test_Message.Length

A section of a string can be extracted by applying the Substring method to the string in question.

A_Bit_Of_It = Test_Message.Substring(10, 6)

The Substring method has two integer parameters.

The first parameter defined the position of the first character of the substring to be referenced. (We have to start counting characters from position zero).

The second parameter gives the length (number of characters) of the substring to be referenced.

The method returns a string value, which has been stored in the string variable A_Bit_Of_It.

Examine how the output strings have been put together. For example:

MyOutPut = "Length of '" & Test_Message & "' = " & Format(L, "0")

It is done by concatenating four strings using the & operation.

"Length of '" seems to be ending with treble quotes. It is in fact a single quote followed by a double quote. Thus the ' becomes the last character of the part message Length of '.

Examine other places in the program where '" occurs.

Examine the For – Next loop.

An expression, L – 10, has been used in its controlling parameters.

We shall find later that there is a whole range of types of expressions that can be used to control a For – Next loop.

The If construction is introduced.

If Temp = " " Then

MyOutPut = MyOutPut & "SPACE" & vbCrLf Else

MyOutPut = MyOutPut & Temp & vbCrLf End If

This construction tests a logical condition and, depending on the result of the test, choice is made as to which program statement will be executed.

A logical condition has just two possible values: True or False.

In the code above the condition is Temp = " ".

(The string variable Temp is a space character)

If the condition is True then the program statement(s) between Then and Else are executed.

Page 49: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 49 of 123

ITP Student Workbook v2 1.docx

If the condition is False then the program statement(s) Between Else and EndIf are executed.

Later we shall come across different forms of the If construction. Also we shall see more complex conditions.

Page 50: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 50 of 123

ITP Student Workbook v2 1.docx

2.5 Private Study Exercises

In general, make each of the following exercises a different project.

Get into the habit of saving before running, at least before the first run.

Exercise 1

Put some text that contains some S and s characters into a string variable.

Write and test the program code that will scan the text character by character counting the number of S or s characters it finds.

Exercise 2

Experiment with the Basic functions ASC & CHR.

[ASC(“z”) CHR(90) ]

Note the ASCII ranges for A to Z & a to z.

Exercise 3

Put some text that contains some upper and lower case characters into a string variable.

Write and test program code so that when the characters are displayed their case is changed. (i.e. T would become t, n would become N).

Exercise 4

Discover the action of the statements:

Temp = "The Blue Cat".Substring(0, 5) and

Temp = "Jack".Substring("Jack".Length - 2)

Exercise 5

A string consists of a Forename and a Surname. The Forename is always separated from the Surname by one or more spaces.

Write a program that will take any composite name in this form placing the Forename in the string variable FIRST and then the Surname in the string variable SECOND.

Exercise 6

You have used three numeric data types: Integer, Long and Single.

Using Help find out the range of numbers for each of these data types.

Justify the statement: "If possible use the Integer data type".

Exercise 7

1. Describe the meaning of the Visual Basic constant vbCrLf.

Page 51: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Topic 3

Page 51 of 123

ITP Student Workbook v2 1.docx

Topic 3: Programming the Graphical User Interface

3.1 Learning Outcomes

On completion of this topic, you will be able to:

Understand the nature of a screen control;

Understand the nature of a property of an object;

Locate the list of events appropriate to a particular control;

Use the InputBox function;

Understand scope as applied to variables;

Understand the structure of a VB program statement; the relationships between Objects properties and methods;

Design and Implement solutions to user interface centred problems;

Understand simple ideas of models and simulation;

Use the Rnd and Randomize functions;

Use the ListBox control;

3.2 Notes to Teachers and Students

This topic moves the student into GUI programming by introducing the placing of screen controls on a form. Within event procedures of screen controls, students will have to exercise the traditional programming skills of sequencing, selecting and iterating.

Concepts introduced in Topic 3 Include:

Screen Controls

Properties of screen controls

Event procedures of screen controls

Programming screen controls

Input dialogs

Scope of variables

The Enabled property

Simple use of random numbers

The Items collection in a List Box

So far we have only used the form object and the Form_Paint() and Form_Load () event procedures to help us become familiar with some Visual Basic program code statements and structures.

The form is a container object which means that it can have other screen objects drawn on to it. If the form is moved then the objects drawn on the form will move with the form. This demonstrates that these objects are contained by the form.

Page 52: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 52 of 123

ITP Student Workbook v2 1.docx

Experiment

1. Start a new project.

2. Click on any object in the Toolbox. With the mouse, draw an instance of the object on the form.

3. Now use the Toolbox a few more times to put several different objects on the form.

The screen should now look something like this:

All of these screen objects, including the form, are called screen controls. This is because they can be programmed to control what happens when a project is running and hence can be used to control the action of the computer system itself.

You have already seen that we start the name of a screen form with the three letters 'frm'. This is a convention suggested by Microsoft. All screen controls should be named in such a way that it is easy to determine what type of object they are. For example, the name of each text box should start with the three characters 'txt', label object names should start with 'lbl' and the name of each button should start with 'btn'.

Other naming conventions will appear throughout this guide.

Later you will be introduced to a PROJECT CONTROL paper-form that will help you with design and documentation.

Remember:

ALWAYS give a form a unique name; don't use the default names, i.e. Form1, Form2 etc.

NEVER do any saving before you have given names to all the forms you have created.

Page 53: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 53 of 123

ITP Student Workbook v2 1.docx

ALWAYS name your project BEFORE you write any program code and save it in the directory where you have decided to keep your VB projects. DON'T shift directories or else, as was said in Topic 1, you may find a project file in one directory and a form module file in another directory.

Visual Basic is an extensive language. Hence there could be a range of alternative facilities that you could use to achieve any defined end. At this stage confine yourself to the simple approaches suggested.

3.3 Timings

The approximate amount of time that you can expect to spend on each type of activity in this topic is as follows:

Lectures: 1 hour

Laboratory Sessions: 5 hours

Private Study: 4 hours

Page 54: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 54 of 123

ITP Student Workbook v2 1.docx

3.4 Student Manual

3.4.1 Programming Screen Controls

Task 1

1. Start a new project.

2. Give a Form Object a Name Property and Text Property. Name and save the project.

{You won't always be prompted to do these initial actions, but don't forget to do them with each new project.}

3. Add a single Button screen control. Make its name property btnQuit and its Text property Quit.

4. Double click the button. This brings up the programming event procedure template:

Private Sub btnQuit_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnQuit.Click End Sub

This template is for the click event procedure of the button. Any program code that is written into this procedure will be executed when the screen control is left-clicked.

(By default all click events are assumed to be activated by the left mouse button)

Only one statement is required to complete this procedure. This is the Application.Exit() statement thus:

Private Sub btnQuit_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnQuit.Click

Application.Exit() End Sub

5. Run the project.

When you click the button Quit the project should terminate.

This may seem quite a trivial task but the inclusion of a Quit button in every project is essential to allow a user of the project to terminate the run.

Every screen control object has its own set of Properties.

If the project is in design mode in the IDE (Integrated Development Environment), then some of the properties of a screen control object can be seen by clicking on the control and looking at the Properties Window.

The Properties Window shows the default values of the properties for the selected control. Any of these properties can be changed in the design mode as you have done often by setting the Name property. All controls have a Name property.

Many of a control's properties can be set by program code. The general structure of such a program code statement is:

<Control Object Name>.<Property> = <Value>

Page 55: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 55 of 123

ITP Student Workbook v2 1.docx

For example, suppose we have a text box whose Name property is txtDisplay.

To set the background colour of this text box to red when the project is running requires that the program code statement is executed:

txtDisplay.BackColor = Color.Red

Note that in this example:

<Control Object Name> is txtDisplay <Property> is BackColor <Value> is Color.Red

Task 2

1. Start a new project.

2. Add three buttons to your form. Set their names to btnRED, btnGREEN, btnBLUE. Set their text properties to RED, GREEN and BLUE respectively.

3. Add a textbox to your form. Name the text box txtDisplay.

4. Put the appropriate Visual Basic instructions in the appropriate Click procedures to make the following happen:

When the "RED" command is clicked, then the colour of the text box should change to red and similarly for clicking on the "GREEN" and "BLUE" buttons.

Task 3

1. Start a new project.

2. Put a single-line text box on the screen. Set the text property to your name.

3. Put three buttons on the screen with captions Quit, Start, SwopColors.

4. Now program the click procedures of Start and SwopColors such that when Start is clicked we will see your name in red on a green background, but from then on when SwopColors is clicked the background and foreground colours swop.

STRONG HINT: Start the program code in the btnAlter click procedure with:

Dim KeepBackColor, KeepForeColor As Color

STRONG WARNING: If you are thinking about putting any actual Color Values in the btnSwopColors click procedure, then you are on the wrong track!

Page 56: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 56 of 123

ITP Student Workbook v2 1.docx

Task 4

1. Start a new project.

2. Put two text boxes on the screen, set the background colour of one to red and the other to green.

3. Put a button on the screen called SWOP.

4. Now write some Visual Basic code so that when the SWOP button is clicked the background colours in the text boxes swop.

Hint: You may wish declare something like:

Dim BackColor_of_Box1, BackColor_of_Box2 As Color

3.4.2 More Looping (Iteration)

Below are a form and the program code that is associated with the two buttons btnLineofStars and btnQuit.

Private Sub btnLineOfStars_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnLineOfStars.Click Dim k As Integer txtStars.Text = "" For k = 1 To 20

txtStars.Text = txtStars.Text & "*" Application.DoEvents()

Next k End Sub Private Sub btnQuit_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnQuit.Click Application.Exit() End Sub

Page 57: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 57 of 123

ITP Student Workbook v2 1.docx

Task 5

Set up the above form and test the code.

When you click 'Make a Line of Stars' 20 stars should appear in the text box. Experiment with the Font properties of the textbox; particularly the font size.

Task 5(a)

VB 2008 has a number of facilities that help to debug programs. One of these is the ‘single step’ facility. The idea here is to be able to observe what happens when each program statement is executed one after the other.

This is achieved by starting the program run with F8 and thereafter pressing F8 to execute the program one statement at a time.

Before you try this, arrange the program code on the right half of the screen.

1. Now press F8 repeatedly until the form appears:

2. NOTE that to get to this point the system entered the frmTopic3Tasks_Load procedure.

Also note what was highlighted when this happened. Not until the system exited this procedure did the form appear, requiring F8 to be pressed three times. Thus we see that the first action taken when a project is run is to load the start up object; in this example frmTopic3Tasks.

3. Continue to press F8 (slowly) and make a mental connection between which program statement is highlighted and when the next star appears.

4. Comment out the Application.DoEvents() statement (by adding a ‘ at the left hand side) and then repeat the single step experiment.

You probably will find that you get no stars output until the loop has completed. This is because the computer’s operating system cannot get the attention of the processor to service the screen’s requirements. Application.DoEvents() gives the operation system a chance to service the peripherals before the next VB statement is executed.

Page 58: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 58 of 123

ITP Student Workbook v2 1.docx

Task 6

1. Start a new project.

2. Set up the form similar to Task 5 but this time place four button controls with Captions: 'Short Line of Stars', 'Medium Line of Stars', 'Long Line of Stars', 'Quit'.

3. Add a second text box object (single line) to your form.

4. Add suitable code to the button click procedures such that the text box will display the message SHORT, MEDIUM or LONG as appropriate.

3.4.3 The InputBox

As yet we have not input any data to a project whilst it was running.

An easy way to do this is by way of the Input Box function.

Let us see what this function does.

Task 7

1. Set up a form with two buttons, a label with text Output and a textbox thus:

2. Name the 'Input Test' button as 'btnInputTest' and the text box as 'txtResult'.

3. The following program code is the click event procedure for the 'Input Test' button.

Private Sub btnInputTest_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnInputTest.Click Dim Response As String txtResult.Text = "" Response = InputBox("Please Type a Number") txtResult.Text = Response End Sub

Page 59: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 59 of 123

ITP Student Workbook v2 1.docx

When the project is run the InputBox function will produce the input window:

This is an example of a dialog window.

Typing in the number 173.785 and then pressing OK should give:

4. What happens if you do not type a number or click OK before you type anything?

It seems that our project does not mind. To make things more robust, edit the code thus:

Dim Response As String txtResult.Text = "" Response = InputBox("Please Type a Number") If Not IsNumeric(Response) Then

MessageBox.Show("Not a number") Else

txtResult.Text = Response End If

A new function IsNumeric has been introduced. This function accepts any string as an argument. If that string contains characters that make a number then the function returns a value of True. Otherwise it will return a value of False.

Note also the operation Not. Not makes a True result False or a False result True. So in this example Not IsNumeric would give a result True to a non-numeric string.

This example is not finished yet.

We might have proved that the string we have entered is numeric but it is still a string so we can’t do arithmetic with the string Response.

Page 60: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 60 of 123

ITP Student Workbook v2 1.docx

Suppose that we want to enter a price and then calculate the Vat. First we must convert the numeric string to a numeric data type. Hence we must declare two variables (Price and Vat) as Single then use the CSng function to convert Response.

Price = CSng(Response)

5. Finally calculate the Vat with the statement:

Vat = Price * 17.5 / 100

Test this code:

Dim Response As String Dim Price, Vat As Single txtResult.Text = "" Response = InputBox("Please Type a Number") If Not IsNumeric(Response) Then

MessageBox.Show("Not a number") Else

txtResult.Text = Response Price = CSng(Response) Vat = Price * 17.5 / 100 txtResult.Text = Vat.ToString

End If

Questions:

a) What is the point of the statement:

txtResult.Text = ""

b) Where was the Vat value output and which program statement achieved this?

Task 8

Redesign your solution to Task 6, using the InputBox function in such a way that:

there is just one button to activate the placing of the stars

the number of stars is variable

the value of this variable is given by the user via an InputBox function.

3.4.4 Scope of variables

Any variables that are declared (Dim) in a procedure are LOCAL to that procedure.

To communicate information between two procedures, you would need to declare variables at a level higher than the individual procedures.

These declarations will have to take place at the Class Level of the form.

Let us demonstrate this.

Page 61: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 61 of 123

ITP Student Workbook v2 1.docx

Task 9

1. Start a new project. Place two buttons and a text box on the form.

The code procedures for the buttons are:

Private Sub btnOne_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnOne.Click

Dim S As String txtDisplay.Text = "" S = "Testing Scope of Variables, One"

End Sub Private Sub btnTwo_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnTwo.Click txtDisplay.Text = S

End Sub

2. At once we see that the variable S in the btnTwo_Click procedure has been underlined in blue. This is because it has not been recognised.

To cure this, cut the line Dim S As String from the procedure Private Sub cmdOne_Click(). Now paste the declaration immediately under any Class or Inherits statement thus:

The variable S now has scope over the whole form; thus the current value stored in S can be used anywhere in the form.

3. Test the project by clicking on btnOne and then btnTwo. The fact that the message appears in the text box after btnTwo is clicked indicated that data had been passed from one procedure to another via the variable S.

The variable S has now been declared at Class – Level.

Page 62: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 62 of 123

ITP Student Workbook v2 1.docx

3.4.5 The Enabled Property

To test the last example, we had to click the two buttons in the right order. In real life situations, pressing buttons in the right order could be a matter of life or death. For example, consider the software that controls a nuclear power station.

We can add statements to the program above to ensure that we can only press the buttons in the right order. This is achieved by using the Enabled property of the buttons.

The Enabled property of a button can be set to either True or False. If False, the button is greyed out on the screen and thus any attempt to click it does nothing. If True, the button behaves normally.

As soon as the program starts we want btnOne to be enabled but btnTwo to be disabled.

Remember that the Form_Load event procedure is executed at start up. Hence we need to put the following code into this procedure:

btnOne.Enabled = True btnTwo.Enabled = False

As soon as btnOne is clicked, then we want to reverse the situation of the buttons. Thus we need to put the following code into the btnOne_Click event procedure:

btnOne.Enabled = False btnTwo.Enabled = True

As soon as btnTwo is clicked, then again we want to reverse the situation of the buttons. Thus we need to put the following code into the btnTwo_Click event procedure:

btnOne.Enabled = True btnTwo.Enabled = False

Hence the final program code will be:

Public Class frmTopic3Tasks Dim S As String Private Sub frmTopic3Tasks_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load

btnOne.Enabled = True btnTwo.Enabled = False

End Sub

Private Sub btnQuit_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnQuit.Click

Application.Exit() End Sub

Private Sub btnOne_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnOne.Click

btnOne.Enabled = False btnTwo.Enabled = True txtDisplay.Text = "" S = "Testing Scope of Variables, One"

End Sub

Private Sub btnTwo_Click(ByVal sender As System.Object, _

Page 63: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 63 of 123

ITP Student Workbook v2 1.docx

ByVal e As System.EventArgs) Handles btnTwo.Click btnOne.Enabled = True btnTwo.Enabled = False txtDisplay.Text = S

End Sub

End Class

Task 10

Test the above program.

3.4.6 A Simulation Exercise

Computers are often programmed to simulate something in the real world.

Many aspects of the real world are random. This means that many things that happen cannot be predicted. The best we can do is to have an idea of the chance that something will happen. For example, it is reasonable to suppose that more cars go through a particular road junction at rush hour than at midnight. We could never say just how many but we could get an average by observation.

Some real things are actually designed to produce sets of random numbers. For example, a real die is a machine for producing a series of random numbers that are part of the whole number set 1, 2, 3, 4, 5, 6.

If we want to simulate the throwing of a die on the computer, then we first must have a mathematical model of a die that we could use.

(N.B. All computer models are mathematical expressions or sets of rules, all computer simulations are the running of a program that uses that mathematical model or set of rules.)

Visual Basic provides us with a function Rnd().

If we were to execute:

Dim MyResult as Single Randomize() MyResult = Rnd()

We would find that the value of MyResult is a number between 0 and 0.999999.

If we could execute this code thousands of times and keep the results we would find that every number was in the range 0 – 0.999999 and has an equal chance of coming up.

So these numbers would obey the laws of randomness.

The code line:

MyResult = 6*Rnd()

would give numbers in the range 0 to 5.999999.

MyResult = 1 + 6*Rnd()

Page 64: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 64 of 123

ITP Student Workbook v2 1.docx

would give numbers in the range 1 to 6.999999.

Dim Throw as Integer

Randomize() Throw = Int(1+6*Rnd())

would give one of the whole numbers in the set 1, 2, 3, 4, 5, 6.

{The Int function removes the fractional part of the number leaving a whole number.}

Hence the mathematical model for a die is:

Throw = Int(1+6*Rnd())

3. We are now going to test this model and introduce the ListBox control.

Task 11

1. Start a new project.

2. Construct a form having two buttons (btnQuit, btnThrow); a ListBox (lstResults); and a label (lblHeading) thus:

The code for the click event in the 'btnThrow' button is:

Private Sub btnThrow_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnThrow.Click Dim DieThrow As Integer Dim k As Integer Randomize() For k = 1 To 60000

Application.DoEvents() DieThrow = Int(1 + 6 * Rnd()) lstResults.Items.Add(DieThrow.ToString)

Next k

Page 65: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 65 of 123

ITP Student Workbook v2 1.docx

End Sub

The items in a list box are strings. Hence it is wise to convert any item, which is not a string, to a string data type before it is added to a list box. Notice the method ToString in the code above.

Before we look in detail at the new controls run the project. Let us look again at the Application.DoEvents() statement.

3. Comment this statement out of the program by putting a ' in front of it.

4. Now run the project again.

5. It may have taken some time for the results to appear in the text box. So let us explain again what Application.DoEvents() achieves.

The program code we were running was quite a long tight loop, which would take over the processor. With the processor thus occupied it would not have time to update the screen.

By including Application.DoEvents() in the loop then the loop is momentarily paused and Windows is allowed some processor time to service any pending requests from peripherals.

Of course the inclusion of Application.DoEvents() would make the running time of the program code a little longer but it gives a much more encouraging experience to the user. There is little worse than having to look at a screen that seems to be doing nothing.

The ListBox control is one that we use frequently when using Windows applications. For example, every time we select a folder for saving our work we are using a ListBox control.

In the code we have just tested, a ListBox control was used to store the results of the die scores. To do this we used the ListBox.Items method Add.

NOTE: Items is an example of a Collection. All Collections have some common properties and methods for example the property Count and the method Add. Later we shall see that the screen controls on a form automatically create a Controls Collection.

Once items are in a ListBox control, an individual item may be selected by clicking it.

Some properties and methods of the ListBox control

lstResults.SelectedItem is the property that gives the item selected.

lstResults.SelectedIndex is the property that gives the position of the item selected.

{the top item is at position zero, if the value is -1 then no item has been selected; the property can be set by a program statement}

lstResults.Items.Count is the property that gives the number of items in the ListBox.

LstResults.Items.Add (<String>) is the method that adds an item to the bottom of the ListBox.

lstResults.Items.RemoveAt (<P>) is the method that removes an item from position P in the ListBox.

lstResults.Items.Remove (<String>) is the method that removes the first item that matches the <String> in the ListBox.

lstResults.Items.Clear() is the method that removes all items for the ListBox.

Page 66: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 66 of 123

ITP Student Workbook v2 1.docx

Task 12

1. Design and implement experiments to demonstrate each of the properties and methods above.

Page 67: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 67 of 123

ITP Student Workbook v2 1.docx

3.5 Private Study Exercises

Exercise 1

State when the Form_Load event is activated.

Exericse 2

Explain why a screen object is better called a screen control.

Exercise 3

State what is meant by a default value and give an example.

Exercise 4

Explain why it is important to give forms unique names.

Exercise 5

State what function has been used in this chapter to allow the user to input data.

Exercise 6

State what is meant by a Local Variable.

Exercise 7

State what scope a variable has when it is declared at the Class level of a form.

Exercise 8

Explain the difference between a model and a simulation.

Exercise 9

Describe the types of projects that require random numbers.

Exercise 10

Describe a situation where the Application.DoEvents() statement should be used.

Exercise 11

1. Create a suitable project to investigate the behaviour of the following Click_Event procedure of a button.

Private Sub btnDisplayTimeNow_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnDisplayTimeNow.Click

Dim StartTime as Object StartTime = Now txtDisplayTimeNow.Text = Format(StartTime, "hh:mm:ss'')

End Sub

(The Object data type can be used when it is unsure which data type is required or there is no data type that suits the problem. There is no Time data type. Generally a variable declared as Object will attempt to take on the guise of another data type depending how it

Page 68: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 68 of 123

ITP Student Workbook v2 1.docx

is used. Do NOT be tempted to declare all variables as Object as this can slow the program and hide errors)

2. Using knowledge gained from this experiment produce a stopwatch project.

There should be two buttons; START and STOP and three text displays labelled Starting Time; Ending Time; Elapsed Time.

You must prevent the STOP button being pressed before the START button

Exercise 12

1. Start a new project.

2. Create two Buttons btnDIE1 and btnDIE2 with Text property DIE1 and DIE2.

3. Label two empty text boxes as "Number of Attempts";

"Score this Attempt".

4. Produce the code that will simulate the throwing of a die for both DIE1 and DIE2. Note DIE1 must be thrown first and the system must prevent the DIE2 button being used before the DIE1 button. {You will need to use the Enabled properties of the DIE buttons.}

After each pair has been thrown, then the displays shown in the text boxes should be updated.

The user may continue to throw pairs until a score greater than 9 is achieved. Use the MessageBox.Show statement to pause the final result.

Note: The RANDOMIZE & RND() Statements.

Page 69: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Topic 4

Page 69 of 123

ITP Student Workbook v2 1.docx

Topic 4: Project Definition and Design

4.1 Learning Outcomes

On completion of this topic, you will be able to:

Understand and use the debugging facilities provided by the IDE;

Program nested loops;

Use multiline textboxes;

Understand the concept of a class;

Understand that an object has to instantiated;

Instantiate form objects;

Understand the importance of project design;

Understand the importance of testing;

Use an Object Definition Sheet;

Design, Implement, Test and Document solutions to non-trivial programming problems.

4.2 Notes to Teachers and Students

This topic introduces more aspects of the Integrated Development Environment and an elementary ritual for designing a solution to a programming problem.

Concepts introduced in Topic 4 include:

Debugging facilities

The Immediate Window

The Locals Window

Multiline text boxes

Multiple forms

Worked example to show specification, design, implementation and testing

Student assignment

4.3 Timings

The approximate amount of time that you can expect to spend on each type of activity in this topic is as follows:

Lectures: 2 hours

Laboratory Sessions: 8 hours

Private Study: 10 hours

Page 70: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 70 of 123

ITP Student Workbook v2 1.docx

4.4 Student Manual

4.4.1 The Immediate Window

This window acts as crude output area in the IDE. When a project is in ‘break’ mode then:

Values are written to this area via Debug.WriteLine or Debug.Write statements

A line of VB statements can be executed by entering them into this window.

Task 1

1. First we must open the Immediate Window: Debug - Windows – Immediate. Right click the banner of this window; click Floating.

2. Start a new project with just one button on the form whose click event procedure contains the program code:

Private Sub btnTestMoreWindows_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnTestMoreWindows.Click Dim a, b, d As Single Dim c as Single = 0 Dim k As Integer a = 98.9 b = 45.6 d = 78.9 For k = 1 To 4

c = a + b + c Debug.WriteLine(c)

Next k MessageBox.Show("Finished") End Sub

As was said above, we can only use the facility of the Immediate Window if the program is in ‘break’ mode. Commonly we need to concentrate on a particular area of our code where we suspect there may be a problem. To do this we set a Break Point at a particular statement by clicking in the left hand column of the code window.

3. Set a Break Point on the statement Debug.WriteLine(c)

4. Run the project.

5. Click the button once; the project should now be in Break mode.

6. Now arrange your whole screen to look like this:

Page 71: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 71 of 123

ITP Student Workbook v2 1.docx

At this point the program has been suspended at the statement Debug.WriteLine(c).

This statement has not been executed but all above it have been executed once. Thus all the variables will have non-zero values at this stage. The easiest way to look at these values is to hover the mouse over a variable name. Notice how the values are displayed.

7. Now move the program on by one statement by pressing F8.

The statement Debug.WriteLine(c) had the effect of displaying the current value of c in the Immediate Window.

8. Continue to press F8 and observe what happens as each statement is executed. Check that the values that have appeared in the Immediate Window are what you expected.

(You may need to click on the line where the break has occurred before pressing F8)

9. Experiment to distinguish between the effects of the methods

WriteLine and Write

Thus during development of a solution, the Output window could be used as a readymade display area.

10. Run the program again and click the button once, as before so we are in break mode again.

11.Type the following line into the Immediate Window:

btnTestMoreWindows.BackColor = Color.Red :Application.Doevents()

followed by the return key.

The button on the form should have turned red.

This shows that whilst in break mode we can type a line of VB code into the Immediate Window and have it executed immediately. This can be useful to check the action of a VB statement.

Page 72: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 72 of 123

ITP Student Workbook v2 1.docx

(Typing ? a would display the current value of the variable a in the Immediate Window.)

Note that Application.Doevents() is required to ensure that the previous instruction is carried out when an alteration to the appearance of the form is involved.

There are certain restrictions on what VB code can be typed in the Immediate Window:

? a : ? b will not work but Debug.Write(a):Debug.Write(b) does.

No loop structures are valid in the Immediate Window

Task 2

This is an exercise on nested loops.

1. Start a new project.

2. Place a button named btnTriangle on the form.

3. With the help of just two different Debug. statements i.e.

Debug.Write( "*") and Debug.WriteLine(" ") (Note that you should only use each of these statements once.)

write a click procedure for the button that would produce the following pattern in the Immediate Window.

* ** *** **** ***** ******

4.4.2 The Locals Window

The Locals Window is very informative as it displays a list of the current values in all the variables in the procedure where the break has occurred.

However the Locals Windows can be elusive. On the one hand, it may appear automatically as a program is run but if it does not it has to be switched on whilst the program is in ‘break’ mode. To do this: Debug – Windows – Locals.

Task 3

1. Go back to Task 1. Modify the Text property of the button. Make sure that both the Immediate and Locals widows are floating.

2. Run the program, click the button and press F8 once. Arrange the screen thus:

Page 73: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 73 of 123

ITP Student Workbook v2 1.docx

3. Examine carefully the information that is given in the Locals Window. Press F8 again and note the change in the value of the variable c.

4.4.3 Multiline Text Boxes

Task 4

1. Start a new project.

2. Place a text box and a button on the form.

Set the Multiline Property of the text box to True. Set the ScrollBars Property of the text box to Vertical.

3. Place the following code in the click procedure for the button.

Private Sub btnLotsOfLines_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnLotsOfLines.Click Dim MyOutPut As String Dim k As Integer MyOutPut = "" For k = 1 To 200

MyOutPut = MyOutPut & "This is Line " & k.ToString & vbCrLf Next k txtOutPut.Text = MyOutPut End Sub

4. Test the code.

So what has happened? We have only used statement with the textbox; txtOutPut.Text = MyOutPut but we see 200 lines of text in the textbox.

Page 74: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 74 of 123

ITP Student Workbook v2 1.docx

The only thing that we set the Text property to was the string MyOutPut. Hence the string MyOutPut must have been a large string of characters representing all the 200 lines and the control characters that arrange the new lines.

This was done by the loop: For k = 1 To 200

MyOutPut = MyOutPut & "This is Line " & k.ToString & vbCrLf Next k

This loop generated each line required and accumulated them into one string.

Note:

The contents of a text box is ALWAYS just one string.

To give the appearance of separate lines, the program code has to insert the formatting characters into the string by using the VB constant vbCrLf.

4.4.4 More than One Form

A project can support any number of forms.

The initial form that is shown is the one that you have defined as the StartUp form.

You must bring up all other forms by using the Show method after you have created an instance of the form itself.

This is a little difficult to understand. A form is an object. All objects are built according to a design that has been defined before.

With our single form projects, we have been able to gloss over this process because our form has always been the StartUp Object. The mechanism of the StartUp Object creates an instance of that object.

To include other form objects in the project, we must first create the design of the form and then create an instance of the form by a declaration (Dim).

Task 5(a)

1.Start a new project.

2. Name the first form as frmONE and make it the StartUp form.

3. Add another from to the project (Project – Add Windows Form).

4. Name the second form frmTWO. Put a button on the second form whose click procedure contains a MessageBox to display any message you wish.

Page 75: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 75 of 123

ITP Student Workbook v2 1.docx

5. On the first form add a button with the program code:

Private Sub btnLoadSecondForm_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnLoadSecondForm.Click

Dim F As New frmTwo() 'Creates an instance of the second form F.Show() 'Makes the second form visible and active

End Sub

6. Run the project and observe the second form appear when you click the button on the first form. Click the button on the second form to see the message you have put in the MessageBox.

However there could be a problem.

If you click the button in frmONE again you will get another instance of frmTWO and another and another!!!

This is because frmTWO has been shown as a non-modal form, which means you can freely switch attention from frmTwo to any other form.

To get over this problem we need to show frmTWO as a modal form, which means that it has to be closed before another form can receive attention.

To implement this replace F.Show() with F.ShowDialog()

Now you will find that you cannot move to frmONE unless you have closed frmTWO.

We can make things even better by putting some control buttons on frmTWO to produce the familiar dialog controls OK and Cancel.

7. On frmTWO add buttons btnOK and btnCancel.

8. Add program code thus:

Private Sub btnOK_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnOK.Click

Me.DialogResult = DialogResult.OK Me.Close()

End Sub Private Sub btnCancel_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnCancel.Click Me.DialogResult = DialogResult.Cancel Me.Close()

End Sub

9. Now add a label (lblMessage) to frmOne and modify the program code in the button thus:

Private Sub btnLoadSecondForm_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnLoadSecondForm.Click

Dim F As New frmTwo() 'Creates an instance of the second form If F.ShowDialog() = DialogResult.OK Then 'Shows and

'tests the response in the second from

lblMessage.Text = "OK Clicked in the second form" Else

Page 76: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 76 of 123

ITP Student Workbook v2 1.docx

lblMessage.Text = "CANCEL Clicked in the second form" End If

End Sub

Now you may close the second form either by clicking on OK or Cancel but in addition the calling form reports on how the called form was closed.

Task 5(b)

Demonstrate another way to prevent multiple instances of the form F. (Hint: Think about where F is declared)

4.4.5 An Important Worked Example

There are two objectives of this worked example:

1. To introduce a methodology of planning a Visual Basic event driven solution. (See the OBJECT DEFINITION SHEET and the way in which the EVENT PROCEDURE CODE is detailed.).

2. As a preparation for the sample assessment assignment set as the next task.

4.5.1 WORKED MINI PROJECT

Make sure you understand every line of this example and take the trouble to copy it into your computer to see if it works.

Task 6

A rudimentary way to specify a project is to define, in a simple way, the outcomes required from the point of view of the user interface. Hence below we have a definition of the major controls that make up the user interface together with a short list of the outcomes required by the user.

Major Screen Controls Required Two ListBoxes named lstPricePds and lstPriceEuros. A multiline TextBox named txtPriceBoth

Page 77: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 77 of 123

ITP Student Workbook v2 1.docx

Required Outcome 1 When the project is run the list box lstPricePds will display a number of items structured thus: One fixed length string per item consisting of a name of a vegetable with the last three characters being digits that give the price in pence per kilo.

Required Outcome 2

When an item in lstPricePds is double clicked then its price per kilo is converted to Euro cents (assume €1.14 to the £1) and the converted item is added into the ListBox lstPriceEuros. The items in lstPriceEuros are to be displayed in alphabetical order.

Required Outcome 3

Once the conversion is complete a line something like: Pea £ 1.33 = € 1.52

should be added to the text box txtPriceBoth

The information in this rudimentary specification is used to complete an Object Definition Sheet form to assist Project Control.

PROJECT CONTROL

OBJECT DEFINITION SHEET

Non Default Properties at Design Time Event procedures that have to be written

Obj.Ref. Object Type Property Value Event Procedure

1 Form Name frmDemoListBox Form_Load ()

Text DEMO ListBoxes

2 Button Name btnQUIT btnQUIT_Click ()

Text Quit

3 Label Name lblBothPrices None

Text BOTH PRICES

4 ListBox Name lstPricePds lstPricePds_DblClick

Font Courier New

5 ListBox Name lstPriceEuros None

Font Courier New

Sorted True

6 TextBox Name txtPriceBoth None

Font Courier New

Multiline True

Text Null

ScrollBars Vertical

Page 78: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 78 of 123

ITP Student Workbook v2 1.docx

The next stage is to design and code the event procedures required.

This is done below in a way that is suitable for simple project control documentation.

Object Reference Number: 1 Object Type: Form

Code:

Private Sub frmDemoListBox_Load(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles MyBase.Load

lstPricePds.Items.Add ("Potato 149")

lstPricePds.Items.Add ("Red Pepper 343")

lstPricePds.Items.Add ("Cauliflower 193")

lstPricePds.Items.Add ("Carrot 075")

lstPricePds.Items.Add ("Pea 132")

lstPricePds.Items.Add ("Courgette 207")

lstPricePds.Items.Add ("Onion 168")

lstPricePds.Items.Add ("Green Bean 149")

lstPricePds.Items.Add ("Mushroom 243")

lstPricePds.Items.Add ("Broccoli 203")

End Sub

(Note that the above code is displayed in the font Courier New. In Courier New, each character is the same physical width on paper and on a computer screen. Thus it is important to set the font of a ListBox to Courier New when neat tabulation is required.)

Simple Test Criteria

When the form is loaded then the details of the vegetables should be listed in the ListBox lstPricePds.

Object Reference Number: 2 Object Type: Button

Code:

Private Sub btnQUIT_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles btnQUIT.Click

Application.Exit()

End Sub

Simple Test Criteria

A single click on the QUIT button should terminate the run.

Object Reference Number: 4 Object Type: ListBox

Code:

Private Sub lstPricePds_DoubleClick(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles lstPricePds.DoubleClick

Dim Temp, Veg As String

Dim Pence, Pounds, Cents As String

Dim Euros, Converted, TwoPrices As String

Dim ExchangeRate As Single

ExchangeRate = 1.14

Page 79: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 79 of 123

ITP Student Workbook v2 1.docx

Temp = lstPricePds.Text

Veg = Temp.Substring(0, Temp.Length - 3)

Pence = Temp.Substring(Temp.Length - 3)

Cents = Format(ExchangeRate * CInt(Pence), "000")

Converted = Veg & Cents

lstPriceEuros.Items.Add(Converted)

Pounds = Format(CInt(Pence) / 100, "0.00")

Euros = Format(CInt(Cents) / 100, "0.00")

TwoPrices = Veg & " £" & Pounds & " = " & "€ " & Euros

txtPriceBoth.Text = txtPriceBoth.Text & TwoPrices & vbCrLf

End Sub

Simple Test Criteria

A double click on an item displayed in the ListBox lstPricePds should:

Select that item; Add information to the ListBox lstPriceEuros (sorted); Add information to the TextBox txtPriceBoth.

You might start testing this example by constructing a form that looks something like:

Note that this design of the form corresponds to the detail in the Object Definition Sheet.

Insert the program code in the specified event procedures and test the project.

Make sure you understand each line of the program code.

REMEMBER: one of the main reasons for this worked example was to give you a simple methodology of designing and starting the documentation of a project.

Page 80: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 80 of 123

ITP Student Workbook v2 1.docx

Task 7 (Optional)

In the worked example the exchange rate was fixed in the program code.

It would be better if the user could type in a new rate in the form via text box.

A revised form might look like this:

The extra information at the top of the form is actually made up of two labels and one text box.

The rate 1.14 has been set as the text property of the text box at design time. When the revised project is running, the user can type in a new rate at any time. The new rate is applied to any further vegetables selected.

Enhance the existing worked example to produce this revised version.

Page 81: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 81 of 123

ITP Student Workbook v2 1.docx

4.5 Private Study Exercises

Exercise 1

Give two examples of the use of the Immediate Window. Describe how the Immediate Window can be cleared.

Exercise 2

Describe the purpose of a break point and how it can be set to a particular line of program code.

Exercise 3

Describe the contents of any text box from a data type point of view.

Exercise 4

Distinguish between Modal and Non-Modal forms.

Exericse 5

4. State when it is useful for program code to be placed in the Form_Load event procedure.

Exercise 6

A list box control supports both a click event and a double click event. Explain why, in general, program code is placed in the double click event of a list box.

Exercise 7

1. Start a new project. Make one form with three buttons; DISPLAY1, DISPLAY2 and QUIT.

2. Make another form with a text box setting the multiline property to TRUE and give it a vertical scroll bar.

3. Complete the project such that clicking on DISPLAY1 would show the second form with its text box containing:

LINE 1 OF DISPLAY 1 LINE 2 OF DISPLAY 1 ... LINE 50 OF DISPLAY 1

and a similar action for clicking on DISPLAY2.

Exercise 8

1. Start a new project. Create a form with two buttons Next_Ten and Quit.

2. Create another form with a text box setting the multiline property to True.

3. Complete the system such that clicking on Next_Ten for the first time would show the second form with its text box containing a table of the first 10 pairs of X and Y values where:

Y = X x X - 5 x X - 6; X starts at -2 and increments by +1

Page 82: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 82 of 123

ITP Student Workbook v2 1.docx

Each subsequent time the button Next_Ten is clicked then the text box in the second form should be overwritten by the next ten pairs of values of X & Y.

Page 83: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 83 of 123

ITP Student Workbook v2 1.docx

4.6 Sample Midcourse Assignment

IMPORTANT NOTE: This is a sample of the assignment you are expected to complete (i.e. not the actual assignment). This is designed to allow you to practice the type of tasks you will need to undertake. The actual assignment will depend on the assessment cycle for which you are registered. Your teacher will give you a copy of the actual assignment that you must complete for your assessment in this module. Your teacher will also set a deadline for the submission of your assignment.

Various clues to the solution of the problem detailed below can be found by careful study of the worked example above.

TASK

The task is to design a screen form and associated procedures that will enable a user to select THREE criteria for an intended aeroplane flight.

The three criteria are: Departure Point, Destination Point, and Type of Seat. (Think of testing your system with about eight departure and destination points and three different seat types.)

It is suggested that the core of your form is three List Boxes.

The initial contents of the List Boxes can be set up in the Form_Load event procedure.

The departure and destination list will have to be maintained in alphabetical order.

Other things that you will have to consider are:

1. Can you use colour to advantage?

2. Can you use images to advantage?

3. How would you present the final selection:

a. in a text box?

b. on a separate form?

4. How to maintain the system by adding or removing items to and from the departure and destination lists?

5. There are security issues here hence you will have to consider implementing some password protection for the maintenance facilities.

NOTES

1. A ‘realistic’ implementation of this system would require file handling.

2. You are not expected to be able to include file handling at this stage of the course.

Page 84: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 84 of 123

ITP Student Workbook v2 1.docx

3. Take the time required to design the project before you type any program code. Follow the design and documentation sequence that was demonstrated in the worked example above.

4. Remember you have to present documented solutions to problems for your coursework. Always document your designs BEFORE you implement them. Keep up to date Object Definition Sheets and do basic tests at each stage of the development.

5. A blank Object Definition Sheet is given for you to copy:

PROJECT CONTROL

OBJECT DEFINITION SHEET

Non Default Properties at Design Time Event procedures that have to be written

No. Type Property Value Event Procedure

Page 85: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Topic 5

Page 85 of 123

ITP Student Workbook v2 1.docx

Topic 5: Programming More Complex User Interfaces

5.1 Learning Outcomes

On completion of this topic, you will be able to:

Program the controls Radio Button, Check Box, Combo Box

Understand the nature of a subscripted variable

Understand the nature and functionality of one dimensional arrays

Program arrays to select

Program arrays to search

Program the Sort Method

Design and program menus

5.2 Notes to Teachers and Students

This topic introduces more screen controls including menus to facilitate appropriate user interfaces. Subscripted variables are introduced via a workshop experiment.

Concepts introduced in Topic 5 Include:

Radio (Option) Button screen control

Check Box screen control

Workshop activity to introduce arrays

Sort method

ComboBoxes

Menus

5.3 Timings

The approximate amount of time that you can expect to spend on each type of activity in this topic is as follows:

Lectures: 1 hours

Laboratory Sessions: 5 hours

Private Study: 4 hours

Page 86: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 86 of 123

ITP Student Workbook v2 1.docx

5.4 Student Manual

5.4.1 Radio (Option) Buttons

Radio buttons act in groups. Only one member of the group can be "on" at any one time.

However each radio button is a separate screen object and has its own properties, methods and can experience its own events.

The purpose of a Radio Button group is to select an immediate or future direction of action from a number of possibilities.

This selection can be achieved in two ways.

1. By program code in the event procedures of the radio buttons themselves.

2. By program code elsewhere that looks at which option is selected.

Task 1

The purpose of this task is to control the fore colour and back colour of the contents of a particular textbox control.

To make radio buttons act as a group and not interact with any other group they must be drawn into a container object.

A suitable container object is a GroupBox Control.

1. Place two GroupBox Controls, a Label and a Textbox on a form.

2. In each of the GroupBoxes draw (don't double click) a set of three Radio Buttons thus:

Page 87: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 87 of 123

ITP Student Workbook v2 1.docx

Notice the hot keys. These were set by typing & before the desired hot character when the Text property was set in the properties window. The purpose of hot key is to ‘click’ a control using the keyboard rather than the mouse. For example, to focus the Red radio button: press the Alt key and whilst keeping it pressed press R.

(Unfortunately when the project is running the underlining of the hot keys disappears, although the hot key action works.)

3. Run the project and notice how the two sets of option buttons are independent.

We now put some code into the Form_Load and the click events of the option buttons to control the colour and font size of any text that is in the text box.

Private Sub frmOptions_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load

rbGreenFore.Checked = True rbCyanBack.Checked = True txtOutPut.ForeColor = Color.Green txtOutPut.BackColor = Color.Cyan txtOutPut.Text = "Some Initial Text"

End Sub Private Sub rbRedFore_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles rbRedFore.Click

If rbRedFore.Checked = True Then txtOutPut.ForeColor = Color.Red

End If End Sub Private Sub rbGreenFore_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles rbGreenFore.Click

If rbGreenFore.Checked = True Then txtOutPut.ForeColor = Color.Green

End If End Sub Private Sub rbBlueFore_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles rbBlueFore.Click

If rbBlueFore.Checked = True Then txtOutPut.ForeColor = Color.Blue

End If End Sub Private Sub rbYellowBack_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles rbYellowBack.Click

If rbYellowBack.Checked = True Then txtOutPut.BackColor = Color.Yellow

End If End Sub Private Sub rbCyanBack_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles rbCyanBack.Click

If rbCyanBack.Checked = True Then txtOutPut.BackColor = Color.Cyan

End If End Sub

Page 88: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 88 of 123

ITP Student Workbook v2 1.docx

Private Sub optMagentaBack_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles optMagentaBack.Click

If optMagentaBack.Checked = True Then txtOutPut.BackColor = Color.Magenta

End If End Sub

4. Insert the program code and test the project.

5. Notice the Checked property of the radio buttons.

You can alter the text in the text box by typing whilst the project is running.

The approach used in this task is to have the code in the radio button’s own event procedures. The next Task uses a quite different approach.

Task 2

1. Start from the solution to Task 1. Copy all the code that was in the option buttons to the TextChanged event procedure of the text box:

Private Sub txtOutPut_TextChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles txtOutPut.TextChanged

If rbRedFore.Checked = True Then txtOutPut.ForeColor = Color.Red

End If If rbGreenFore.Checked = True Then

txtOutPut.ForeColor = Color.Green End If If rbBlueFore.Checked = True Then

txtOutPut.ForeColor = Color.Blue End If If rbYellowBack.Checked = True Then

txtOutPut.BackColor = Color.Yellow End If If rbCyanBack.Checked = True Then

txtOutPut.BackColor = Color.Cyan End If If rbMagentaBack.Checked = True Then

txtOutPut.BackColor = Color.Magenta End If

End Sub

2. Now comment out all the code from the radio buttons. (Note: You could also remove the code but once you have gone to the trouble of entering code it may be better to preserve it for future use by commenting it out. Note the menu items ‘Comment out the selected lines’ and ‘Uncomment the selected lines’.)

3. Run the project.

4. Select a new foreground colour and background colour. Nothing should happen. Now type into the text box. At once the new colours will appear.

Here the approach is to use code to refer to the states of the option buttons.

Page 89: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 89 of 123

ITP Student Workbook v2 1.docx

5.4.2 Check Box

A check box acts by itself. Like a radio button, it has a Checked property that takes on values of True or False.

Task 3

1. Set up a text box that displays a list of ten random numbers in the range 10 to 50.

The code to generate the numbers is best in the Form_Load procedure.

2. Use the Format function to convert a numeric value to a set of displayable characters and to define the format of the number: e.g. Format(<value>, "00.000") would ensure that the number is displayed correct to three decimal places.

3. On the same form, set up a check box such that:

The check box toggles the colour of the numbers displayed from black to red.

5.4.3 Arrays

5.4.3.1 A Physical Experiment

For this experiment, you will need:

Six identical cups. Number them 1 to 6 so that you can refer to them as Cup One, Cup Two and so on.

A die

A pile of counters (coins would do)

1. Make sure all the cups are empty of counters.

2. Throw the die.

3. Note the score and put a counter in the appropriate cup. {If the die comes up 4 then you would put a counter in Cup Four.}

4. Carry on throwing the die and putting a counter in the appropriate cup for about twenty times.

The six cups now contain the frequency of the scores that the die produced.

5.4.3.2 Programmed Simulation of this Experiment

The six cups are a family. Each member of the family is only distinguishable from another by its position; 1, 2, 3, 4, 5 or 6. Such a structure is represented in VB (and most other programming languages) by an Array.

An array is a family of variables or objects. Each member of the family has a common stem to its name but has an individual subscript.

With reference to our experiment, the stem name of the family could be Cup but the individual names would be Cup(1), Cup(2), Cup(3), Cup(4), Cup(5), Cup(6).

The VB statement:

Page 90: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 90 of 123

ITP Student Workbook v2 1.docx

Dim Cup(6) As Long

sets up an array of seven long integer variables named: Cup(0) Cup(1) Cup(2) …………. Cup(6).

All arrays in VB 2008 are zero based but we don’t have to use the member with a zero index. In this example we shall ignore the existence of Cup(0). To simulate the emptying of the cups we have the program code:

For k = 1 To 6 Cup(k) = 0

Next k

To simulate the throwing of the die and putting the counter in the right cup we have:

For k = 1 To 60000 Throw = Int(1 + 6 * Rnd) 'Note the next program statement 'The value of the throw determines which cup has one added 'to its contents. Cup(Throw) = Cup(Throw) + 1

Next k

Now let’s see the whole code:

Private Sub btnThrow_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnThrow.Click

Dim Cup(6) As Long Dim k As Long Dim ThisThrow As Integer lstScores.Items.Clear() Randomize() For k = 1 To 6

Cup(k) = 0 Next k For k = 1 To 60000

ThisThrow = Int(1 + 6 * Rnd()) 'Note the next program statement 'The value of throw determines 'which cup has one added to its contents. Cup(ThisThrow) = Cup(ThisThrow) + 1

Next k For k = 1 To 6

lstScores.Items.Add(Cup(k).ToString) Next k

End Sub

Task 4

Test the above code.

You will need just one button and a ListBox for the results. Every time you click 'btnThrow' the ListBox will be cleared and another 60000 throws will be simulated.

As there is an equal chance of 1/6 of any of the numbers 1 to 6 being thrown, there should be approximately a score of 10000 for each.

Page 91: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 91 of 123

ITP Student Workbook v2 1.docx

5.4.4 Lists of Data Items

Arrays give us the ability to process lists of data items.

Suppose that we wish to scan a list of numbers and find the values of the largest number and its position in the list. (Assuming that the largest number is unique.)

Task 5

All the following code is in one project.

1. Construct a new project to test this code.

Dim MyNumbers(50) As Single 'This goes directly after Inherits or Class

Private Sub btnGenerateNumbers_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnGenerateNumbers.Click Dim k As Integer Randomize() For k = 1 To 50

MyNumbers(k) = 10 + 50 * Rnd() Next k

End Sub Private Sub btnSeeMyNumbers_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnSeeMyNumbers.Click

Dim k As Integer lstMyList.Items.Clear() For k = 1 To 50

lstMyList.Items.Add(Format(MyNumbers(k), "00.000000")) Next k

End Sub Private Sub btnFindBiggest_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnFindBiggest.Click

Dim k As Integer Dim BiggestSoFar As Single Dim PositionOfBiggestSoFar As Integer BiggestSoFar = MyNumbers(1) PositionOfBiggestSoFar = 1 For k = 2 To 50

If MyNumbers(k) > BiggestSoFar Then BiggestSoFar = MyNumbers(k) PositionOfBiggestSoFar = k

End If Next k lblBig.Text = Format(BiggestSoFar, "00.000000") lblPosBig.Text = Format(PositionOfBiggestSoFar, "00")

End Sub

Points to note about the code

1. It is a test project with each section of the program activated by a button. This is a good technique when experimenting with a new facility.

2. The Rnd() function has been used to generate some test data. Use this idea to test programs that need a lot of data. Try to avoid wasting time typing in blocks of test data.

Page 92: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 92 of 123

ITP Student Workbook v2 1.docx

3. A ListBox has been used to just show the numbers.

4. Labels have been used for simple output. Labels cannot be typed into and thus results cannot be messed up by accidental use of the keyboard.

5. Long variable names have been used to help the code explain itself.

6. Take the time to understand each line of this code; don't forget to use the debugging facility of single stepping to help you.

5.4.5 Sorting

VB 2008 provides a Sort method for a one-dimensional array. (At this stage we confine ourselves to arrays of numbers or strings.)

The syntax to sort the whole of an array is:

Array.Sort(<target array>)

BEWARE as all VB 2008 arrays are zero based then the above syntax would include the element with zero index in the sort.

BUT the Sort method allows the sorting of a section of an array.

The syntax for this is:

Array.Sort(<Target Array>,<Lower Index of Section>, <Upper Index of Section>)

Hence to sort the 50 numbers that we produced in the last task:

Private Sub btnSortAndSee_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnSortAndSee.Click

Dim k As Integer Array.Sort(MyNumbers, 1, 50) 'This one statement sorts the 'Selected range of the array

'Now use a text box to see the result of the sort txtSeeSorted.Text = "" For k = 1 To 50

txtSeeSorted.Text = txtSeeSorted.Text & _ MyNumbers(k).ToString & vbCrLf

Next k End Sub

Task 6

1. Start a new project.

2. Generate an array of ten names.

3. Sort this array in descending alphabetic order.

Note: To sort the array in ascending order then apply the Reverse method i.e.

Array.Reverse(Names)

Page 93: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 93 of 123

ITP Student Workbook v2 1.docx

5.4.6 Combo Boxes

A TextBox allows the user to input data. A ListBox allows the user to select an item from a displayed list. A ComboBox combines the above features of text and list boxes, that is to say, the user can either* input some data into an edit area or the user could select an item from a displayed list.

There are three choices for the DropDownStyle of a Combo Box: (DropDownStyle is a property that is set in properties window at the design mode.)

Dropdown (default) A drop-down list and an edit area; can select or type in.

Simple Displayed list and edit area, can select or type in.

Dropdown List Selection only.

(* Not in the case of a Dropdown List Combo Box.)

Task 7

1. Create a form containing one of each DropDownStyle of Combo Box.

2. Write a Form_Load procedure that will initialise each Combo Box with the names of five different towns. [Hint :Items.Add ]

As you move focus from Combo Box to Combo Box, you would change the text property by either entering or selecting.

Whenever a selection in any of the Combo Boxes is changed the current states of the selections in all three Combo Boxes are to be reported by way of a text box.

This requirement gives us an opportunity of examining the long list of event procedures for a Combo Box.

You will observe that there is a SelectedIndexChanged event. Clicking on this item in the list gives the procedure template:

Private Sub ComboBox1_SelectedIndexChanged _ (ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles ComboBox1.SelectedIndexChanged

End Sub

This event would be fired whenever a selection from the dropdown list of a comb box is changed. Thus we need to put some program code in each of the three such event procedures.

3. Do so and test.

Types 1 and 2 of Combo Boxes allow the text property to be changed by typing. However an item entered into text box part of the Combo Box is not transferred to the list of items in the Combo Box.

The next task is to program the appropriate event procedure such that when an item is typed in and terminated by pressing the RETURN key then the item in the text area is added to the list.

So how to detect that the RETURN key has been pressed?

Again search the list of events and you will find KeyDown.

Private Sub ComboBox1_KeyDown _

Page 94: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 94 of 123

ITP Student Workbook v2 1.docx

(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) _ Handles ComboBox1.KeyDown

End Sub

The question is what program code must we put here. This gives a reason to examine the e parameter(argument) that appears.

Every event has a list of of event arguments, which are relevant to that particular event. We can see what they are by entering e. in the procedure code window thus:

The facility to look at any a particular code of a key is given by e.KeyCode. IntelliSense then gives a list of all the codes of the keys:

We are now in a position to write the code required.

4. Try this:

Private Sub ComboBox1_KeyDown _ (ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) _ Handles ComboBox1.KeyDown

If e.KeyCode = Keys.Return Then ComboBox1.Items.Add(ComboBox1.Text) ComboBox1.Text = String.Empty

Page 95: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 95 of 123

ITP Student Workbook v2 1.docx

End If End Sub

You will need to put the equivalent code in the KeyDown event procedure for the style 2 Combo Box.

However, this would still allow an item already in the list to be added from the text area.

5. Therefore complete this task by preventing this happening.

5.4.7 Menus

For most Windows applications, Menus are the main structure by which the user makes choices.

There are two common places where a menu appears in an application:

At the top of a form, called a Menu Strip in VB 2008

By popping up in the vicinity of a control, called a Context Menu Strip in VB 2008.

Once a menu structure has been designed and realised on a form then we can consider each part of the menu as being akin to a simple button that just has a click event.

All that we have to do is put the required program statements in the appropriate click event procedures.

Task 8 (A Menu Strip)

1. Start a new project.

2. In the toolbox locate the MenuStrip control and drag it on to your form.

As this object will be invisible at run time, a new element named MenuStrip1 appears in the component tray area:

Page 96: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 96 of 123

ITP Student Workbook v2 1.docx

The MenuStrip is an object.

3. Right click MenuStrip1 in the component tray, select Properties.

4. Rename this MenuStrip via its property list. Then click the object in the tray giving:

5. Notice the selected area “Type Here”. This is the first indication that we have entered a Menu Editor. Each time you type in the Text property of a menu item, new “Type Here”s will appear.

6. Design your menu to produce:

Page 97: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 97 of 123

ITP Student Workbook v2 1.docx

7. Only the submenu for Main is shown. Create your own submenus for Starter and Desert.

NOTE the Hot Characters. They are created by placing an & before the required character.

Each time you entered a ‘caption’ into a menu item you set the Text property of that item. Remember that each item is akin to a button. We now need to change the name properties of each menu item.

8. To do this right click each item in turn, select Properties, change the Name property. (The convention is to name a menu item as mnu……… .)

9. Extend the menu structure to the required depth of submenus to specifying the details of the actual part of the meal, including the price that could be ordered.

10. Add another menu item “Order” to the top menu.

11. Add a textbox to the form.

To display the click event procedure templates for the menu items, then just double click on that item.

12. Create the event procedures such that when the “Order” menu item is clicked then the price of that whole meal ordered appears in the text box.

Task 9 (A Context MenuStrip)

1. Start a new project.

2. In the toolbox locate the ContextMenuStrip control and drag it on to your form.

As this object will be invisible at run time, a new element named ContextMenu1 appears in the component tray area:

3. Rename the ContextMenuStrip as mnuPopUp.

Page 98: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 98 of 123

ITP Student Workbook v2 1.docx

4. Click on the ContextMenuStrip to display the menu editor.

We want our context menu to give us the option to change the background colour and foreground of our text box and to place text relating to the foreground colour in the textbox.

The menu is constructed as before using the facilities of the menu editor. If the menu editor for the mnuPopUp is not displayed just click on it in the component tray.

The only thing left to do is to associate the text box with the context menu.

This is done by looking in the property list for the text box and setting the ContextMenu property to mnuPopUp.

5. Test that the ContextMenu works.

Page 99: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 99 of 123

ITP Student Workbook v2 1.docx

5.5 Private Study Exercises

Exercise 1

Distinguish between the uses of Radio Buttons and Check Boxes.

Exercise 2

Pos = 10

Jim(10) = "Kurt" Jim(11) = "Jane" Jim(Pos) = Jim(Pos) & Jim(Pos +1)

Refer to the program code above.

1. Name the array.

2. State the data type of the array.

3. State a sensible data type for Pos.

4. Give the final value in Jim(10).

Exercise 3

Write down a VB program statement that would generate a random number in the range 50 to 60.

Exercise 4

"A menu is like a group of buttons". Describe to what limited extent this statement is true.

Exercise 5

Design, implement and test a menu based project for choosing a holiday. Make this as simple or as complicated as you wish.

Page 100: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Topic 6

Page 100 of 123

ITP Student Workbook v2 1.docx

Topic 6: Programming Serial File Processing

6.1 Learning Outcomes

On completion of this topic, you will be able to:

Understand the terms and concepts Data Item, Record, File;

Understand the nature of a serial file;

Understand the nature of data capture;

Understand the nature and importance of data validation;

Design and Implement a data capture form;

Understand the nature of data streams;

Program the StreamWriter and StreamReader objects;

Understand the importance of common dialogs;

Program the Common Dialog control;

Design, Implement, Test and Document solutions to serial file handling problems.

6.2 Notes to Teachers and Students

This topic exposes students to the fundamentals of simple serial file processing.

Concepts introduced in Topic 6 include:

File

Record

Data item

Data capture form

Data validation

StreamWriter

StreamReader

Peek method

CommonDialog screen controls

Every file is just a sequence of characters. Text-based files are usually human readable and the characters can be edited in a text editor, such as Notepad.

From an application point of view, a file is a collection of organised data about some defined area of interest. For example, personnel records about the employees of a particular company. Such a file would be essential to deal with payroll calculations.

To make such files useful they are generally organised as Data Items and Records.

For example, Data Items concerning a particular individual could include: social security number, name, gender, marital status. The set of data items for one individual is a Record. A set of records makes up the file.

Page 101: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 101 of 123

ITP Student Workbook v2 1.docx

It is important for any particular record to be uniquely identifiable. Thus when designing a record structure, one of the data items is designated to have a unique value i.e. no other record in the file will have the same value. Such a data item is known as the Primary Key. Some primary keys are already to hand, for example the social security number. However in many cases they are generated to suit the application, for example a bank account number.

The processing of files is a very major activity for commercial computer applications leading to complex database structures and processing. Hence modern programming languages have a host of objects, properties, methods and events to allow efficient programs to be developed to deal with database structures.

This course does not deal with database structures but it does introduce the very fundamental processes concerning serial files.

The records of a serial file are in no particular order.

(Beware: Some VB documentation calls serial files, sequential files. This is incorrect; the records in a sequential file are in primary key sorted order.)

6.3 Timings

The approximate amount of time that you can expect to spend on each type of activity in this topic is as follows:

Lectures: 1 hours

Laboratory Sessions: 5 hours

Private Study: 4 hours

Page 102: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 102 of 123

ITP Student Workbook v2 1.docx

6.4 Student Manual

6.4.1 Working with File Streams

VB 2008 supports classes designed to work with streams. Files on a disk drive are thought of as a stream of character data, but sections of computer memory can also be considered as streams as can data travelling in a network. In this course we confine ourselves to simple text files that are stored on a file device.

Task 1

We are going to create a very simple serial text file by writing a sequence of characters to a file device.

1. Start a new project.

2. At the top of the code window type:

Imports System.IO

This is required in order to make the file processing facilities available to your project.

3. Place a button (btnMakeFile) on your form.

4. To create a file we have to use a StreamWriter.

Now type in the following code in to the click procedure of this button; the code window should now look like this:

Imports System.IO Public Class frmTopic6Task1

Private Sub btnMakeFile_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnMakeFile.Click

Dim MyFile As StreamWriter Dim k As Integer

'Open a file for storing new data. 'If there is already a file with 'this name then the data in it will be lost. MyFile = File.CreateText("G:\FileTask1.txt")

' Write 10 records to this file. ' Each record comprises: ' The text 'This is a record' followed by a number in string form. For k = 1 To 10

MyFile.WriteLine("This is record " & k.ToString) Next k

'Close the file MyFile.Close()

End Sub End Class

(Note: This example puts the test file on a Flash Drive; you may decide to put it elsewhere.)

Page 103: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 103 of 123

ITP Student Workbook v2 1.docx

Important Note. If the file already exists then the method CreateText would remove any data in the file. To add data to an existing file use the method AppendText.

5. Run the project and use NotePad to ensure that the file has been created.

6. In order to read the file with VB 2008 code we have to use a StreamReader.

Add another button to your form (btnReadFile) and a list box (lstSeeFile).

7. Copy the code below to the click procedure of this new button.

Private Sub btnReadFile_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnReadFile.Click

Dim MyFile As StreamReader Dim LineOfText As String

' Open an existing file for reading MyFile = File.OpenText("G:\FileTask1.txt") ' We need to keep reading the file until ' the End Of File. ' The method Peek looks ahead in the file, ' without moving the current read position, ' and returns the next character to be read. ' If there are no more characters (EOF), ' then the method returns -1.

Do Until MyFile.Peek = -1

' As each record of our simple file is just one string ' ReadLine will return a record LineOfText = MyFile.ReadLine ' Add a record to a list box for display purposes lstSeeFile.Items.Add(LineOfText)

Loop MyFile.Close()

End Sub

8. Test the code.

9. Notice the use of a Do Loop. Generally the number of records in a file will not be known. The technique is to keep reading the file until a condition occurs that indicates the end of file has been found.

Task 2: More complex records

The following program code creates a serial file with just three records but each record has four data items (ID, Name, Gender, DOB).

Each value is stored on the file as a single string terminated with an end of line marker. The structure of four data items (also known as fields) is a logical concept in this example.

Dim MyFile As StreamWriter Dim ID As Integer = 100 Dim Name As String Dim Gender As String Dim Dob As Date Dim DobString As String

Page 104: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 104 of 123

ITP Student Workbook v2 1.docx

MyFile = File.CreateText("G:\ThisFile2.txt") ID = ID + 1 : Name = "Mary" : Gender = "F" Dob = #1/2/1978# : DobString = Format(Dob, "MM/dd/yyyy") MyFile.WriteLine(ID.ToString) : MyFile.WriteLine(Name) MyFile.WriteLine(Gender) : MyFile.WriteLine(DobString) ID = ID + 1 : Name = "John" : Gender = "M" Dob = #2/3/1979# : DobString = Format(Dob, "MM/dd/yyyy") MyFile.WriteLine(ID) : MyFile.WriteLine(Name) MyFile.WriteLine(Gender) : MyFile.WriteLine(DobString) ID = ID + 1 : Name = "Christine" : Gender = "F" Dob = #3/4/2001# : DobString = Format(Dob, "MM/dd/yyyy") MyFile.WriteLine(ID) : MyFile.WriteLine(Name) MyFile.WriteLine(Gender) : MyFile.WriteLine(DobString) MyFile.Close()

1. Test this code and look at the file produced.

Points to note in this code:

More than one statement can been put in one line so long as the statements are separated by a colon.

ID has been declared as an Integer. This is so we can perform arithmetic on ID thereby generating the ID for each new record: ID = ID + 1.

When the ID is written to a text file a string version is used: MyFile.WriteLine(ID.ToString)

The date of birth (Dob) is stored both as a Date data type and a String data type:

Dim Dob As Date Dim DobString As String

If an attempt is made to enter data in a non date format into a variable with Date data type then an error would occur. Note that date constants are enclosed with # characters.

A date variable stores both the date and time. We only want the date part hence the formatting:

DobString = Format(Dob, Format(Dob, "MM/dd/yyyy")

The format function returns a string; this is fine as we want to write strings to our file.

The code below reads and displays the contents of the file in a list box.

Dim MyFile As StreamReader Dim IDString As String Dim Name As String Dim Gender As String Dim DobString As String MyFile = File.OpenText("G:\ThisFile2.txt") Do Until MyFile.Peek = -1 Loop MyFile.Close()

'Read next record IDString = MyFile.ReadLine : Name = MyFile.ReadLine Gender = MyFile.ReadLine : DobString = MyFile.ReadLine

Page 105: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 105 of 123

ITP Student Workbook v2 1.docx

'Add the record to a listbox lstFileView.Items.Add(IDString) lstFileView.Items.Add(Name) lstFileView.Items.Add(Gender) lstFileView.Items.Add(DobString) Application.DoEvents()

2. Test the code.

6.4.2 Data Capture and Data Validation

We have previously entered data by using the Input function. However, it is better to design forms whereby data is entered via text boxes.

Data validation is the process of detecting if the data input meets specified criteria for example to check that the data is numeric, to check that the data entered is in date format, to check that a particular character or one of a set of characters has been entered.

The following test program has three text boxes and associated labels. Text box txt1 is programmed to accept only numeric characters. There are two ways the user can indicate that entry of data into the text box is complete:

By pressing the Return key. (Needs program code for the KeyDown event.)

Private Sub txt1_KeyDown(ByVal sender As Object, _ ByVal e As System.Windows.Forms.KeyEventArgs) Handles txt1.KeyDown

If (e.KeyCode = Keys.Return) Then If IsNumeric(txt1.Text.Trim) Then

lbl1.Text = "OK" Else

lbl1.Text = "NOT Numeric" End If End If

End Sub

Note the use of the Trim method. This removes leading and trailing spaces which are easily unintentionally entered.

By moving to a different control. (Needs program code for the Leave event.)

Private Sub txt1_Leave(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles txt1.Leave

If IsNumeric(txt1.Text.Trim) Then lbl1.Text = "OK"

Else lbl1.Text = "NOT Numeric"

End If End Sub

Text box txt2 is programmed to accept only entries in date format. The code is similar to before:

Private Sub txt2_KeyDown(ByVal sender As Object, _ ByVal e As System.Windows.Forms.KeyEventArgs) Handles txt2.KeyDown

If (e.KeyCode = Keys.Return) Then If IsDate(txt2.Text.Trim) Then

lbl2.Text = "OK"

Page 106: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 106 of 123

ITP Student Workbook v2 1.docx

Else lbl2.Text = "NOT in Date Format"

End If End If

End Sub Private Sub txt2_Leave(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles txt2.Leave

If IsDate(txt2.Text.Trim) Then lbl2.Text = "OK"

Else lbl2.Text = "NOT in Date Format"

End If End Sub

Text box txt3 is programmed to accept only alphabetic letters. Note that the KeyCode returns the same value for a lower case letter or an upper case letter. It is actually the ASCII code for the upper case letter.

The programming technique is different from above as each character must be examined at the instant it is entered. Thus only the KeyDown event needs to be considered:

Private Sub txt3_KeyDown(ByVal sender As Object, _ ByVal e As System.Windows.Forms.KeyEventArgs) Handles txt3.KeyDown

Dim UP As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" If UP.IndexOf(Chr(e.KeyValue)) <> -1 Then

lbl3.Text = "OK" Else

lbl3.Text = "Not a letter" End If

End Sub

Points to note about this code:

The syntax of the string method IndexOf is: <position> = <str1>.IndexOf(<str2>)

The outcome would be the position of str2 within str1. In the code above str2 is the character that has just been entered into the text box. If no match is found then a value of -1 is returned as the position. So, as long as the position is not equal to -1, then we have a letter, i.e. it is somewhere in the string UP.

6.4.3 ‘Fixed’ Length Strings

VB 2008 does not support fixed length strings i.e. we cannot declare a string to be a specific length. However we can engineer the length of a particular string by program code.

Task 3

When data is to be tabulated for display it is sometimes convenient to have certain data, for example names, stored in strings of the same length.

Look back at the example above where we were validating that the entry to a text box was purely alphabetic. Suppose we were entering a name and we wanted all such names to be stored in a string just 20 characters in length.

Page 107: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 107 of 123

ITP Student Workbook v2 1.docx

This is achievable by using the string method PadRight(<Total Length of string>).This method adds spaces to the right of the string until the whole string is the length defined by the parameter of the method.

The code below uses this method in the Leave event of txt3.

Private Sub txt3_Leave(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles txt3.Leave

Dim Name As String Name = txt3.Text.Trim.PadRight(20) 'Get evidence that Name is just 20 characters 'By displaying its length MessageBox.Show(Name.Length.ToString) 'By displaying Name in a textbox 'and putting a * after the last character. 'Set font to Courier New so you can measure number of characters txtDisplayName.Text = Name & "*"

End Sub

6.4.4 Common Dialog Controls

Whenever we want to open or save a file, a Windows application displays a window that looks almost the same for every application. For example opening a file in Word displays a similar dialog to opening a file in Excel.

Therefore it would be sensible to use such a common dialog display when we are saving or opening our own files via VB 2008.

Task 4

1. Start a new project.

2. Before we start to use common dialog controls we shall set up some class-level procedures.

Looking back to Task 1 we take the program code that is within the two click procedures (for making and reading a file) to create the class-level procedures:

MySaveProcedure MyOpenProcedure

The code window should now look like this:

Imports System.IO Public Class frmCommonDialog

Private Sub MySaveProcedure(ByVal MyFileName As String) Dim MyFile As StreamWriter Dim k As Integer 'Open a file for storing new data. 'If there is already a file with 'this name then the data in it will be lost. MyFile = File.CreateText(MyFileName) ' Write 10 records to this file. ' Each record comprises: ' The text 'This is a record' followed by a number in string form. For k = 1 To 10

MyFile.WriteLine("This is record " & k.ToString) Next k 'Close the file

Page 108: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 108 of 123

ITP Student Workbook v2 1.docx

MyFile.Close() End Sub

Private Sub MyOpenProcedure(ByVal MyFileName As String)

Dim MyFile As StreamReader Dim LineOfText As String ' Open an existing file for reading MyFile = File.OpenText(MyFileName) ' We need to keep reading the file until ' the End Of File. ' The method Peek looks ahead in the file, ' without moving the current read position, ' and returns the next character to be read. ' If there are no more characters (EOF), ' then the method returns -1. Do Until MyFile.Peek = -1

' As each record of our simple file is just one string ' ReadLine will return a record LineOfText = MyFile.ReadLine ' Add a record to a list box for display purposes lstSeeFile.Items.Add(LineOfText)

Loop MyFile.Close()

End Sub

Note: We have replaced the explicit file names by the value of the parameter in the procedures i.e. MyFileName.

3. We are now ready to set up a form that will use the common dialog controls for Saving and Opening a file. Name the form.

4. In the Toolbox locate the SaveFileDialog control. Drag it to the form.

Notice that its graphic does not appear on the form but in an area below the form known as the component tray.

The component tray is an area of the designer window that is provided for controls that will not be visible at run time. This is good as such controls do not interfere with the form user interface design.

5. Name this control SdlgTest1.

6. From the Toolbox, place an OpenFileDialog in the component tray and name it OdlgText1.

7. Place three buttons and a list box on the form thus:

Page 109: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 109 of 123

ITP Student Workbook v2 1.docx

8. Name the save button as btnSaveFile and the open button as btnOpenFile. Now add the program code thus:

Private Sub btnSaveFile_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnSaveFile.Click Dim NameOfFileToSave As String SdlgTest1.Filter = "Text Files(*.txt)|*.txt|All Files(*.*)|*.*" SdlgTest1.FilterIndex = 1 SdlgTest1.ShowDialog() NameOfFileToSave = SdlgTest1.FileName() If NameOfFileToSave <> "" Then

MySaveProcedure(NameOfFileToSave) Else

MessageBox.Show("No File Chosen") End If End Sub Private Sub btnOpenFile_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnOpenFile.Click

Dim NameOfFileToOpen As String OdlgTest1.Filter = "Text Files(*.txt)|*.txt|All Files(*.*)|*.*" OdlgTest1.FilterIndex = 1 OdlgTest1.ShowDialog() NameOfFileToOpen = OdlgTest1.FileName If NameOfFileToOpen <> "" Then

MyOpenProcedure(NameOfFileToOpen) Else

MessageBox.Show("No File Chosen") End If

End Sub

Note: Both these dialog controls have the properties:

Filter This sets up the possible file extensions.

FilterIndex This defines the default file extension.

Page 110: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 110 of 123

ITP Student Workbook v2 1.docx

FileName

- For the Save dialogue this is the name that is typed into the dialog. - For the Open dialogue this is the name that is selected from the dialog.

Once the file name has been assigned then one or other of a class-level procedure is called:

MySaveProcedure(NameOfFileToSave)

or

MyOpenProcedure(NameOfFileToOpen)

In both cases a file name is passed as a parameter to the class-level procedure.

9. Test the system that you have just created.

Page 111: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 111 of 123

ITP Student Workbook v2 1.docx

6.5 Private Study Exercises

Exercise 1

The form below contains:

a. Four Labels

b. Four Text Boxes

c. Four Buttons

Construct a similar form.

This is a data capture form. A record is typed into the form and when the Commit Record button is clicked the record is to be written to a text file.

To help you implement this task, a general description of some of the required event procedures are given. You will have to implement sensible data validation. Your code will have to ensure that buttons cannot be clicked in a wrong order. Also there must be a process that ensures that an ID entered does not exist already in the file.

Declare Form Class level variables:

Dim PartsFileForOutput As StreamWriter Dim FilePath As String Dim Id, DesCription, Price As String

Click event for btnOpenFile The file whose path should be found in the top most text box is opened using the CreateText method (See Task 1).

Page 112: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 112 of 123

ITP Student Workbook v2 1.docx

Leave event for txtPartId The variable Id is given the value of the text property padded right with spaces to 8 characters.

Leave event for txtDescription The variable Description is given the value of the text property padded right with spaces to 15 characters.

Leave event for txtPrice The variable Price is given the value of the text property padded right with spaces to 8 characters.

Click event for btnCommit A record is generated. This record is written to the open file using the WriteLine method (See Task 1).

Click event for btnClose The open file is closed using the Close method (See Task 2).

Use the form to capture some test data and then use NotePad to look at the file you have created.

The next stage of the task is to search the file for records that lie within a specified price range. Add a second form to the project. It should contain four labels, one button, three text boxes and one list box thus:

Design, implement and test a solution.

Exercise 2

You may edit any data displayed in a text box by using the standard Window short cut keys.

CUT Ctrl-X COPY Ctrl-C PASTE Ctrl-V

Page 113: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 113 of 123

ITP Student Workbook v2 1.docx

Hence a simple way of changing a small data file is to:

Display its contents in a text box

Edit the display

Overwrite the file with the edited text.

Design, implement and test a new project named File_Edit.

It should include buttons that allow the user to load a text file of their choice, edit the contents on the screen, and then save the edited text as an edited file with a new name.

Page 114: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Topic 7

Page 114 of 123

ITP Student Workbook v2 1.docx

Topic 7: Programming the Range and Type of Procedures

7.1 Learning Outcomes

On completion of this topic, you will be able to:

Understand the hierarchy of procedures;

Understand the scope of variables;

Understand the nature of parameter lists;

Distinguish between the ways in which procedures may communicate with each other (Higher scope variables, parameters);

Distinguish between ByRef and ByVal;

Distinguish between a procedure and a function;

Understand the nature of a collection;

Use the For Each – Next loop construction to process collections.

7.2 Notes to Teachers and Students

This topic reinforces the work already covered on procedures and extends experience in this area.

Concepts introduced in Topic 7 include:

Event Procedures

Module-Level Procedures

Scope of Variables

Communication between Procedures

Parameters

ByRef

ByVal

Functions

Collections

For Each - Next construction

Sample End of Course Assignment

A procedure is a section of program code that is designed to perform a particular task.

The section of code is bracketed between a Private/Public Sub and an End Sub.

All well-designed and structured programs are made up of a number of procedures. The flow of execution of a programmed system is defined by how these procedures are called and call each other.

Event Procedures are generally sections of code that are executed when visual objects experience specific events; for example, a button is clicked or a character is keyed into a TextBox.

Page 115: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 115 of 123

ITP Student Workbook v2 1.docx

Traditional programming languages did not support Event Procedures.

VB 2008 supports a number of types of procedures.

These include Event Procedures, Form Class-Level Procedures and Module-Level Procedures.

7.3 Timings

The approximate amount of time that you can expect to spend on each type of activity in this topic is as follows:

Lectures: 1 hours

Laboratory Sessions: 9 hours

Private Study: 20 hours

Both the laboratory and private study sessions for this module include time to work on the final module assignment.

Page 116: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 116 of 123

ITP Student Workbook v2 1.docx

7.4 Student Manual

7.4.1 Module-Level Procedures

These procedures are very like the procedures from which traditional programs are constructed. They exist within a Module and can be declared either Private or Public.

A Module-Level Procedure has no specific relationship with visual forms. In fact, it would be possible to consider one Module (there can be several) as similar to the complete environment of a traditional program.

If a procedure in a Module is declared as Public, then its functionality is available anywhere in the whole project.

If a procedure in a Module is declared as Private, then its functionality is available only to other procedures within that Module.

7.4.2 Form Class-Level Procedures

These procedures are located above the event procedures section of a form.

They are declared as Private and their functionality is available from anywhere in that form but not from anywhere else in the project. In most other respects they are similar to Module-Level procedures.

7.4.3 Scope of Variables

A variable that is declared within any procedure is local to that procedure.

A variable that is declared at the form class-level can be referenced anywhere in that form but not from anywhere else.

A variable that is declared as Private within a Module can be referenced from anywhere in that module but not from any other module or any form.

A variable that is declared as Public within a Module can be referenced from anywhere in the project.

It is good and safe programming practice to limit the scope of all variables as much as possible.

7.4.4 Communication between procedures

This can be achieved by using variables that have scope above the procedures that need to communicate. For example, declaring a variable in form class-level allows communication via that variable to and from every event and other procedure in that form.

Mostly it is better practice to communicate via parameters but it must be stressed that each event procedure has its own specific parameter signature and you cannot add your own parameters to an event procedure.

The following walkthrough examples will demonstrate the use of communicating between procedures via parameter lists.

Page 117: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 117 of 123

ITP Student Workbook v2 1.docx

Task 1

We need to have a procedure that will reverse the contents of any string.

This procedure is to be confined to one form.

The following code is placed as a procedure in the class-level of a form.

Private Sub ReverseString(ByVal Original_String As String, _ ByRef Reversed_String As String)

Dim k As Integer Dim Length_of_String As Integer Length_of_String = Original_String.Length Reversed_String = String.Empty For k = 0 To Length_of_String - 1

Reversed_String = Original_String.Substring(k, 1) & Reversed_String Next k

End Sub

The code below, used as a button click event procedure, could be an elementary test for this procedure.

Private Sub btnTest_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnTest.Click

Dim a, b As String a = "Abcde" ReverseString(a, b) MessageBox.Show(a.ToString & " *** " & b.ToString)

End Sub

1. Test the code and then:

2. Create a simple project to demonstrate that the form class-level procedure ReverseString is available from different procedures within the form.

ByRef ByVal

3. Look again at the statement:

Private Sub ReverseString(ByVal Original_String As String, _

ByRef Reversed_String As String)

The parameter Original_String was passed BY VALUE.

The parameter Reversed_String was passed BY REFERENCE.

When a parameter is passed by reference then both the calling procedure and the procedure itself make reference to the same physical storage location for any dealings with the parameter. Thus if the called procedure changes the value of the parameter then that change is passed back to the calling procedure.

When a parameter is passed by value, then a copy of the value of the parameter is passed from the calling procedure to the called procedure using some intermediate storage location to which we have no direct access. Thus if the called procedure changes the values of the parameter then that change is NOT passed back to the calling procedure.

Page 118: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 118 of 123

ITP Student Workbook v2 1.docx

In the example above we did not want the value of the original string to be changed.

Task 2

1. To compare ByRef and ByVal examine the following program code:

Public Class frmByValByRefTest 'This is at the form class-level Dim MyValue As Integer Private Sub TrebleIt(ByRef X As Single)

X = 3 * X lblDisplay3.Text = X.ToString

End Sub

Private Sub frmByValByRefTest_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load

MyValue = 2 End Sub

Private Sub btnTestProc_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnTestProc.Click

lblDisplay1.Text = MyValue.ToString TrebleIt(MyValue) lblDisplay2.Text = MyValue.ToString

End Sub End Class

2. Test this program code. You will need a button and three labels.

Each time you click the button, you will see the trebled value has been passed back to be trebled again.

3. Insert some Debug.Write statements to get the Immediate Window to display the history of the values of the variables MyValue and X.

4. Now replace the statement:

Private Sub TrebleIt(ByRef X As Single)

with

Private Sub TrebleIt(ByVal X As Single)

Page 119: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 119 of 123

ITP Student Workbook v2 1.docx

5. Run the program again and notice that the output does not change no matter how many times you click the button. Thus the value has NOT been passed back.

7.4.5 Functions

Everything that has been said about passing parameters for procedures also applies to functions.

A function is a procedure that uses its name to pass a parameter. A function can pass other parameters via its parameter list in the same way as standard procedures.

As the name of a function has a value then it must have a data type.

Task 3

1. Examine the behaviour of the following program code:

Public Class frmFunctionTest Dim MyValue As Integer

Private Function TrebleItAgain(ByRef X As Single) As Single

TrebleItAgain = 3 * X X = 2 * X lblDisplay3.Text = X.ToString

End Function

Private Sub frmFunctionTest_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load

MyValue = 2 End Sub

Private Sub btnTestFunction_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnTestFunction.Click

lblDisplay1.Text = MyValue.ToString lblDisplay2.Text = TrebleItAgain(MyValue).ToString

End Sub End Class

2. Again alter the ByRef to ByVal and notice the difference.

Task 4

This task involves the following concepts:

Collections

For Each – Next iterative construction (to iterate through a collection of objects)

Module (the highest level for scope in a project)

Control as Data Type (actually an Object Type)

Objects passed as parameters (the actual form in which we are interested is passed as a parameter to a procedure in the module)

A Public Procedure is required such that when it is called from anywhere in a form, then all the buttons in that form have their background colour set to a colour defined by the calling statement.

Page 120: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 120 of 123

ITP Student Workbook v2 1.docx

In this case the parameter list of the procedure must be such that it can identify the calling form and the required colour. As Visual Basic is an object based system, then it is possible to pass object identifiers as procedure parameters.

Moreover, how is it possible for code to distinguish between one form control and another?

The mechanism lies in the concept of Collections.

A collection is a way of grouping a set of objects (not unlike an array). Members of a collection are identified by an index.

Visual Basic automatically keeps track of certain groups of objects such as all the controls on a form (the Controls collection).

The special For Each – Next loop construction is for easy iteration through collections.

A specific control type can be identified by the TypeOf ---- Is structure.

The code below achieves the original specification of the required procedure and has the bonus of illustrating the new program constructs described above.

This code would have to be placed in a module. To insert a module into a project: Project - Add Module.

This gives:

Module Module1 Public Sub CmdsColour(ByVal Current_Form As Form, _ ByRef The_Given_Colour As Object)

Dim One_Control As Control

For Each One_Control In Current_Form.Controls

If TypeOf One_Control Is Button Then

One_Control.BackColor = The_Given_Colour

End If

Next One_Control

End Sub

End Module

1. Test this code by placing several different types of controls (including some Buttons) on a form.

2. Place the following code in the Click event of one of the buttons.

Private Sub btnColourControls_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnColourControls.Click

'Calling procedure in module CmdsColour(Me, Color.Red)

'Showing the array-like nature of a collection MessageBox.Show("There are " & Me.Controls.Count.ToString & " Controls")

Page 121: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 121 of 123

ITP Student Workbook v2 1.docx

MessageBox.Show("Name of second to be placed is " & Me.Controls(1).Name) End Sub

3. Develop the test to show that the procedure works for different colours and for more than one form in the same project.

4. Produce a procedure that when called makes all the TextBoxes on any form to line up with the left-most one.

Page 122: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 122 of 123

ITP Student Workbook v2 1.docx

7.5 Private Study

Please note: This is a practice project, designed to allow you to improve the skills you have aquired throughout the module and prepare for your final examination. Make sure you use the marks and feedback from your teacher to improve any areas of weakness that you have.

Exercise 1: Project

The record structure of a particular serial file is to be:

Data Item Data Type Length Validation

NAME STRING 15 Alpha and Spaces only

GENDER STRING 1 M or F only

STATUS STRING 1 0 Single

1 Married

2 Widowed

3 Divorced

NUMBER OF CHILDREN

INTEGER 2 0 to 15

Design a project, with textboxes in mind, to produce a data capture screen for this data record including the event procedures required for "real time" data validation. The system should be able to recover from any validation error by asking the user to re-enter the offending data.

The screen should have a COMMIT button; when COMMIT is pressed the record is sent to the file and the input text boxes cleared.

Implement and test your system.

Use the data capture form to enter a test file of at least 20 records

Show how you tested your system by annotating screen shots to indicate how your expectations of the system were met.

Extend the design of the system to add a second form the purpose of which is to allow those with a password to edit the file.

Extend the system again to give the system the facility to produce a report from the file to show the details of all the females who have 2 or more children.

Page 123: ITP Student Workbook - basilissachin [licensed for non ...basilissachin.pbworks.com/.../ITP_Student_Workbook... · Overview Page 5 of 123 ITP Student Workbook v2 1.docx 1. Overview

Page 123 of 123

ITP Student Workbook v2 1.docx

Notes on Implementation

Make use of the Enabled property to help to make all forms fool proof.

Always design your testing in the sense of writing down what you are expecting from a test with particular test data. Then give evidence of the actual outcomes of the tests with copies of computer screen shots.

Put explanatory comments in your program code.

Document (may be in rough) your designs and implementation as they happen.

Make good use of the help facility supplied with VB 2008.