MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming...

351
V0.1 i MS Visual Basic 6.0 Programming Introduction NCC Education Limited

Transcript of MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming...

Page 1: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

V0.1 i

MS Visual Basic 6.0Programming Introduction

NCC Education Limited

Page 2: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction

ii V0.1

MS Visual Basic 6 Programming Introduction

File Name butthead\Program Development\VB&Java\VB6

Date: 2nd December 1999

Author David Williams & CWC 1999

Number of pages:

Reviewer: Nick Palmer

Quality Approval:

MODIFICATION HISTORY

Revision Date Revision DescriptionV0.1 2nd Dec 99 Changed headers/footers. Inserted front pages.

Page 3: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction

V0.1 iii

NCC Education Portfolio

Our portfolio includes comprehensive course packages, competence testing and accreditation services. We arealso a publisher of academic textbooks.

Academic Awards

§ International Certificate in Computer Studies§ International Diploma in Computer Studies§ International Advanced Diploma in Computer Studies§ BSc (Hons) in Computer & Information Systems§ BSc (Hons) in Information Systems for Business§ MSc in Information Networks§ MSc in IT – Business Information Systems

Professional Programmes

§ Business Class Seminars§ NCC Certified Professional Engineer§ MSc in Professional Practice in IT§ A+§ E-Commerce§ PC Application Courseware§ Visual Basic§ JAVA

Products

§ Student Materials supporting all NCC Education Courses§ Tutor Training Materials to support our Courses§ Euro PC Test – Automated Test Software for European Computer Driving Licence§ PCDT – Automated Test Software for PC Driving Test

Services

§ Course Accreditation§ Centre Accreditation§ Institute of IT Training – International Division

Page 4: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction

iv V0.1

NCC Education

NCC Education was originally the education division of the National Computing Centre. The NationalComputing Centre was set up by the UK government in 1966 to support and promote the use of computingtechnology within industry. As such, it developed strong links with the Information Technology (IT) industry.

NCC Education Limited became a separate company in April 1997, since when we have introduced many moreIT education programmes to our portfolio. Our mission is to ensure the widespread availability of qualityeducation and training for developers and users of IT.

Experts in our field

NCC Education is one of the world’s leading IT qualification awarding bodies, with numerous academic andprofessional educational and training courses being taught in over 30 countries.

NCC Education’s specialists work with government and national bodies worldwide to devise and implementeducational and training projects. NCC Education’s training programmes are recognised internationally asbeing an effective means for students to advance careers in IT.

NCC Education provides comprehensive support from the outset, from the provision of comprehensive tutor andstudent training materials to moderating the process of training delivery and establishing the assessmentmechanism.

Who are our Partners?

Our unique position bridging IT education and industry allows us to develop partnerships within many differenttypes of organisation. In addition to our work with government and national bodies, our academic programmesare run in IT and business and colleges worldwide our professional programmes are run in colleges, largecompanies and IT training organisations worldwide.

Page 5: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction

V0.1 v

ISO 9001 Quality in Education

Historically, our aim has been to equip the UK with personnel who are competent in using and developing IT inbusiness. As such, quality assurance is a rigorous requirement of all NCC Education products and partners.

NCC Education has gained, and continuously maintained, a quality standard throughout the organisation. Itscertificate number 928858/B was awarded by Lloyds’s Register Quality Company. The NCC Education Qualitymanual states:

NCC Education is unreservedly committed to satisfying its customers through quality in all NCC Education’sproducts and services.

In support of this policy, NCC Education operates a Quality System that provides a framework of standards andprocedures within which it manages and controls all its project, product and service activities.

The Quality System is based on the requirement of the pertinent parts of the ISO 9000 (BS 5750, EN 29000)Series, independently assessed for compliance to the appropriate standard.

Specifically NCC Education’s quality objectives are:

§ To provide the highest quality administration and support to the international qualifications alliedcertification schemes.

§ To ensure that NCC Education accredited centres provide courses that meet the requirements specified inthe NCC Education syllabus and regulations.

§ To specify and maintain syllabi and regulations that meet the career development needs of users andcomputer specialists in the IT community.

§ To ensure where appropriate that syllabi meet national academic standards.

abcdeabcde

Page 6: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction

vi V0.1

Acknowledgements

Director of Course Development...............................................................................................James D.M Minter

Course Developer.................................................................................................................................David Williams

Technical Editor ................................................................................................................................................. Bob Bird

Editor .........................................................................................................................................................James Pengelly

Production....................................................................................................................................................Jeremy Dean

Reprographics ........................................................................................................................................ Grove Printing

COPYRIGHT

This CourseWare is copyrighted: David Williams & CWC 1999. No part of this manual may be

copied, photocopied or reproduced in any form or by any means without the permission in writing

from The CourseWare Company Limited. Violation of these laws will lead to prosecution. All

trademarks, service marks, products or services are trademarks or registered trademarks of their

respective holders and are acknowledged by the authors.

LIMITATION OF LIABILITY

Every effort has been made to ensure complete and accurate information concerning the material

presented in this manual. However, The CourseWare Company Limited cannot be held legally

responsible for any mistakes in printing or faulty instructions contained within this manual. The

authors appreciate receiving notice of any errors or misprints.

Information in this manual is subject to change without notice. Companies, names and data used in

examples herein are fictitious unless otherwise noted.

This CourseWare and all materials supplied for training are designed to familiarise the user with the

operation of software programs. We urge the user to review the manuals provided by the software

publisher regarding specific questions as to the operation of the programs.

There are no warranties, expressed or implied, including warranties of merchantability or fitness for

a particular purpose, made with respect to the materials or any information provided to the user

herein. Neither the author nor publisher shall be liable for any direct, indirect, special, incidental or

consequential damages arising out of the use or inability to use the contents of this manual.

Warning Photochromatic paper, randomly placed, is used in the production of this manual.

Should this paper be exposed to intense light, such as that used in the photocopying process, the

photochromatic paper will turn 100% black and all information will be irretrievably lost.

Page 7: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

V0.1 iii

Table of Contents

Introduction to Visual Basic 6.0...................................................................................................1

Visual Basic Overview.................................................................................................................................................. 1Editions ............................................................................................................................................................................. 2VB Start Up ...................................................................................................................................................................... 2Stopping VB.................................................................................................................................................................... 2New Language Features............................................................................................................................................ 3New Control ................................................................................................................................................................... 3Visual Basic 6.0 and Internet Integration................................................................................................................ 4Win32 API and Visual Basic 6.0.................................................................................................................................. 4Visual Basic Development Environment ................................................................................................................. 5Visual Basic IDE Elements............................................................................................................................................ 6Visual Basic File Types................................................................................................................................................... 8

Understanding VB Development .............................................................................................. 13

Understanding Event-Driven Programming.........................................................................................................14Procedural Applications ...........................................................................................................................................14Event Driven Applications ........................................................................................................................................14Features of Visual Basic.............................................................................................................................................14Working with Objects and Classes.........................................................................................................................15Using an Object's Methods, Properties and Events..........................................................................................16Methods.........................................................................................................................................................................16Examples of methods ................................................................................................................................................16Properties.......................................................................................................................................................................17Setting Properties at Design Time...........................................................................................................................17Setting Properties at Run Time.................................................................................................................................18Getting Properties at Run Time................................................................................................................................18Events .............................................................................................................................................................................19Adding a Menu using the Menu Editor ................................................................................................................20Writing Code.................................................................................................................................................................20Scope of Code............................................................................................................................................................22Using the Object Browser to View Procedures...................................................................................................22Data Types Supported in Visual Basic 6.0 ............................................................................................................23Using Data Types.........................................................................................................................................................24Declaring Variables....................................................................................................................................................24Declaring Constants..................................................................................................................................................25Scope of Variables.....................................................................................................................................................25Program Structures .....................................................................................................................................................27Looping Structures......................................................................................................................................................28Do...Loop .......................................................................................................................................................................28Do While Loop..............................................................................................................................................................28Do Until Loop................................................................................................................................................................29Do Loop While Loop...................................................................................................................................................30If…Then...........................................................................................................................................................................30Syntax.............................................................................................................................................................................30For...Next........................................................................................................................................................................31For Each...Next .............................................................................................................................................................32Select Case...................................................................................................................................................................33InputBox.........................................................................................................................................................................34MessageBox .................................................................................................................................................................35

Page 8: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction

iv V0.1

Intrinsic Controls....................................................................................................................... 39

Intrinsic Controls...........................................................................................................................................................39Picture Box ....................................................................................................................................................................40Label...............................................................................................................................................................................41Text Box..........................................................................................................................................................................42Frame..............................................................................................................................................................................42Command Button.......................................................................................................................................................43List Box............................................................................................................................................................................44Combo Box ...................................................................................................................................................................45Image Control..............................................................................................................................................................46Line and Shape Controls ..........................................................................................................................................47Line Control...................................................................................................................................................................47Shape Control..............................................................................................................................................................48Timer Control ................................................................................................................................................................49Drive List Box Control ..................................................................................................................................................50Directory List Box Control..........................................................................................................................................50File List Box Control......................................................................................................................................................51ScroollBars .....................................................................................................................................................................52Option Button Control ...............................................................................................................................................53Check Box Control .....................................................................................................................................................53Data Control ................................................................................................................................................................54

Visual Basic Practice Exercises................................................................................................. 79

Multiple Document Interface (MDI) ........................................................................................ 131

Multiple-Document Interface (MDI) Applications...........................................................................................131Using MDI in Visual Basic .........................................................................................................................................132Set the Properties......................................................................................................................................................132Create a Menu ..........................................................................................................................................................133Coding..........................................................................................................................................................................133

Visual Data Manager - Worked Example............................................................................... 135

The Data Manager Program..................................................................................................................................135Field Types...................................................................................................................................................................135Create a Database..................................................................................................................................................136A Database with a One to Many Link.................................................................................................................136Set the Key Fields ......................................................................................................................................................137Set the Relationship..................................................................................................................................................137

Database Development in VB ................................................................................................ 139

Data Access Programming Models ....................................................................................................................140DAO - Data Access Objects.................................................................................................................................140RDO - Remote Data Objects.................................................................................................................................142ADO - ActiveX Data Objects..............................................................................................................................143Data Access Choices..............................................................................................................................................143Opening a Table Directly........................................................................................................................................144Accessing ISAM Databases...................................................................................................................................144Distributing the Executables ..................................................................................................................................145Working with Data Files ...........................................................................................................................................145Accessing ODBC Databases.................................................................................................................................146Connecting to a Remote Data Source..............................................................................................................147Retrieving Remote Data.........................................................................................................................................148Data Integrity.............................................................................................................................................................150Defining Validation Rules........................................................................................................................................150Rule Violation Errors ..................................................................................................................................................151Handling Rule Violations .........................................................................................................................................151Referential Integrity..................................................................................................................................................152Preventing Referential Integrity Violations.........................................................................................................153Using Transactions to Improve Performance....................................................................................................153Multiple-User Issues ...................................................................................................................................................154Microsoft Jet Database Engine Locking ............................................................................................................155

Page 9: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction

V0.1 v

Unlocking.....................................................................................................................................................................156Handling Errors on Update.....................................................................................................................................157Handling Errors on Records Deleted by Other Users.......................................................................................157Accessing External Data.........................................................................................................................................158Performance Issues...................................................................................................................................................158

Example Database Programs in VB........................................................................................ 161

Custom Controls..................................................................................................................... 195

MS Chart Control ......................................................................................................................................................195SSTab Control.............................................................................................................................................................197Grid Control................................................................................................................................................................200Solution :.......................................................................................................................................................................202DBGrid Control...........................................................................................................................................................203MSFlexGrid Control...................................................................................................................................................205RichTextBox Control..................................................................................................................................................206MS FlexiGrid Control .................................................................................................................................................209Masked Edit Control.................................................................................................................................................212

MS Windows Common Controls ............................................................................................. 215

Toolbar Control ..........................................................................................................................................................215Status Bar Control .....................................................................................................................................................217Progress Bar.................................................................................................................................................................220Slider Control..............................................................................................................................................................221List View Control ........................................................................................................................................................225TreeView Control.......................................................................................................................................................225ImageList Control ......................................................................................................................................................230TabStrip Control .........................................................................................................................................................232

OLE – Object Linking and Embedding.................................................................................... 233

OLE (Object Linking & Embedding.)....................................................................................................................233OLE in Visual Basic.....................................................................................................................................................233OLE Terminology........................................................................................................................................................234Embedding..................................................................................................................................................................235Linking...........................................................................................................................................................................235Inserting an OLE Object : ........................................................................................................................................235Inserting OLE Objects at Design Time..................................................................................................................236Using Paste Special method at Design Time.....................................................................................................237Properties, Methods and Events of OLE Container Control .........................................................................238Code in Form Module:.............................................................................................................................................239Create Object Statement ......................................................................................................................................243Get Object Statement ............................................................................................................................................244Solution.........................................................................................................................................................................245Solution.........................................................................................................................................................................246

Data Reports........................................................................................................................... 247

Data Report in Microsoft Visual Basic 6.0...........................................................................................................247Features of Data Report Designer .......................................................................................................................247Data Report Controls ...............................................................................................................................................248Adding a Data Environment .................................................................................................................................249Property Tab of Command Object .....................................................................................................................252Creating a Simple Data Report ...........................................................................................................................254Running the Report...................................................................................................................................................256Calling a Data Report through Form...................................................................................................................256Creating a data report using master details relationship.............................................................................257Data Report Events..................................................................................................................................................261Data Report Methods..............................................................................................................................................261Exporting a Report using Object key..................................................................................................................263Printing a Data Report.............................................................................................................................................264

Page 10: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction

vi V0.1

Advanced ActiveX Controls & WIN API.................................................................................. 265

Advanced ActiveX Controls:.................................................................................................................................265Animation Control ....................................................................................................................................................265Winsock Control ........................................................................................................................................................266Internet/Transfer Control .........................................................................................................................................270Web Browser Control ...............................................................................................................................................271Accessing the Microsoft Windows API................................................................................................................272Using the API Viewer Application.........................................................................................................................272Viewing the Win32api.txt file with a Text Editor ................................................................................................273

Validating Input and Handling Errors...................................................................................... 277

Validating Input and Handling Errors ..................................................................................................................277Tools for Debugging .................................................................................................................................................277Validating Field Information...................................................................................................................................278Validating Form Information..................................................................................................................................279Validating All Fields on a Form..............................................................................................................................280Using the QueryUnload Event ...............................................................................................................................280Handling run-time Errors ..........................................................................................................................................281Err Object Properties ................................................................................................................................................282Disabling Error Handling ..........................................................................................................................................283Compiling an Application......................................................................................................................................284Compiling to Native Code.....................................................................................................................................284

Reading and Writing Files ....................................................................................................... 285

Handling Files .............................................................................................................................................................285Reading and Writing Files.......................................................................................................................................286File Functions ..............................................................................................................................................................286Binary and Sequential Files.....................................................................................................................................287Sequential Access ....................................................................................................................................................287Text Files on Disk.........................................................................................................................................................287A Text File Program ...................................................................................................................................................288Open, Save and Close Files - Random Access................................................................................................289Reading Files - Random Access ...........................................................................................................................291Writing Changes Back to Disk - Random Access ............................................................................................291Closing Files - Random Access..............................................................................................................................292Binary Access.............................................................................................................................................................292

Client/Server Architecture...................................................................................................... 293

The Typical Monolithic Application Architecture............................................................................................293Client/Server Architecture (Two-tier Architecture)........................................................................................293Three Tier Architecture ............................................................................................................................................294Types of Binding.........................................................................................................................................................295

ActiveX Code Components ................................................................................................... 297

Introduction to ActiveX Components.................................................................................................................297Creating Objects in Visual Basic...........................................................................................................................298What is a Class Module...........................................................................................................................................298Purpose of a Class Module.....................................................................................................................................298Adding a Class Module to a Project ...................................................................................................................299Creating an Instance of a Class...........................................................................................................................299Class Module Events................................................................................................................................................299Creating Methods.....................................................................................................................................................300Creating Properties ..................................................................................................................................................301Setting and Retrieving a Property........................................................................................................................301Registering a Component ......................................................................................................................................302

Page 11: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction

V0.1 vii

Creating ActiveX Controls...................................................................................................... 323

Introduction to ActiveX Controls..........................................................................................................................323What is a control?.....................................................................................................................................................323Control Classes ..........................................................................................................................................................324Control Components...............................................................................................................................................324Code Components..................................................................................................................................................324UserControl Object ...................................................................................................................................................324Distributing Controls..................................................................................................................................................324Creating an ActiveX control .................................................................................................................................325

Creating & Using ActiveX Documents .................................................................................... 331

Introduction to ActiveX Documents....................................................................................................................331ActiveX Document Containers.............................................................................................................................332ActiveX Documents Vs. Embedded Objects...................................................................................................332ActiveX Documents in VB.......................................................................................................................................332The UserDocument Object ....................................................................................................................................333Working with ActiveX Document Projects.........................................................................................................333Elements of an ActiveX Document Project .......................................................................................................333Creating a New ActiveX Project ..........................................................................................................................334Converting a Existing Standard EXE Project......................................................................................................334Compiling an ActiveX Document Project .........................................................................................................334Where to Site an ActiveX Document..................................................................................................................335

Appendix 1 - Standard Menu Bar........................................................................................... 337

Page 12: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip
Page 13: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

V0.1 1

Introduction to Visual Basic 6.0

Objectives

In this Chapter, you will learn about Visual Basic DevelopmentEnvironment. You will also create your first VB 6.0Application.

• Visual Basic Overview

• Editions

• VB Start Up

• Stopping VB

• VB 6.0 Features

• VB 6.0 and Internet Integration

• WIN 32 API and VB 6.0

• Visual Basic Development Environment

• Visual Basic IDE Elements

• Visual Basic File Types

• Visual Basic Standard Menu Bar

• Your First Visual Basic 6.0 Application

Visual Basic Overview

The Enterprise Edition of Microsoft Visual Basic version 6 provides the programmingenvironment and integrated tools the corporate developer needs to build, test, and deploy large-scale distributed client/server applications.

With these tools and techniques, it is now possible to easily build applications from component"building blocks" that can be shared, reused, and relocated across the network.

This introduces the three-tiered model for distributed application design, along with the tools

and techniques needed to take full advantage of component-based design. It also provides aninnovative set of development strategies that programmers can use to cope with the newchallenges of building distributed applications.

Page 14: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Introduction to Visual Basic 6.0 MS Visual Basic 6 Programming Introduction

2 V0.1

Editions

Visual Basic comes in several different variations. Each of these adds more functionality than the

previous. At this time, the following six editions of Visual basic are available.

♦ Learning edition - demonstration version.

♦ Control Creation edition - Full features, but only builds executable ActiveX controls.

♦ Professional edition - creates all types 32-bit executables for Windows.

♦ Enterprise edition - Same as Professional, plus all of the tools necessary to create enterprise-wide client/server applications.

♦ Application edition - Embedded macro language in Microsoft Office applications.

♦ Scripting edition - Provides server -and client-side scripting in web pages.

VB Start Up

Click start, from the task bar, select programs and then select Visual Basic 6.0. The Windowsoperating system will take you to the Microsoft Visual Basic main screen from where you startexploring VISUAL BASIC 6.0.

Stopping VB

Easy termination of VB is through the standard menu bar. Click File and then Exit to close VB

once for all. Clear screen can be obtained by not terminating VB by minimizing the screen to keepVB session alive to be restored whenever needed.

VB 6.0 Features

There are a lot of new features available in Visual Basic 6. The following are a few goodiesavailable.

♦ ActiveX Data Objects are now included with Visual Basic.

♦ File System Objects offer drive and folder navigation and text file creation without the use ofcontrols.

♦ Format objects provide data conversion and formatting as data moves between a database

and bound control.

♦ There are many new features and enhancements to support Internet integration includingHTML page design with drag and drop control placement, and support for Dynamic HTML

code authoring.

♦ The Image List control now supports GIF files.

Page 15: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Introduction to Visual Basic 6.0

V0.1 3

New Language Features

New Language Features in VB 6.0 include the following:

♦ Passing User Defined Types (UDT) as arguments and return values for properties andmethods.

♦ Functions can now return arrays.

♦ There are now Drive, Folder and File collection objects.

♦ New formatting statements include Format Currency, Format Date Time and Format Percent.

♦ New built-in constants cover date formats.

♦ Call By Name enables properties and methods to be invoked using variable contents insteadof explicitly coding the names.

New Control

New Controls in VB 6.0 include the following:

♦ ADO data control.

♦ Data Grid Unicode - enabled version of older DBGrid.

♦ Hierarchical FlexGrid updated version handles structured data from multiple tables.

♦ DataList and DataCombo allow dynamic runtime switching of data sources.

♦ ImageCombo is similar to the regular ComboBox but allows graphics for the list items.

♦ LightWeight versions of CheckBox, ComboBox, Command, Frame, ScrollBars, ListBox,

Options and TextBox.

♦ Data Repeater.

♦ DatePicker offers drop-down date selection.

♦ Flat ScrollBar.

♦ Header, supports header items for tabular data.

♦ Script control allows adding VB Script capabilities to any program.

Page 16: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Introduction to Visual Basic 6.0 MS Visual Basic 6 Programming Introduction

4 V0.1

Visual Basic 6.0 and Internet Integration

The number of web pages has exploded in recent years and continues to grow at an increasing

pace. Microsoft Visual Basic 6.0 has several features that make it easier for programmers to createapplications that interact with the Internet and to create robust pages, when Microsoft InternetExplorer is loaded.

Visual Basic uses containers and property bags to create an ActiveX document, whereinformation can be stored and retrieved.

Visual Basic uses wizard to create CAB files to distribute ActiveX Components. The deployment

wizard that comes with Visual Basic is used to create Internet aware applications.

Visual Basic helps to include ActiveX components in the web page. This is done by appropriateentries in the HTML file to cause the ActiveX component to be downloaded and registered.

Visual Basic uses OLE automation to load several web pages and show how to make use of thebrowser's own events to cause changes in your program to occur. Visual Basic 6.0 comes with acontrol called Microsoft Internet transfer control 6.0 that can be used to communicate with HTTP

and FTP servers.

Visual Basic 6.0 has added the ability to create DHTML applications, which allows creatingprograms that make use of dynamic HTML to interact with the user and desktop by using Visual

Basic code.

Win32 API and Visual Basic 6.0

Visual Basic 6.0 explores different aspects of using the WIN32 API, a feature-rich set of functionsand subroutines that can be used to extend and add features to the user program.

Two specific aspects of the API were previously not available to Visual Basic developers in theearliest versions of the language: callbacks and sub classing. Visual Basic now allows developersto call API functions that use callbacks and set hooks for sub classing.

All of these new features should get you thinking about the great new applications that you canbuild.

Page 17: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Introduction to Visual Basic 6.0

V0.1 5

Visual Basic Development Environment

Visual Basic 6.0 is a powerful application tool. The package is an unusual combination of a

familiar and accessible programming language and also an efficient interactive environment fordesigning forms and windows. In Visual Basic, you can easily and quickly design the visualelements of new programming project. It is not just a language. It is an Integrated Development

Environment in which you can develop, run, test and debug your applications. The workingenvironment in Visual Basic is referred to Integrated Development Environment because itintegrates many different functions such as design, editing, compiling and debugging within a

common environment.

With Visual Basic, you can create the following types of applications.

Standard Exe: A Standard Exe project is a typical application. These are the types of applications

you developed with previous versions of Visual Basic.

Active X EXE and ActiveX DLL: These types of projects are available with the professionaledition. ActiveX components are OLE automation servers. The two types of projects are identical

in functionality, but are packaged differently (as executable files or dynamic link libraries).

ActiveX Control: This type of project is also a feature of the professional edition. This is used todevelop your own ActiveX controls.

ActiveX Document EXE, ActiveX Document DLL: ActiveX documents are in essence VisualBasic applications that can run in the environment of a container that supports hyper-linking. Insimple terms, this environment is a web browser, such as Internet Explorer.

VB Application Wizard: The Wizard takes you through the steps of setting up the skeleton of anew application. (You should not use this Wizard unless you can develop a project on your own).Modifying the skeleton code created by the Wizard is just as difficult, if not more, than

developing your own application from scratch.

DHTML Application: DHTML applications are a combination of both compiled Visual Basic anddynamic HTML. This combination allows update of the web page without recreating or

reloading and interacting with the browser and other desktop applications. You can leverageyour knowledge of Visual Basic to create interesting web deliverables.

IIS Application: This is server based that delivers HTML and other Internet content to client

browsers. This is used to write web applications dynamically.

ADD-INS: You can create your own add-ins for the Visual Basic IDE.

VB Wizard Manager: A tool in the Visual Basic environment that assists in the creation of custom

wizards that look and act like those that ship with Visual Basic. The Wizard Manager managesthe screens of a wizard while it is in the development stage. The utility provides the initialframework for a wizard type of add-in and the ability to add, change, and delete screens from the

wizard.

Page 18: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Introduction to Visual Basic 6.0 MS Visual Basic 6 Programming Introduction

6 V0.1

Wizard Manager is a great tool for managing wizard creation efforts and for giving user wizards

a look similar to those used by Microsoft and other vendors.

Using data projects and VB enterprise edition controls, various applications can be developed byselecting appropriate type of projects based on the sensitivity of the applications to be developed.

Visual Basic IDE Elements

The Visual Basic Integrated Development Environment consists of the following elements.

Standard menu bar, Tool Bar, Tool Box, Project Explorer, Properties Window and Form LayoutWindow.

Standard menu bar

The Standard Menu Bar is the Main Menu of VB 6.0 It has options like File, Edit, View, Project,Debug, Run, Query, Diagram, Tools, Add-Ins, Window and Help.

Tool Bar

The Tool Bar provides short cuts for many important menu commands. Menu commands aredesigned to give way to perform specific operations. The buttons in the Tool Bar represent thecontrols that can be included in any program under development. The Tool Bar is the main focusto begin a project and has controls to depict the options, procedures and activities planned in anapplication.

Tool Box

This provides a set of tools that can be used at run time to place controls on a form. They includethe controls like Labels, Picture Box, Frames (to organize text and graphics in a window), TextBoxes and Command buttons (controls for taking input or instructions from the user), CheckBoxes, Option buttons. Combo boxes (controls providing options). These controls help indesigning simple as well as complex applications.

Project Explorer

The project window provides a list of the files in the current working program. The project

window is activated by simply clicking it or pressing Ctrl + R , the keyboard short cut

method for the project command.

Page 19: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Introduction to Visual Basic 6.0

V0.1 7

Properties Window

Properties determine the appearance and behaviour of individual controls and forms in the

application you create. In order to set the property of a particular control highlight the propertywindow. The columns on the left, contains the names of all properties that apply to a selectedobject, and the column on the right shows the setting of each property. Each property has adefault setting that remains in effect unless it is changed.

Page 20: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Introduction to Visual Basic 6.0 MS Visual Basic 6 Programming Introduction

8 V0.1

Visual Basic File Types

.BAS

Standard modules (.BAS file name extension) are containers for procedures and declarationscommonly accessed by other modules within the application. They can contain global (availableto the whole application) or module-level declarations of variables, constants, types, externalprocedures, and global procedures. The code that you write in a standard module isn'tnecessarily tied to a particular application; if you're careful not to reference forms or controls byname, a standard module can be reused in many different applications.

.CLS

Class modules (.CLS file name extension) are the foundation of object-oriented programming inVisual Basic. You can write code in class modules to create new objects. These new objects caninclude your own customized properties, methods and events.

.BMP

Graphics formats recognised by Visual Basic include bitmap (.bmp) files, icon (.ico) files, run-length encoded (.rle) files, metafile (.wmf) files, enhanced metafiles (.emf), GIF files, and JPEG(.jpg) files.

.CAB

For ActiveX control, ActiveX EXE, and ActiveX DLL projects, all run-time components - such asMsvbvm50.dll, individual controls, Data Access Objects (DAO), and Remote Data Objects (RDO)- are packaged into separate .cab files, digitally signed by Microsoft, and placed on the MicrosoftWeb site. You can choose to link your files to the .cab files on the Microsoft Web site, or you candownload local copies of them.

.CTL

If a User Control or its constituent controls use graphical elements which cannot be stored asplain text, such as bitmaps, Visual Basic stores those elements in a .ctx file with the same nameyou give to the .ctl file. This is analogous to the .frx files used to store graphical elements used informs.

The .ctl and .ctx files completely define an ActiveX control's appearance and interface(properties, methods and events). You can include .ctl files in any of the project types.

.EXE

EXE files are the precompiled executables of your Visual Basic Programs, which can be executedunder MS Windows Operating System independently.

Page 21: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Introduction to Visual Basic 6.0

V0.1 9

.FRM

The forms that you create in VB are stored in .FRM extension.

.VBP

Visual Basic always saves project files (.vbp) in ASCII format. The project file contains entries thatreflect settings for your project. These include the forms and modules in your project, references,miscellaneous options that you have chosen to control compilation, etc.

.FRX

.FRX files are skeletons of compiled forms and contains reports of a form.

.MDB

.MDB file are Microsoft Access database files.

.OCX

ActiveX controls have .OCX extension.

.RES

Visual Basic resource files have .RES extension.

.OCA

Each ActiveX control is accompanied by a file with an .oca extension. This file stores cached typelibrary information and other data specific to the control. The .oca files are typically stored in thesame directory as the ActiveX controls and are recreated as needed (file sizes and dates maychange).

Page 22: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Introduction to Visual Basic 6.0 MS Visual Basic 6 Programming Introduction

10 V0.1

ExerciseYour First VB 6.0 Application

In this sample application, we will write a VB program to display the system date in a text box onthe click of a command button.

1. Click on start ->Programs ->Microsoft Visual Studio 6.0 -> Microsoft Visual Basic 6.0 to start

VB.

2. Select 'Standard EXE' from the dialog box, to open a Standard EXE project.

3. A screen appears which has Standard Menu Bar, Standard Tool Bar, Tool Box Window,

Project Window, Project Explorer Window, Property Window and Form Layout Window

The TOOL BOX contains Intrinsic controls. The PROJECT WINDOW contains a form onwhich you can place the controls. The PROJECT EXPLORER displays a hierarchical list of

projects and all the items contained in a project. The PROPERTY WINDOW displays theproperties of the objects. The Form Layout Window allows you to visually position yourforms at design time.

4. Now place a textbox control on the form. This can be done, by double clicking on the textboxcontrol. Alternatively, you can select the control and draw it on the form. The text box has thedefault name as Text1.

Select the text box control and Press F4 to change the properties of this control.

Alternatively, select the text box control, click the right button of the mouse and chooseproperties. The 'text' property has a default value as text1. Erase this value and make it blank.

Change the font property of this control by choosing from the font dialog box, which appearswhen you click on the 'font' property.

5. Place a Command Button on the form, below the text box control. The command button hasthe default name as Command1. Select the command button and press F4 to get the

property window. Change the caption property of the control to 'Display Date'.

Page 23: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Introduction to Visual Basic 6.0

V0.1 11

6. To write the code, double click on the command button. This takes you to the code window.The 'Click Event' of the 'Command Button' is selected and the following CODE appears

Private Sub Command1_Click()

End Sub

Our program should display the system date when the command button is clicked. The code

for this purpose is

text1.text = date

By the above code, we are assigning the value of system date (date) to the text property of thetext box control (text1).

Hence, the code will now be as follows:

Private Sub Command1_Click()text1.text = date

End Sub

7. Now, press F5 , to run the project. Alternatively select 'Run' menu and click on 'Start' sub

menu.

The run form appears with a text box and the command button. Click on the 'display date'command button to display the current system date in the text box.

8. To stop execution of the above project, select 'Run' menu and click on 'End' sub menu.

Page 24: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Introduction to Visual Basic 6.0 MS Visual Basic 6 Programming Introduction

12 V0.1

9. Use the 'Save Project' and 'Save Form' sub menus under 'File' menu to save your project and

form.

10. To create an executable file of project, choose 'Make EXE' under the 'File' menu. A dialog boxappears. Save the EXE file in a specified directory with a specified name. For example, we can

say our first application as c:\samples\sample.exe

11. Now, exit VB by choosing File -> Exit.

12. Click on Start -> Run and type “C:\samples\sample.exe”.

13. Click on OK to run the application that we created, without entering VB.

Page 25: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

V0.1 13

Understanding VB Development

Objectives

In this chapter you will learn about Event Driven Programming., Objectsand Classes, Data Types, Variables and Constants, InputBox and Message Box. You will learn to create a sampleVB application that uses Class Modules.

• Procedural Applications

• Event Driven Applications

• Features of Visual Basic

• Online Help

• Code Editor

• Designing the User Interface

• Using Controls

• Using the Toolbox

• Adding Controls to the Toolbox

• To add an ActiveX control to the Toolbox

• Naming Controls

• Working with Objects and Classes

• Using an Object's Methods, Properties and Events

• Setting Properties at Design Time

• Setting properties at Run Time

• Getting Properties at Run Time

• Events

• Writing Code

• Data Types in Visual Basic 6.0

• Syntax

• MessageBox

Page 26: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Understanding VB Development MS Visual Basic 6 Programming Introduction

14 V0.1

Understanding Event-Driven Programming

VB is derived from the basic language, which is a structured programming language. However,

VB uses an event-driven programming model.

Procedural Applications

In traditional or procedural applications, the application controls which portions of code run, andthe sequence in which they run. Application execution starts with the first line of code, and

follows a predefined path through the application, calling procedures as needed.

Event Driven Applications

In an event-driven application, execution does not follow a predetermined path. Instead, it runsdifferent code sections in response to events. Events can be triggered by the user's actions, bymessages from the system or other applications, or from the application. The sequence of events

determines the sequence in which the code runs. Therefore, the path through the application'scode differs each time the program which the code runs.

An essential part of event-driven programming is to write code that responds to the possible

events that may occur in an application. VB makes it easy to implement an event drivenprogramming model.

Features of Visual Basic

Online Help

VB provides extensive online help. The help file contains many code samples that we can copydirectly into an application. VB 6.0 Help is context-sensitive.

Code Editor

The VB code editor automatically provides us with relevant information as we enter code. Forexample, if we type the name of a control, followed by the dot (.) operator, the properties andmethods of that control will be automatically displayed in a list box. We can then choose theappropriate property or method to complete the statement.

Designing the User Interface

The first step in creating an application in Visual Basic is to design the forms that will be used inthe application.

Page 27: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Understanding VB Development

V0.1 15

Using Controls

When we build an application in VB, we begin by creating the user interface. Using the Toolbox,we draw or place controls on a form to create the visual elements of our application. The toolboxis available at design time only.

Using the Toolbox

The Toolbox contains built-in VB controls and any ActiveX controls we have added to the project.If the Toolbox is closed, we can open it by clicking Toolbox on the view menu.

To place a control on a form, we can either double-click the control, or single-click it and drawthe control on the form.

Adding Controls to the Toolbox

We can extend the Toolbox by adding ActiveX controls. The professional Edition of VB providesadditional ActiveX controls. We can also purchase ActiveX controls form third-party vendors.

To add an ActiveX control to the Toolbox

1. On the project menu, click Components. VB displays the Components dialog Box.

2. On the Controls tab, click the control we want to include, and then click OK. VB adds thecontrol to the Toolbox.

Naming Controls

When naming controls, follow standard user interface and control naming conventions. This willmake our code easier to read and debug.

Working with Objects and Classes

An object is a combination of code and data that is treated as a unit. An object can be an element

of an application, such as a control or a form. It can also be an entire application.

A class is a template for an object, just as blue print is a template for a house. All objects arecreated as identical copies or instances of their class. Once they exist as individual objects, their

properties can be changed

In Visual Basic, each object is defined by classes. The controls in the Toolbox represent classes.When we place a control on a form, we create an object of the control's class.

Page 28: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Understanding VB Development MS Visual Basic 6 Programming Introduction

16 V0.1

Using an Object's Methods, Properties and Events

All objects have methods, properties and events. Properties are values we set to determine the

object's appearance and behavior. The benefit of working with objects is that objects provide codethat we do not have to write. We simply set the object's property and call the object's methods,and the object performs various functions.

Methods

Method is an invoke-able function that is defined to be a member of an interface. It can also becalled a procedure that acts on an object. The program below is an example of a circle method ofa form that draws circles of different colors on clicking the form.

Private Sub Form_Click() Dim CX, CY, Radius, Limit ' Declare variable. ScaleMode = 3 ' Set scale to pixels. CX = ScaleWidth / 2 ' Set X position. CY = ScaleHeight / 2 ' Set Y position.

If CX > CY Then Limit = CY Else Limit = CX For Radius = 0 To Limit ' Set radius. Circle (CX, CY), Radius, RGB(Rnd * 255, Rnd * 255, Rnd * 255) Next Radius End If

End Sub

Examples of methods

MoveCircleDragZOrderRefreshSetFocus

Page 29: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Understanding VB Development

V0.1 17

Properties

Property is a named attribute of an object. Properties define object characteristics such as size,

color, and screen location, or the state of an object, such as enabled or disabled.

Setting Properties at Design Time

Some properties can be set at design time. To set these properties, we can use the propertywindow or property pages. To access the property window, right click on an object and thenclick properties. The property window displays only the properties that are common to all of the

selected controls. Any change we make to a property applies to all of the controls.

Page 30: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Understanding VB Development MS Visual Basic 6 Programming Introduction

18 V0.1

Setting Properties at Run Time

At run time, we can write code to set or retrieve properties. The following code sets a font as

bold for a text box named txtData.

txtData.Font.Bold = True ' Set text to bold

This code sets the Text property of the textbox txtData.

txtData.Text = "Hello World" ' Set value of text

If we omit the property name, we set the default property of the control. The default property ofa Text box is the Text property. The default property of a label is the Caption property.

The following code sets the default text and caption properties for a text box and a label control.

txtData = "Set the Text property of text box"lbldata = "Set the Caption Property of label"

Getting Properties at Run Time

We can use the following code to get properties at run time:

Dim sName as StringsName = txtName.Text

Page 31: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Understanding VB Development

V0.1 19

Events

An action recognized by an object, such as clicking the mouse or pressing a key, and for which

you can write code to respond. Events can occur as a result of a user action or program code, orthey can be triggered by the system.

Example of event are

ClickChangeGot focusLost focusLoadUnloadQuery UnloadActivateTerminate

For example,

Private Sub Picture1_Click() Picture1.Move Picture1.Left + 750, Picture1.Top - 550

End Sub

In the above example Click is the event, Picture1 is the object, Move is the method, Left and Topare the properties of Picture1 Object.

In certain cases one event suppresses another event. For example if both click and double click

events are coded for a textbox then the double click event does not fire at all because the clickevent fires and suppresses the double click event.

Page 32: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Understanding VB Development MS Visual Basic 6 Programming Introduction

20 V0.1

Adding a Menu using the Menu Editor

The Menu editor is an interactive tool that enables to create and modify menus with a minimum

of coding. With the Menu Editor, we can add new commands to existing menus, replace existingmenu commands with our own, create new menus and menu bars, and change and deleteexisting menu and menu bars.

To add a menu to a form

• Click the Menu Editor button on the Standard tool bar to display the Menu Editor dialogbox.

• In the Caption field, enter the menu or command name that we want to appear on themenu bar in our menu.

• Use the arrow command buttons to move menu items up or down in the command list.

At runtime, we can modify the appearance of a menu and add new menu items. We can also usethe Popup Menu method to display a pop-up menu.

Writing Code

Once we have designed forms and set properties, we are ready to add code to our application.

VB is a complete programming language that supports the programming constructs found inmost other programming languages.

This section describes how to create events and general procedures, the scope of procedures, and

how to use the object Browser to list the procedures. It also discusses the different data typesavailable in VB, how to declare variables, and the scope and life of variables.

Creating Procedures

In VB there are two types of procedures we will work with:

1) Event procedures and 2) General procedures

Event procedures

VB automatically calls event procedures in response to keyboard, mouse, or system actions. Forexample, command buttons have click event procedure. The code we place in a Click eventprocedure is executed when the user clicks a command button.

To open a code window, double click the control or form, or click code on the View menu.

Each control has fixed set of event procedures. The event procedures for each control are listed ina drop-down list box in the code window.

The following code shows the Click event procedure for a command button named cmdOK:

Page 33: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Understanding VB Development

V0.1 21

Private Sub cmdOK_Click()MsgBox "Hello"

End Sub

General Procedures

General Procedures are Sub or Function procedures that are created to perform specific tasks. Toexecute a general procedure, we must explicitly invoke it.

To create a general procedure, we open a code window and click Add procedure on the Toolsmenu. We can also create a new procedure by typing the procedure heading Sub, followed byour procedure name, on a blank line in a code window.

If you have duplicate code in several event procedures, we can place the code in a generalprocedure, and then call the general procedure from the event procedures.

Sub Procedures

Sub procedures do not return values. For example:

Private Sub SortList ( s as string)

We invoke a Sub procedure by specifying only the procedure name, or by using the Callstatement with the procedure name. For example:

Call SortList("myname")

If we use the Call statement, we must enclose the argument list in parenthesis. If we omit Call,we must also omit the parenthesis around the argument list

Function Procedures

Function procedures return values. In the following code, the Function procedure receives anumber and returns the number squared.

Function Square ( I as Integer ) As Integer Square = I * IEnd Function

If we want to save the return value, we must use parenthesis when invoking a function, as shownin the code below:

J = square(5)

Page 34: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Understanding VB Development MS Visual Basic 6 Programming Introduction

22 V0.1

Scope of Code

In addition to declaring code in a module associated with a form, we can also declare procedures

in a standard code module. Standard code modules contain only VB code, and they are goodplace to store code that is not specific to a single form. Procedures can be declared as - Private orPublic.

Private procedures can be called only by other procedures located in that form, module or class.

Public procedures on a form become methods of the form. The procedure can be called fromanywhere in the application by specifying the form and procedure names.

Public procedures in a module are available throughout the application, and can be called byspecifying the procedure name.

If we have declared the procedure in a form module, we call it with this code

Form1.myproc

If we declared the procedure in a standard module, we call it with this code

Myproc

If we declared a procedure with the same name in two standard modules, we must qualify theprocedure name when we call it, as shown in the following code.

Module1.myproc

Using the Object Browser to View Procedures

Once we have added code to our application, we can use the Object Browser to list all of the

procedures we have created, jump quickly to a specific procedure, or paste a procedure call into acode window.

The Object Browser displays the classes that are available from any object libraries we have

referenced.

To display the Object Browser, Press F2 in a code window.

Page 35: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Understanding VB Development

V0.1 23

Data Types Supported in Visual Basic 6.0

Data type Storagesize

Range

Byte 1 byte 0 to 255

Boolean 2 bytes True or False

Integer 2 bytes -32,768 to 32,767

Long(long integer) 4 bytes -2,147,483,648 to 2,147,483,647

Single(single-precisionfloating-point)

4 bytes-3.402823E38 to -1.401298E-45 for negativevalues; 1.401298E-45 to 3.402823E38 for positivevalues

Double(double-precisionfloating-point)

8 bytes

-1.79769313486232E308 to-4.94065645841247E-324 for negative values;4.94065645841247E-324 to1.79769313486232E308 for positive values

Currency(scaledinteger)

8 bytes -922,337,203,685,477.5808 to922,337,203,685,477.5807

Decimal 14 bytes

+/-79,228,162,514,264,337,593,543,950,335 withno decimal point;+/-7.9228162514264337593543950335 with 28places to the right of the decimal; smallest non-zero number is+/-0.0000000000000000000000000001

Date 8 bytes January 1, 100 to December 31, 9999

Object 4 bytes Any Object reference

String(variable-length)

10 bytes+ stringlength

0 to approximately 2 billion

String(fixed-length)

Length ofstring 1 to approximately 65,400

Variant(with numbers) 16 bytes Any numeric value up to the range of a Double

Variant(withcharacters)

22 bytes+ stringlength

Same range as for variable-length String

User-defined(using Type)

Numberrequiredbyelements

The range of each element is the same as therange of its data type.

Page 36: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Understanding VB Development MS Visual Basic 6 Programming Introduction

24 V0.1

Using Data Types

The data type of a variable determines the type of information that a variable can store and the

range of possible values. For example, if we want a variable to act as a counter for a loop, weassign it the data type integer.

If we do not provide a data type when we declare a variable, the variable is given the variant data

type. The Variant data type can store null, numeric, date/time, or string data. However, thevariant data type requires more memory than other data types. If we want to create concise andfast code, we should use explicit data types where appropriate.

Declare each variable on a separate line to avoid confusion.

Dim sfname, slname as string

Instead of the above, we use

Dim sfname as stringDim lname as string

VB coerces data types if necessary. For example, if we use a string variable in an arithmeticexpression. VB will convert the string variable to a numeric value, if possible.

The following code shows how VB adds 1 to the value in the text box.

Dim inewrate as integertxtrate.text = "5"inewrate = txtrate.text + 1

Declaring Variables

To declare a variable, we use the Dim Statement. The code declares the variable icounter as anInteger variable.

Dim icounter As Integer

Although VB lets us to use variables that we have not declared, our code will be easier to debugif we declare all variables. To require variable declaration, include the Option Explicit statementto the General Declarations section of a form or module. If we try to use a variable that we have

not declared when Option Explicit is set, we will receive a run-time error.

Page 37: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Understanding VB Development

V0.1 25

Declaring Constants

We use the Const Statement to declare a constant. We cannot change the value of a constant.

The following code declares the constant PI as a variable of type single.

Const PI As single = 3.14

VB provides many built in constants that are useful with various statements.

The following code uses the predefined constants vbYesNo and vbYes with the MsgBoxstatement

iresult = MsgBox ("Do you want to continue ?", vbYesNo)if iresult = vbYes Then||End If

Scope of Variables

Procedure Level Variables

A variable in a procedure is recognized only within the procedure in which the variable isdeclared. The following code dimensions a variable as an integer within a procedure.

Dim itest As integer

Form Level Variables

Variables declared within the General Declarations section of a form can be Private or Public.

Private variables are available to all procedures within the form, but are not visible to anyprocedures outside the form.

Public variables are available to an entire application as a property of the form. When accessing aPublic form-level variable from outside the form, we must specify the form name. For example

Public ftotal As Integer 'Declared in Form named frm

frm.ftotal = 4 'Used outside form

Page 38: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Understanding VB Development MS Visual Basic 6 Programming Introduction

26 V0.1

Standard Module-Level Variables

Variables declared within the General Declarations section of module can be Private or Public.

Private variables are available only to the module.

Public variables are available to the entire application. We can access a module level publicvariable by specifying only the variable name. For example

'Declare variable in modulePublic gitest As Integergitest = 5

Module1.gitest = 5

Life of Variables

The title of a variable refers to how long a variable is available, where the variable is declared (ina procedure or module), and how the variable is declared (as Static or not Static - determines thelife of the variable).

Procedure level

A procedure level variable lasts as long as the procedure does. When the procedure is calledagain, the variable is reinitialized.

If we do not want the variable to be reinitialized, declare the variable as Static. Variablesdeclared as Static, are still only available to the procedure; however, the variables retain theirvalue the entire time the application is running.

In the following code, iRetryCount retains its value for each invocation of myProc. The variableiValue is reset to 0 each time myProc is invoked.

Sub myProc()Static iRetryCount as IntegerDim iValue As integeriRetryCount = iRetryCount + 1

End Sub

Form-Level Variables

Variables declared at the form level are maintained until the form is set to nothing. Form-levelvariables retain their values when the form is unloaded.

When we set a form variable to Nothing, the variables are cleared and the Terminate event of theform is executed. The following code shows how to set Form2 to Nothing.

Set Form2 = Nothing

Page 39: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Understanding VB Development

V0.1 27

Standard Module-Level Variables

Variables declared at the module level are available during the entire time an application isrunning.

Program Structures

Array

A set of sequentially indexed elements having the same intrinsic data type is called an array.Each element of an array has a unique identifying index number. Changes made to one elementof an array, does not affect the other elements.

In Visual Basic there are two types of Arrays:

* Fixed size array which always remain the same size.

* Dynamic Array whose size can change at run time.

Fixed Size Array

We declare a fixed size Array as shown below.

Dim counters (14) As IntegerDim Sums (20) As Double

To create a public array, you use public in the place of Dim.

Public Counters (14) As IntegerPublic Sums (20) As Double

To create a local array, you declare as private/dim.

Dim Counters (14) As IntegerDim Sums (20) As Double

Dynamic Array

To create a Dynamic Array:

You declare the array as dynamic by giving it an empty dimension list.

Dim dynArray ()

Now allocate the actual number of elements with ReDim statement.

ReDim DynArray(X+1)

Page 40: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Understanding VB Development MS Visual Basic 6 Programming Introduction

28 V0.1

A ReDim statement appears only in a procedure. ReDim is an executable statement, it makes theapplication carry out an action at run time. Each ReDim statement can change the number ofelements, as well as the lower and upper bounds.

ReDim DynArray (4 to 12)

Looping Structures

Loop structures allow you to execute one or more lines of code repetitively. The loop structuresthat Visual Basic supports include:

Do...LoopFor...NextFor Each...Next

Do...Loop

Do loop is used to execute a block of statements an indefinite number of times. There are severalvariations of the Do...Loop statement, but each evaluates a numeric condition to determinewhether to continue execution. As with If...Then, the condition must be a value or expression that

evaluates to False (zero) or to True (nonzero).

Do While Loop

In the following Do...Loop, the statements execute as long as the condition is True:

Do While condition [statements] [Exit Do] [statements]Loop

When Visual Basic executes this Do…Loop, it first tests condition. If condition is False (zero), itskips past all the statements. If it's True (nonzero), Visual Basic executes the statements and then

goes back to the Do While statement and tests the condition again.

Consequently, the loop can execute any number of times, as long as condition is nonzero or True.The statements never execute if condition is initially False. User can voluntarily come out from the

loop based on some condition.

Page 41: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Understanding VB Development

V0.1 29

Example

The following procedure will display the numbers up to n=10.

Private sub Demoloop() N=1 Do while n <= 10 Msgbox n N = n + 1 LoopEnd sub

Do Until Loop

Do Until condition [statements][Exit Do] [statements]Loop

When Visual Basic executes this Do…Loop, it first tests condition. If condition is True, it skips pastall the statements. If it's False, Visual Basic executes the statements and then goes back to the Do

Until statement and tests the condition again. Consequently, the loop can execute any number oftimes, as long as condition is false. The statements never execute if condition is initially True. Usercan voluntarily come out from the loop based on some condition.

Example: The following procedure will display the numbers up to n=6.

Private Sub Demoloop1()Dim i As Integeri = 10Do Until i < 1 MsgBox i i = i – 1 If I = 6 then Exit do End ifLoopEnd Sub

Page 42: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Understanding VB Development MS Visual Basic 6 Programming Introduction

30 V0.1

Do Loop While Loop

Another variation of the Do...Loop statement executes the statements first and then tests

condition after each execution. This variation guarantees at least one execution of statements:

Do statementsLoop While condition

If…Then

Conditionally executes a group of statements, depending on the value of an expression.

Syntax

If condition Then [statements] [Else elsestatements]

Or, you can use the block form syntax:

If condition Then[statements][ElseIf condition-n Then[elseifstatements] ...[Else[elsestatements]]End If

Page 43: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Understanding VB Development

V0.1 31

The If...Then...Else statement syntax has these parts:

Part Description

Condition Required. One or more of the following two types of expressions:

A numeric expression or string expression that evaluatesto True or False. If condition is Null, condition is treated asFalse.

An expression of the form TypeOf objectname Isobjecttype. The objectname is any object reference andobjecttype is any valid object type. The expression is True ifobjectname is of the object type specified byobjecttype; otherwise it is False.

StatementsOptional in block form; required in single-line form that hasno Else clause. One or more statements separated bycolons; executed if condition is True.

condition-n Optional. Same as condition.

elseifstatements Optional. One or more statements executed if associatedcondition-n is True.

elsestatements Optional. One or more statements executed if no previouscondition or condition-n expression is True.

For...Next

Do loops work well when you don't know how many times you need to execute the statements inthe loop. When you know you must execute the statements a specific number of times, however,

a For…Next loop is a better choice. Unlike a Do loop, a For loop uses a variable called a counterthat increases or decreases in value during each repetition of the loop. The syntax is:

For counter = start To end [Step increment] statementsNext [counter]

The arguments counter , start , end, and increment are all numeric.

In executing the For loop, Visual Basic:

♦ Sets counter equal to start.

♦ Tests to see if counter is greater than end. If so, Visual Basic exits the loop.

(If increment is negative, Visual Basic tests to see if counter is less than end.)

Page 44: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Understanding VB Development MS Visual Basic 6 Programming Introduction

32 V0.1

Executes the statements.

♦ Increments counter by 1 or by increment, if it's specified.

♦ Repeats steps 2 through 4.

This code prints the names of all the available Screen fonts:

Private Sub Form_Click () Dim I As Integer For i = 0 To Screen.FontCount Print Screen.Fonts(i) NextEnd Sub

For Each...Next

A For Each...Next loop is similar to a For...Next loop, but it repeats a group of statements for eachelement in a collection of objects or in an array instead of repeating the statements a specified

number of times. This is especially helpful if you don't know how many elements are in acollection. For example, the following Sub procedure opens Biblio.mdb and adds the name ofeach table to a list box.

Sub ListTableDefs() Dim objDb As Database Dim MyTableDef as TableDef Set objDb = OpenDatabase("c:\vb\biblio.mdb", _ True, False) For Each MyTableDef In objDb.TableDefs() MSGBOX MyTableDef.Name Next MyTableDefEnd Sub

Keep the following restrictions in mind when using For Each...Next:

♦ For collections, element can only be a Variant variable, a generic Object variable, or an objectlisted in the Object Browser.

♦ For arrays, element can only be a Variant variable.

♦ You cannot use For Each...Next with an array of user-defined types because a Variant cannotcontain a user-defined type.

Page 45: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Understanding VB Development

V0.1 33

Select Case

A Select Case structure works with a single test expression that is evaluated once, at the top of

the structure. Visual Basic then compares the result of this expression with the values for eachCase in the structure. If there is a match, it executes the block of statements associated with thatCase:

Select Case testexpression[Case expressionlist1[statementblock-1]][Case expressionlist2[statementblock-2]]...[Case Else[statementblock-n]]End Select

Each expressionlist is a list of one or more values. If there is more than one value in a single list,

the values are separated by commas. Each statementblock contains zero or more statements. Ifmore than one Case matches the test expression, only the statement block associated with the firstmatching Case will execute. Visual Basic executes statements in the Case Else clause (which is

optional) if none of the values in the expression lists matches the test expression.

Page 46: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Understanding VB Development MS Visual Basic 6 Programming Introduction

34 V0.1

InputBox

InputBox displays a prompt in a dialog box, waits for the user to input text or click a button, and

returns a String containing the contents of the text box.

Syntax

InputBox(prompt[, title] [, default] [, xpos] [, ypos] [, helpfile, context])

prompt: Required parameter. It is a string expression displayed as the message in the dialog box.

title: It is a string expression displayed in the title bar of the dialog box.

default: It is a string expression displayed in the text box as the default response if no other inputis provided. If you omit default, the text box is displayed empty.

xpos: It's a numeric expression that specifies, in twips, the horizontal distance of the left edge ofthe dialog box from the left edge of the screen.

ypos: It's a numeric expression that specifies, in twips, the vertical distance of the upper edge ofthe dialog box from the top of the screen.

helpfile: It's a string expression that identifies the Help file to use to provide context-sensitiveHelp for the dialog box.

context: It's a numeric expression that is the Help context number assigned to the appropriateHelp topic by the Help author.

A typical Inputbox looks like this:

Page 47: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Understanding VB Development

V0.1 35

MessageBox

MessageBox displays a message in a dialog box, waits for the user to click a button, and returns

an Integer indicating which button the user clicked.

Syntax

MsgBox(prompt[, buttons] [, title] [, helpfile, context])

prompt: Required parameter.

buttons: It's a numeric expression that is the sum of values specifying the number and type ofbuttons to display, the icon style to use, the identity of the default button, and the modality of themessage box. If omitted, the default value for buttons is 0.

title: It's a string expression displayed in the title bar of the dialog box. If you omit title, theapplication name is placed in the title bar.

helpfile: It's a string expression that identifies the Help file to use to provide context-sensitiveHelp for the dialog box. If helpfile is provided, context must also be provided.

context: Numeric expression that is the Help context number assigned to the appropriate Helptopic by the Help author. If context is provided, helpfile must also be provided.

Page 48: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Understanding VB Development MS Visual Basic 6 Programming Introduction

36 V0.1

ExerciseApplication of Class Modules

This application uses the class module for the execution of a simple task of addition of twonumbers. The numbers to be added are entered in two textboxes and the result is displayed in thethird textbox on clicking the command button.

The form looks like this:

Enter the following code into the code window of the form.

Option ExplicitDim x As New clOpp 'Create an instance of clOpp

Private Sub Command1_Click()x.num1 = Text1.Text 'Assign the value of num1x.num2 = Text2.Text 'Assign the value of num2Select Case Combo1.Text 'Check for the operator in the combobox Case "+" Text3.Text = x.GetOp("+") Case "-" Text3.Text = x.GetOp("-") Case "*" Text3.Text = x.GetOp("*") Case "/" Text3.Text = x.GetOp("/") End Select

End Sub

Private Sub Form_Load()'populating the operator symbolsCombo1.AddItem "+" 'adding the symbol +Combo1.AddItem "-" 'adding the symbol -Combo1.AddItem "*" 'adding the symbol *Combo1.AddItem "/" 'adding the symbol /Combo1.ListIndex = 0 'set + as the default display in the combobox

End Sub

Page 49: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Understanding VB Development

V0.1 37

Enter the following code into a class name clOpp

Option ExplicitDim n1 As DoubleDim n2 As Double

Public Property Get num1() As Doublenum1 = n1 ' Fetch the value of num1 from n1End Property

Public Property Let num1(ByVal vNewValue1 As Double)n1 = vNewValue1 'Assign the value to num1End Property

Public Property Get num2() As Doublenum2 = n2 ' Fetch the value of num2 from n2End Property

Public Property Let num2(ByVal vNewValue2 As Double)n2 = vNewValue2 'Assign the value to num2End Property

Private Function Add(n1, n2) As DoubleAdd = n1 + n2 'Add the two local variablesEnd Function

Private Function Subtract(n1, n2) As DoubleSubtract = n1 - n2 'Subtract the two local variablesEnd Function

Private Function Multiply(n1, n2) As DoubleMultiply = n1 * n2 'Multiply the two local variablesEnd Function

Private Function Divide(n1, n2) As VariantIf n2 <> 0 Then 'Divide the two local variablesDivide = n1 / n2ElseDivide = "Infinity"End IfEnd Function

Public Function GetOp(Sign As String) As Variant

Page 50: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Understanding VB Development MS Visual Basic 6 Programming Introduction

38 V0.1

Select Case Sign Case "+" GetOp = Add(Me.num1, Me.num2) Case "-" GetOp = Subtract(Me.num1, Me.num2)

Case "*" GetOp = Multiply(Me.num1, Me.num2) Case "/" GetOp = Divide(Me.num1, Me.num2) End SelectEnd Function

Execution: Run the form and enter a number into the two textboxesand choose the operator from the combobox and then clickthe button with caption "=".

Note: If text or an invalid entry is made into the textboxes, then an erroris encountered which can be trapped and appropriatemessage passed on to the user for correction.

Page 51: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

V0.1 39

Intrinsic Controls

Objectives

In this chapter you will learn about various Intrinsic Controls (like PictureBox, Label, List Box, Combo Box, Image, Line and Shape,Timer, Drive, Directory, File List Box, Scroll Bar, OptionButton, Check Box and Data Control).

• Picture Box

• Label Control

• Text Box

• Frame

• Command Button

• List Box

• Combo Box

• Image Control

• Line and Shape Control

• Timer Control

• Drive, Directory and File List Box

• Scroll Bar

• Option Button

• Check Box

• Data Control

Intrinsic Controls

These controls are contained inside the Visual Basic .exe file. Intrinsic controls are alwaysincluded in the toolbox, unlike ActiveX controls and insertable objects, which can be removedfrom or added to the toolbox.

The intrinsic controls are Command Button, Picture Box, Check Box, Option Button, List Box,Combo Box, Text Box, Label etc. In this topic we discuss the features of intrinsic controls.

Page 52: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Intrinsic Controls MS Visual Basic 6 Programming Introduction

40 V0.1

Picture Box

A Picture Box control is the container, which is used to display a bitmap, icon, or metafile, as well

as enhanced metafile, JPEG, or GIF files. It clips the graphic if the control isn't large enough todisplay the entire image. It is the only control that can be placed on a MDI form.

Important Picture Box Properties

Property Description

Autosize The Autosize property is used to determine whether thepicture box is automatically resized to display the entirecontents or not. To make a picture box controlautomatically resize by setting its autosize property toTrue

Picture The Picture property is used to specify the filename ofthe bitmap to be displayed. Set the picture property withthe path and name of the picture file that has to bedisplayed when the picture box is loaded. You can alsoassign the picture at run time.

Do exercise Picture Box

Page 53: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Intrinsic Controls

V0.1 41

Label

A Label control is a graphical control you can use to display text that a user can't change directly.

Important Label Properties

Property Description

Alignment Determines whether the label's caption appears leftjustified, centered, or right justified within the label'sboundaries.

Caption Holds the text that appears on the Label.

Font Produces a font dialog box in which you can set thefont name, style, and size.

ToolTipText Holds the text that appears as a tooltip at runtime.

Wordwrap Determines whether the label expands to fitwhatever text appears in the caption.

Do exercise Label

Page 54: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Intrinsic Controls MS Visual Basic 6 Programming Introduction

42 V0.1

Text Box

Text Boxes accepts the user input. Although several other controls accept user input, text boxes

are perhaps the easiest to set up and respond to.

Important Text Box Properties

Property Description

Locked Determines whether the user can edit the text insidethe text box that appears.

Maxlength Specifies the number of characters the user can typeinto the text box.

Multiline Lets the text box hold multiple lines of text or sets thetext box to hold only a single line text.

Passwordchar Determines the character that appears in the textbox when the user enters a password.

Scrollbars Determines whether scrollbars appear on the edgesof a multiline text box.

Text Holds the value of the text inside the text box.

Do Exercise Text Box

Frame

A Frame control provides an identifiable grouping for controls. You can also use a Frame tosubdivide a form functionally—for example, to separate groups of Option Button controls.

Do Exercise Using Frames

Page 55: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Intrinsic Controls

V0.1 43

Command Button

Command Button is used to begin, interrupt, or end a process. When chosen, a Command Button

appears pushed in and so is sometimes called a push button.

Important Command Button Properties

Property Description

Cancel Determine whether the command button gets a clickevent if the user presses Esc.

Caption Holds the text that appears on the command button.

Default Determine if the command button responds to anenter keypress even if another control has the focus.

Enabled Determine whether the command button is active.Often, you'll change the Enabled property at runtimewith code when a command button is no longerneeded and you want to gray out the commandbutton.

Mousepointer Determines the shape of the mouse cursor when theuser moves the mouse over the command button.

Picture Holds the name of an icon graphic image thatappears on the command button as long as the Styleproperty is set to 1-Graphical.

Style Determine whether the command button appears asa standard windows command button (if set to 0-standard) or a command button with color andpossible picture (if set to1-Graphical).

Do Exercise Command Button

Page 56: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Intrinsic Controls MS Visual Basic 6 Programming Introduction

44 V0.1

List Box

A List Box control displays a list of items from which the user can select one or more. If the

number of items exceeds the number that can be displayed, a scroll bar is automatically added tothe List Box control.

If no item is selected, the ListIndex property value is -1. The first item in the list is ListIndex 0,

and the value of the ListCount property is always one more than the largest ListIndex value.

Important List Box Properties

Property Description

Columns Determine the number of columns. If 0, the list boxscrolls vertically in a single column. If 1 or more, the listbox items appear in the number of columns specified(one or more columns) and a horizontal scrollbarappears so you can see all the items in the list.

IntegralHeight Determines whether the list box can display partialitems, such as the upper half of an item that fallstoward the bottom of the list box.

List Holds, in a drop-down property list box, values that youcan enter into the list box at design time.

MultiSelect The state of the list box selection rules. If 0-None (thedefault), the user can select only one item. If 1-Simple,the user can select more than one item. If 2-Extended,the user can select multiple items using shift + Click andShift + arrow to extend the selection from a previouslyselected item to the current one.

Sorted Determine whether the list box values areautomatically sorted.

Style Determines whether the list box appears in its usual listformat or, with check boxes next to the selected items.

Do Exercise List Box

Page 57: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Intrinsic Controls

V0.1 45

Combo Box

Combo boxes work much like list boxes except that the user can add items to a combo box at

runtime, whereas the user can only scroll and select items from a list box at runtime. Visual Basicsupports three kind of combo boxes, and the kind you select depends on the combo box youwant to display on the form and on the ability you want the user to have.

Here are the three kinds of combo boxes:

1. Drop-down combo box - Takes up only a single line on the form unless the user opens thecombo box (by pressing the combo box's down arrow) to see additional values. The user can

enter additional items at the top of the drop-down combo box and select items from thecombo box.

2. Simple combo box - Displays items as if they were in a list box. The user can add items to the

combo box list (whereas the user cannot with a normal list box).

3. Drop-down list box - Does not let the user enter new items, so is similar to a list box. Unlikea list box, however, the drop-down list box normally appears closed to a single line until the

user clicks the down arrow button to open the list box to its full size. Technically, drop-downlist boxes are not combo box controls but work more like list boxes. The reason drop-downlist box fall in the combo box control family is that you place drop-downlist boxes on forms

by clicking the combo box control and setting the style combo box property.

Important Combo Box Property

Property Description

List Holds, in a drop-down property list box, values that youcan enter into the combo box at design time.

Sorted Determines whether the combo box values areautomatically sorted. If false (the default value), thevalues appear in the same order in which the programadded the items to the combo box.

Style Determines the type of combo box your applicationneeds. If 0 - the combo box is a drop-down combo box.If 1 - the combo box turns into a simple combo box. If 2 -the combo box turns into a drop-down list box.

Do Exercise Combo Box

Page 58: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Intrinsic Controls MS Visual Basic 6 Programming Introduction

46 V0.1

Image Control

Use the Image control to display a graphic. An Image control can display a graphic from a

bitmap, icon, or metafile, as well as enhanced metafile, JPEG, or GIF files.

Important Image Properties

Property Description

Picture Picture property determines a picture to be displayed inthe image control. You can load the picture from theproperty window at design time. You can also set thisproperty using the LoadPicture function at run time.

Stretch Stretch property is used to set a value to indicatewhether the picture or control resizes to fit the size of animage control.

Do exercise Form & Image Control

Page 59: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Intrinsic Controls

V0.1 47

Line and Shape Controls

The line and shape controls work together to draw lines, boxes and all kinds of circular figures on

the form. By placing the controls and setting appropriate properties, you'll be adding flair toapplications.

Here are the primary graphic images that you can draw with the line and shape controls.

♦ Lines

♦ Rectangles

♦ Squares

♦ Ovals

♦ Circles

♦ Rounded Rectangles

♦ Rounded Squares

By combining these fundamental geometric images and setting appropriate color and sizeproperties, you can draw virtually anything you need to draw on the form.

Line Control

We use the line control for drawing lines of various widths, lengths and patterns. The shapecontrol handles the drawing for all the other fundamental shapes.

Important Line Control Properties

Property Description

Borderwidth Specifies the size, in twips, that the line takes.

X1 Contains the number of twips from the left of the formwindow to the start of the line.

X2 Contains the number of twips from the left of the formwindow to the end of the line.

Y1 Contains the number of twips from the top of the formwindow to the left starting point of the line.

Y2 Contains the number of twips from the top of the formwindow to the left ending point of the line.

Page 60: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Intrinsic Controls MS Visual Basic 6 Programming Introduction

48 V0.1

Shape Control

The shape control gives you the ability to draw six different kinds of figures on the form. The

various shading and color properties help you distinguish one shape from another.

Important Shape Control's Properties

Property Description

Shape Contains one of six values that specifies the type of shapethat the shape control takes on. The default shapeproperty is 0-Rectangle.

The shape Control's Shape Value

Value Description

0-Rectangle A Rectangle.

1-Square A Square.

2-Oval An Oval.

3-Circle A Circle.

4-Rounded Rectangle A Rectangle with rounded corners.

5-Rounded Square A Square with rounded corners.

Do exercises Shape Control and Line Drawing

Page 61: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Intrinsic Controls

V0.1 49

Timer Control

A timer control is used to execute a set of codes at regular intervals. The timer control is invisible

to the user at run time.

Important Timer Control Properties

Property Description

Interval Interval property is used to set the number of millisecondsbetween calls to a timer event. Set an interval between 1and 65535. You can set a timer control's interval propertyat design time or run time.

Do Exercise timer control.

Page 62: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Intrinsic Controls MS Visual Basic 6 Programming Introduction

50 V0.1

Drive List Box Control

A DriveListBox control enables a user to select a valid disk drive at run time. Use this control to

display a list of all the valid drives in a user's system. You can create dialog boxes that enable theuser to open a file from a list of files on a disk in any available drive.

Important Drive List Box Properties

Property Description

Drive Used to return the selected drive at run time.

Directory List Box Control

A DirListBox control displays directories and paths at run time. Use this control to display ahierarchical list of directories. You can create dialog boxes that, for example, enable a user to

open a file from a list of files in all available directories.

Important Directory List Box Properties

Property Description

Path Returns or sets the current path. Not available atdesign time

Page 63: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Intrinsic Controls

V0.1 51

File List Box Control

A FileList Box control lists files in the directory. This enables the user to select a valid file and

with a help of a dialog box you can open different files from different directories.

Important File List Box Properties

Property Description

Archive Used to determine whether a FileListBox controldisplays files with archive attributes.

Hidden Used to determine whether a FileList box controldisplays files with hidden attributes.

Normal Used to determine whether a FileList Box controldisplays files with normal attributes.

System Used to determine whether a FileList Box controldisplays files with system attributes.

Filename Returns the filename of a selected file. You can usethis property only at run time.

Pattern Used to set a Value indicating the type of filenamesthat should be displayed when the FileListBox isloaded.

Do Exercise Exploring Drive, Directory, File ListBox Controls

Page 64: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Intrinsic Controls MS Visual Basic 6 Programming Introduction

52 V0.1

ScroollBars

Scroll bars provide easy navigation through a long list of items or a large amount of information.

They can also provide an analog representation of current position. You can use a scroll bar as aninput device or indicator of speed or quantity—for example, to control the volume of a computergame or to view the time elapsed in a timed process.

The toolbox includes both Horizontal and Vertical Scrollbar control.

Important ScrollBar Properties

Property Description

Largechange Specifies the amount that the scrollbar changeswhen the user clicks within the scrollbar's shaft area.

Max Indicates the maximum number of units that thescrollbar value represents at its highest setting. Therange is from 1 to 32767 (the default max value).

Min Indicates the minimum number of units the scrollbarvalue represents at its lowest setting. The range isfrom 1 (the default min value) to 32767.

Smallchange Specifies the amount that the scrollbar changeswhen the user clicks an arrow at either end of thescrollbar.

Value Contains the unit of measurement currentlyrepresented by the position of the scrollbar.

Page 65: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Intrinsic Controls

V0.1 53

Option Button Control

An OptionButton control displays an option that can be turned on or off.

Important Option Button Property

Property Description

Caption Determines the text displayed in an option buttoncontrol.

Value Value property is used to set the state of the optionbutton.

True - The button is selected.

False - The button is not selected.

Check Box Control

A CheckBox control displays an X when selected; the X disappears when the CheckBox is cleared.

Use this control to give the user a True/False or Yes/No option. You can use CheckBox controlsin groups to display multiple choices from which the user can select one or more. You can alsoset the value of a CheckBox programmatically with the Value property.

Important CheckBox Properties

Property Description

Caption Caption property determines the text displayed in acheckbox control.

Value Value property is used to set the state of thecheckbox.

0 - Unchecked

1 - Checked

2 - Grayed or Dimmed

Do Exercise Exploring ScrollBars, CheckBox and OptionButton Controls

Page 66: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Intrinsic Controls MS Visual Basic 6 Programming Introduction

54 V0.1

Data Control

Data Control provides access to data stored in databases using any one of three types of

Recordset objects. (A Recordset object represents the records in a base table or the records thatresult from running a query. )

The Data control enables you to move from record to record and to display and manipulate data

from the records in bound controls.

You can perform most data access operations using the Data control without writing any code atall. Data-aware controls bound to a Data control automatically display data from one or more

fields for the current record or, in some cases, for a set of records on either side of the currentrecord. The Data control performs all operations on the current record.

Important Data Control Properties

Property Description

Connect This property sets the type of DMBS to beconnected. For example, Access, dbase, Foxproetc.

Database Name This specifies the name of the database file.

Recordset Type three types of Recordset objects available on thedata control. These are Table-type Recordset,Dynaset-type Recordset and Snapshot-typeRecordset.

Record Source Name of the table

Page 67: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Intrinsic Controls

V0.1 55

The following table lists the three types of Recordset objects available on the data control.

Recordset type Description

Table-typeRecordset

(dbOpenTable) A set of records that represents asingle database table that you can use to add,change, or delete records.

Dynaset-typeRecordset

(dbOpenDynaset) A dynamic set of records thatrepresents a database table or the results of aquery containing fields from one or more tables.You can add, change, or delete records from adynaset-type Recordset, and the changes will bereflected in the underlying table(s).

Snapshot-typeRecordset

(dbOpenSnapshot) A static copy of a set ofrecords that you can use to find data orgenerate reports. A snapshot-type Recordsetcan contain fields from one or more tables in adatabase but can’t be updated.

Do exercise Using Data Control

Page 68: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Intrinsic Controls MS Visual Basic 6 Programming Introduction

56 V0.1

ExercisePicture Box

Write an application having a form and a picture box on the form. While loading the form, apicture (abc.bmp) should be loaded into the picture box.

• Open a project.

• Add a picture box to the form by dragging and placing the picture box control on theform.

• In the form load event, write the following code.

Private Sub Form_Load()Picture1.Picture = LoadPicture("C:\ABC.BMP")

End Sub

• Press F5 to run the program.

Page 69: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Intrinsic Controls

V0.1 57

ExerciseLabel

Display today's date and time on a 2 label controls on a form.

• Open a project.

• Add two label controls to the form by dragging and placing the controls on the form.

• In the form load event, write the following code.

Private Sub Form_Load()Label1.Caption = DateLabel2.Caption = Time

End Sub

• Press F5 to run the program.

Page 70: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Intrinsic Controls MS Visual Basic 6 Programming Introduction

58 V0.1

ExerciseText Box

Write a program to accept only characters in a text box.

• Open a project.

• Add a text box control to the form by dragging and placing the control on the form.

• In the text box key press event, write the following code.

Private Sub Text1_KeyPress(KeyAscii As Integer)If KeyAscii > 47 And KeyAscii <= 58 Then

KeyAscii = 8End If

End Sub

• Press F5 to run.

Page 71: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Intrinsic Controls

V0.1 59

ExerciseUsing Frames

A frame should have a picture box, two labels and a text box. While loading the form, a picture(abc.bmp) should be loaded in the picture box and today's date and time should be displayed onthe two label controls. Also the textbox should accept only characters.

• Open a project.

• Add a text box control, 2 labels and a picture box control on the frame.

• Write the following code.

Private Sub Form_Load()Picture1.Picture = LoadPicture("C:\abc.bmp")Label1.Caption = DateLabel2.Caption = Time

End Sub

Private Sub Text1_KeyPress(KeyAscii As Integer)If KeyAscii > 47 And KeyAscii <= 58 ThenKeyAscii = 8

End If

• Press F5 to run

Page 72: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Intrinsic Controls MS Visual Basic 6 Programming Introduction

60 V0.1

ExerciseCommand Button

The form should have one textbox and a command button. The user can type a string in thetextbox. Whenever the command button is clicked, the caption of the form should be changed tothe string typed in the textbox.

• Open a project.

• Add a text box control and a command button on the form.

• Write the following code

Private Sub Command1_Click()Command1.Caption = Text1.Text

End Sub

• Press F5 to run.

Page 73: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Intrinsic Controls

V0.1 61

ExerciseList Box

An application should have a text box, a list box and a command button. When the commandbutton is clicked, the content of the text box should be added to the list box.

• Open a project.

• Add a text box control, list box and a command button on the form.

• Write the following code

Private Sub Command1_Click()List1.AddItem Text1.Text

End Sub

• Press F5 to run the program.

Page 74: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Intrinsic Controls MS Visual Basic 6 Programming Introduction

62 V0.1

ExerciseExploring ListBox Control

In this exercise you will create a form with two list boxes and two command buttons to show:

♦ How to Add items in a list box

♦ How to Remove items from a list box

♦ How to use the MultiSelect property of the list box

Creating the form

• Start a new project.

• Add controls to the form, as shown in the following illustration.

Control Property Setting

Form Name frmList

" Caption ListBox Demonstration

ListBox Name lstLeft

" MultiSelect 2 - Extended

" List (Add month names i.e.Jan - Dec)

ListBox Name lstRight

" MultiSelect 2 - Extended

Command Name cmdLeft

" Caption <<

Command Name cmdRight

" Caption >>

Page 75: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Intrinsic Controls

V0.1 63

Writing Code

• In the General Declarations of the form type the followings:

Option Explicit

Private Sub cmdLeft_Click()

'Loop through the list items, and check how many'items are selected. Copy selected items to the Right'ListBox.

Dim i As Integer

For i = 0 To lstRight.ListCount - 1 If lstRight.Selected(i) Then lstLeft.AddItem lstRight.List(i) End If

Next i

'Loop through the list items (from bottom to top),'and check how many items are selected. Delete the'selected items from the Left ListBox.

For i = lstRight.ListCount - 1 To 0 Step -1 If lstRight.Selected(i) Then

lstRight.RemoveItem (i) End IfNext i

End Sub

Private Sub cmdRight_Click()

'Loop through the list items, and check how many'items are selected. Copy selected items to the Left'ListBox.

Dim i As Integer

For i = 0 To lstLeft.ListCount - 1 If lstLeft.Selected(i) Then lstRight.AddItem lstLeft.List(i) End IfNext i

Page 76: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Intrinsic Controls MS Visual Basic 6 Programming Introduction

64 V0.1

'Loop through the list items (from bottom to top),'and check how many items are selected. Delete the'selected items from the Right ListBox.

For i = lstLeft.ListCount - 1 To 0 Step -1 If lstLeft.Selected(i) Then

lstLeft.RemoveItem (i) End If

Next i

End Sub

• Save the Project

• Press F5 to run.

Page 77: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Intrinsic Controls

V0.1 65

ExerciseCombo Box

This application should have a text box, a combo box and a command button. The combo box hasitems like TV, Fridge, Washing machine, Radio etc. When the command is clicked, the content ofthe text box should be deleted from the combo box (if available).

• Open a project

• Add a text box control, combo box and a command button on the form.

• Write the following code

Dim i As IntegerDim j As Integer

Private Sub Command1_Click()i = Combo1.ListCount - 1For j = i To 0 Step -1

If Trim(Combo1.List(j)) = Trim(Text1.Text) ThenCombo1.RemoveItem (j)Combo1.RefreshExit SubEnd If

NextEnd Sub

• Press F5 .to run

Page 78: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Intrinsic Controls MS Visual Basic 6 Programming Introduction

66 V0.1

ExerciseForm & Image Control

Write an application having a form and a image control on the form. While loading the form, apicture (abc.bmp) should be loaded into the image control.

• Open a project.

• Add an image control to the form by dragging and placing the image control on the form.

• In the form load event, write the following code

Private Sub Form_Load()image1.Picture = LoadPicture("C:\ABC.BMP")

End Sub

• Press F5 to run the program.

Page 79: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Intrinsic Controls

V0.1 67

ExerciseShape Control

Write an application having a form, a text box, a command button and a shape control on theform. The user can type values 0 to 5 (only) in the text box. On clicking the command button, thedifferent shapes should be loaded on the form.

• Open a project.

• add a text box, a command button and a shape control to the form by dragging andplacing controls on the form.

• Write the following code

Private Sub Command1_Click()Shape1.Shape = Val(Text1.Text)

End Sub

• Press F5 to run.

Page 80: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Intrinsic Controls MS Visual Basic 6 Programming Introduction

68 V0.1

ExerciseLine Drawing

Write an application to draw a line. The x1, x2, y1 and y2 co-ordinates of the line is to be acceptedin 4 text boxes. On clicking the command button, the line should be drawn.

• Open a project.

• Add a line control, 4 text boxes and a command button to the form by dragging andplacing the controls on the form.

• Write the following code

Private Sub Command1_Click()Line1.X1 = val(text1.text)Line1.Y1 = val(text2.text)Line1.X2 = val(text3.text)Line1.Y2 = val(text4.text)

End Sub

• Press F5 to run the program.

Page 81: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Intrinsic Controls

V0.1 69

ExerciseTimer Control.

Write an application to demonstrate the timer control.

• Open a project.

• Add a label control, a timer control and 2 command buttons to the form by dragging andplacing the controls on the form.

• Set the caption value for the label as “INNOVATION SOFTWARE EXPORTS”

• Write the following code

Private Sub Command1_Click()Timer1.Interval = 0

End Sub

Private Sub Command2_Click()Timer1.Interval = 100

End Sub

Private Sub Timer1_Timer()Dim i As IntegerLabel1.Caption = Right(Trim(Label1.Caption),_Len(Trim(Label1.Caption)) – 1) + Trim(Left(Label1.Caption, 1))

End Sub

• Press F5 to run the program.

Page 82: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Intrinsic Controls MS Visual Basic 6 Programming Introduction

70 V0.1

ExerciseExploring Drive, Directory, File ListBox Controls

In this exercise, you will create a Image Viewer application using the Drive, Directory and Filelist box controls.

Creating the form

• Start a new project.

• Add controls to the form, as shown in the following illustration.

Control Property Setting

Form Name frmView

" Caption Image Viewer

File ListBox Name File1

" Pattern *.bmp; *.ico

Directory ListBox Name Dir1

Drive ListBox Name Drive1

Command Button Name cmdShow

" Default True

Command Button Name cmdExit

" Cancel True

Page 83: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Intrinsic Controls

V0.1 71

Writing Code

• In the General Declarations of the form type the following:

Option Explicit

Private Sub cmdExit_Click() Unload MeEnd Sub

Private Sub cmdShow_Click() 'Load the selected picture file from the File list box 'to Image1. Image1.Picture = LoadPicture(Dir1.Path & "\" & File1.filename)End Sub

Private Sub Dir1_Change()'Change the File list box as the user changes the'Directory list box.File1.Path = Dir1.PathEnd Sub

Private Sub Drive1_Change()'Change the Directory list box as the user changes the'Drive list box.Dir1.Path = Drive1.DriveEnd Sub

• Save the Project

• Press F5 to run the program

Page 84: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Intrinsic Controls MS Visual Basic 6 Programming Introduction

72 V0.1

ExerciseExploring ScrollBars, CheckBox andOptionButton Controls

In this exercise, you will create a form with Scroll Bars and Option Buttons to implement the use

of Shape control.

Creating the form

• Start a new Visual Basic project.

• Add controls to the form, as shown below:

Control Property Setting

Form Name frmGnrl

" Caption Buttons and ScrollBars Demo

Frame Name Frame1

HScrollBar Name HScroll1

" Min 500

" Max 5000

" LargeChange 100

" SmallChange 10

VScrollBar Name Vscroll1

" Min 500

" Max 5000

" LargeChange 100

" SmallChange 10

Page 85: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Intrinsic Controls

V0.1 73

Shape1 Name Shape1

CheckBox Name chkFill

" Value False

OptionButton Name optBox

" Value True

OptionButton Name optCircle

OptionButton Name optRoundBox

Writing Code

• In the General Declarations of the form type the followings:

Option Explicit

Private Sub chkFill_Click()

'Check for the value if Fill is selected set the FillStyle property'of the Spahe control to 0 - Solid , else 1 - Transparent

If chkFill.Value = vbChecked Then Shape1.FillStyle = 0Else Shape1.FillStyle = 1End If

End Sub

Page 86: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Intrinsic Controls MS Visual Basic 6 Programming Introduction

74 V0.1

Private Sub HScroll1_Change()

'Changes the width of the Shape control according to the 'value of the HScrollBar Shape1.Width = HScroll1.Value

End Sub

Private Sub optBox_Click()

'Check whether Box option is selected, if selected change the'Shape property of the Shape control to 0 - RectangleIf optBox.Value Then Shape1.Shape = 0End If

End Sub

Private Sub optCircle_Click()

'Check whether Circle option is selected, if selected change the'Shape property of the Shape control to 2 - OvalIf optCircle.Value Then Shape1.Shape = 2End If

End Sub

Private Sub optRBox_Click()

'Check whether RoundedBox option is selected, if selected change the'Shape property of the Shape control to 4 - RoundedRectangle

If optRBox.Value Then Shape1.Shape = 4End If

End Sub

Private Sub VScroll1_Change()

'Changes the height of the Shape control according to the 'value of the VScrollBar

Shape1.Height = VScroll1.Value

End Sub

• Save and press F5 to run the program

Page 87: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Intrinsic Controls

V0.1 75

ExerciseUsing Data Control

Create a application using Data Control to manage Employees table we created inCompany.MDB database. The application should have the following Controls.

• Insert, Edit, Delete records from the table,

• Save and Cancel transactions made by the user,

• Find specific record by supplying EmpNo.

Solution:

Creating the form

• Start a new Visual Basic project.

• Add controls to the form, as shown in the following illustration.

Control Property Setting

Form Name frmEmp

' Caption Employees

Data Name dtaEmp

' DatabaseName C:\Company.MDB

' RecordSource Employees

TextBoxs Name txtFields( )

' Index [0 - 4]

' DataSource dtaEmp

' DataField [EmpNo, EmpName, Desig,DeptNo,

Commands Name cmdInsert, cmdEdit,cmdRemove, cmdCancel,cmdFind, cmdExit, cmdSave

Caption Insert, Edit, Remove,Save, Cancel, Find, Exit

Your Form should look like this at run time:

Page 88: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Intrinsic Controls MS Visual Basic 6 Programming Introduction

76 V0.1

Writing Code

• In the General Declarations of the form type the following:

Option Explicit

Private Sub cmdCancel_Click() dtaEmp.Recordset.CancelUpdate Call LockText Call OnButtonsEnd Sub

Private Sub cmdDelete_Click() If MsgBox("R U Sure to Delete ?", vbQuestion + vbYesNo) = vbYes_

Then dtaEmp.Recordset.Delete dtaEmp.Refresh End IfEnd Sub

Private Sub cmdEdit_Click() Call UnLockText Call OffButtons dtaEmp.Recordset.EditEnd Sub

Private Sub cmdExit_Click() Unload MeEnd SubPrivate Sub cmdFind_Click() Dim c As Integer

Page 89: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Intrinsic Controls

V0.1 77

c = InputBox("Enter Employee # to Find") dtaEmp.Recordset.FindFirst "EmpNo = " & c If dtaEmp.Recordset.NoMatch ThenMsgBox "There is no such Employee #"End IfEnd Sub

Private Sub cmdInsert_Click() Call UnLockText Call OffButtons dtaEmp.Recordset.AddNewEnd Sub

Private Sub UnLockText() Dim i As Integer For i = 0 To 4 txtFields(i).Locked = False NextEnd Sub

Private Sub LockText() Dim i As Integer For i = 0 To 4 txtFields(i).Locked = True NextEnd Sub

Private Sub OffButtons() cmdInsert.Enabled = False cmdEdit.Enabled = False cmdDelete.Enabled = False cmdExit.Enabled = False cmdFind.Enabled = False cmdSave.Enabled = True cmdCancel.Enabled = TrueEnd Sub

Private Sub OnButtons() cmdInsert.Enabled = True cmdEdit.Enabled = True cmdDelete.Enabled = True cmdExit.Enabled = True cmdFind.Enabled = True cmdSave.Enabled = False cmdCancel.Enabled = FalseEnd Sub

Private Sub cmdSave_Click() dtaEmp.Recordset.Update dtaEmp.Refresh Call LockText Call OnButtons

Page 90: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Intrinsic Controls MS Visual Basic 6 Programming Introduction

78 V0.1

End Sub

Private Sub dtaEmp_Reposition() dtaEmp.Caption = "Record # : " & _dtaEmp.Recordset.AbsolutePosition + 1End Sub

Private Sub Form_Load() dtaEmp.DatabaseName = App.Path & "\Company.mdb" dtaEmp.RecordSource = "SELECT * FROM Employees_ ORDER BY EmpNo" dtaEmp.RefreshEnd Sub

• Save the Project and press F5 to run.

Page 91: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

V0.1 79

Visual Basic Practice Exercises

Objectives

In this chapter you will learn Programming in Visual Basic byobserving some sample programs.

Page 92: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

80 V0.1

Exercise 1Displaying the date and time

Write a program to display the current date and time in a form.

Solution 1

• Open a new project.

• Place two TextBox controls on the form.

• Choose the timer control from the tool box and place it on the form. Press F4 to view

the property window of the timer control. Set the interval property of the timer control to1000 (which implies that the timer is activated every 1 second).

• Enter the following code in the Form_Load( ) procedure:

Private Sub Form_Load( )Text1.Text = Time$Text2.Text = Date$

End Sub

• Enter the following code in the Timer1_Timer( ) Procedure:

Private Sub Timer1_Timer( )Text1.Text = Time$

End Sub

• Execute the program by pressing F5

Page 93: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 81

Exercise 2Writing Event Procedures

Write Event Procedures for the following:

1. To display the day for a given date.

2. To convert a text from lowercase to uppercase.

Solution 2

• Open a new project.

• Place 4 TextBox controls on the form.

• Place 2 Label Controls on the form. Change their Caption Properties to "Enter a Date" and"Enter a Text".

• Place 2 CommandButton Controls. Change their caption properties to "Day of the Date"and "Uppercase".

• Enter the following code in the Click Event of the command button controls:

Private Sub Command1_Click( )

Dim Mydate As Datemydate = Format (Text1.Text, "D-MMMM-YY")Text2.Text = Format (Mydate, "dddd")

End Sub

Private Sub Command2_Click( )Text4.Text = Format (Text3.Text, ">")

End Sub

Page 94: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

82 V0.1

Exercise3Event Procedure- sum of values

Write an event procedure to find the sum of numbers from 1 to the selected value. Use ahorizontal scroll bar to set the maximum value.

Solution 3

• Open a new project.

• Place a horizontal scroll bar and set its maximum property value to 100.

• Place a CommandButton and a TextBox in the form.

• Change the Caption Property of the Command Button to "Add".

• Enter the following code in the click event of the Add command button:

Private Sub Command1_Click( )Dim I, J As IntegerI = 1Do While I < HScroll1.Value

J = J + 1I = I + 1

LoopText1.Text = Str(J)

End Sub

Page 95: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 83

Exercise 4Using Select Case

Write a VB Program to change the caption of a label using the select case ---- end select structure.

Solution 4

• Open a new project.

• Place a Label, TextBox and CommandButton control on your form.

• The caption property of the CommandButton is changed to "Select".

• The Caption Property of the Label and Text property of the TextBox is set to empty.

• Enter the following code in the Command1_Click( ) procedure.

Private Sub Command1_Click( )Dim N As IntegerN = Va l(Text1.Text)If N <= 2 Then

Select Case Text1.TextCase 0Label1.Caption = "Good-Day"

Case 1Label1.Caption = "Good Morning"Case 2Label1.Caption = "How are You ?"

End SelectElselabel1.Caption = "Invalid Option"End IF

End Sub

Page 96: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

84 V0.1

Exercises 5 to 9Creating Forms and Controls

Write VB programs to create forms and controls, Write code in event procedures, Trap andhandle a run-time error, Restrict input in a TextBox control & Compile an executable application.

5. Creating FormsIn this exercise, you will create two simple forms for an application.

Create the main form

1. Start a new Visual Basic project.2. Add controls to the form, as shown in the following illustration.

3. Using the Visual Basic Menu Editor, add menus to the form as follows:File-- Exit

Help -- About

4. Save the project.

Page 97: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 85

Create the About form

1. Add a new form to the project that will be used as the About box for theapplication.

2. Add controls to the form, as shown in the following illustration.

The picture in the upper-left corner is an Image control. You can select anyicon you want from the Visual Basic \Icons folder.

3. Save the project.

6. In this exercise, you will add code to make the application functional.

Add code for the temperature conversion

1. In the KeyUp event for the Celsius text box, convert the number enteredto Fahrenheit and place the converted number in the Fahrenheit text box.The conversion formula is: Fahrenheit = (Celsius * 9/5) + 32

2. In the KeyUp event for the Fahrenheit text box, convert the enterednumber to Celsius, and place the converted number in the Celsius text box.The conversion formula is: Celsius = (Fahrenheit - 32) * 5/9.

3. Test the application. What happens if you enter text characters in one ofthe text boxes?

Observe the CODE:

Private Sub txtCelsius_KeyUp(KeyCode As Integer, Shift As Integer)txtFahrenheit.Text = (txtCelsius.Text * 9 / 5) + 32

End Sub

Private Sub txtFahrenheit_KeyUp(KeyCode As Integer, Shift AsInteger) txtCelsius.Text = (txtFahrenheit.Text - 32) * 5 / 9

End Sub

Page 98: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

86 V0.1

Add code for menus and an OK button

1. In the Click event for the Exit menu command, Unload the form and Endthe application.2. In the Click event for the About menu command, Show the About box asa modal form.For information about modal forms, see the Show method in the Help forVisual Basic.3. In the Click event for the OK button on the About form, Unload theAbout form.4. Save the project.5. Test the application.

Observe the CODE:

Main Form Code

Private Sub mnuFileExit_Click() Unload Me EndEnd Sub

Private Sub mnuHelpAbout_Click() frmAbout.Show vbModalEnd Sub

About Form CodePrivate Sub cmdOK_Click() Unload MeEnd Sub

Page 99: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 87

7. Creating an Error-Handling Routine

In this exercise, you will add error handling to trap for the Type Mismatchrun-time error that occurs if users type a non-numeric value into one of thetext boxes.

Create an error handler

1. In the KeyUp event procedure for the Celsius TextBox control, add an OnError Goto statement to enable error handling.2. Create the error-handling routine specified in the On Error Gotostatement.3. In the error-handling routine, add code to test for run-time error 13: TypeMismatch.4. If error 13 is found, set the Text property of the txtFarhenheit text box toCan't Convert.5. Test the application.

Observe the CODE:

Private Sub txtCelsius_KeyUp(KeyCode As Integer, Shift As Integer) On Error GoTo handleErr txtFahrenheit.Text = (txtCelsius.Text * 9 / 5) + 32 Exit Sub handleErr: If Err.Number = 13 Then 'type mismatch txtFahrenheit.Text = "Can't convert" Else Err.Raise Err.Number End IfEnd Sub

Page 100: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

88 V0.1

8. Restricting Input

In this exercise, you will restrict user input for the Username text box to alimited length and to use only uppercase characters.

Restrict user input

1. Use the MaxLength property of the Username text box to limit thenumber of characters that can be entered to 15.

2. In the KeyPress event of Username text box, convert all characters enteredin the text box to uppercase characters.3. Save the project.4. Test the application.Is text box input limited to 15 characters? Are all characters converted touppercase characters?

9. Creating an Executable File

In this exercise, you will compile your project into an executable application,and then test the application.

Create an executable file

1. On the File menu, click Make <Project>.exe.2. Name the application Convert.exe, and save it.3. To compile the application, click OK.

Test the executable file

1. Using the Microsoft Windows Explorer, navigate to the folder where thefile Convert.exe is saved. Double click on it to test the application.

Page 101: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 89

Exercise 10Adding and deleting Items from a list

A Store presently has 4 brands of Toothpaste. It proposes to add a few more brands to theexisting list. Write an event procedure to add Items to the List as well as Delete Items from theList.

Solution 10

• Open a new project.

• Place a ComboBox control in the form.

• Place a TextBox control.

• Place two CommandButton controls on the form.

• Set the caption property of the CommandButtons to "Add" and "Delete".

• Enter the following code in the Add Button procedure:

Private Sub CmdAdd_Click( )Combo1.AddItem Text1.TextText1.Text = ""CmdDelete.Enabled = True

End Sub

• Enter the following code in the Delete button procedure:

Private Sub CmdDelete_Click( )n = Combo1.ListIndexIf n <> -1 ThenCombo1.RemoveItem nEnd If

End Sub

Page 102: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

90 V0.1

Exercise 11Setting Background Colours

Write a program to change the background color of the Form using three Option Buttons.

Solution 11

• Open a new project.

• Place 3 OptionButtons in the Form.

• Write the following code in the Click Event of the Option Buttons:

Private Sub Option1_Click( )Form1.BackColor = QBColor(2)

End Sub

Private Sub Option2_Click( )Form1.BackColor = QBColor(5)

End Sub

Private Sub Option3_Click( )Form1.BackColor = QBColor(0)

End Sub

Page 103: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 91

Exercise 12Using Control Arrays

Write a program to change the background color of the Form using 3 Option Buttons UsingControl Arrays.

Solution 12

• Open a new project.

• Place an OptionButton Control in the Form and Change the Caption property to"Option".

• Select the Option Button and Press Cntrl + C and Cntrl + V to create a Control Array. Amessage Box will appear with the message "Object with the name already exists, CreateControl Array?" Choose "Yes" to create Control Array.

• Enter the following code in the Click Event of the Option buttons.

Private Sub Option_Click(Index As Integer)Form1.BackColor = QBColor(Index + 1)

End Sub

• Press F5 to run the program.

Page 104: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

92 V0.1

Exercise 13Displaying a Message Box

A company proposes to introduce housing loan facilities for its employees who are in theManagerial Grade. Based on the following parameters, the employees who are eligible to availthe facility are identified.

A. Marital Status (Y/N)

B. Managerial Grade (Y/N)

C. Age of Children < 5 (Y/N)

Note: Y denotes eligibility

Display a message box if the employee is eligible for the loan.

Solution 13

• Open a new project.

• Place 3 CheckBox Controls and a CommandButton in the form.

• Enter the following code in the click event of the command button:

Private Sub Command1_Click( )If Check1.Value = 1 And Check2.Value=1 And Check3.Value = 1

ThenMsgBox "Eligible for the Housing Loan"

ElseMsgBox "Not Eligible for the Housing Loan"

End IfEnd Sub

Page 105: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 93

Exercise 14Using MouseDown event

Write a VB application to identify whether the Right or Left mouse Button was clicked.

Solution 14

• Open a new project.

• Place 2 CheckBoxes on the form.

• Place a TextBox to display a message when the mouse button is clicked.

• Place a Command Button to exit from the Form.

• Enter the following code in the MouseDown event of the Form:

Private Sub MouseDown (Button As Integer, Shift As Integer,_X as Single, Y As Single)

If Button = 1 ThenText1.Text = "LeftButton of the Mouse is Pressed"Check1.Value = 1

ElseCheck1.Value = 0

End IF

If (Button And 2) = 2 ThenText1.Text = "RightButton of the Mouse is Pressed"Check2.Value = 1

ElseCheck2.Value = 0

End IFEnd Sub

Private Sub Command1_Click( )End

End Sub

Page 106: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

94 V0.1

Exercise 15Adding a Category Dynamically

A dealer who sells a range of home appliances has computerized his operations. His monthlysales report on each product category is Printed Out by Choosing the Required Category from amenu. Write a program to enable the dealer to add new product categories dynamically. The

total number of categories that can be added are 10.

Solution 15

• Open a new project.

• Select Menu Editor from the Tools Menu to customize a menu.

• Add the menu items as given below:

Caption Name&fans mnFans&Music Systems mnMusic

• Set the Index Property of the menu Item &Music Systems to 0.

• Place a TextBox Control on the Form to accept the new Item that is to be added to themenu.

• Place a CommandButton to activate the application.

• Write the code in the General Declarations section of the Form.

Dim lastitem As Integer

Page 107: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 95

• Write the following code in the Click event of the CommandButton.

Private Sub Command1_Click( )lastitem = lastitem + 1If lastitem > 10 Then

MsgBox "Limit Exceeded"Else

Load mnMusic(lastitem)mnMusic(lastitem).Caption = Text1.Text

End IfEnd Sub

• Press F5 to run the form.

Enter data in the Text Box and click the CommandButton.

The added item is entered to the menu.

Page 108: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

96 V0.1

Exercise 16Command Buttons

A company needs to validate the joining date of its employees. How would you implement thisin Visual Basic?

Solution 16

• Open a new project.

• Change the Caption Property of the Form to InputBox program.

• Place a CommandButton to activate an InputBox which will accept the date to bechecked. Change its property to Join Date.

• Enter the following code in the click event of the CommandButton:

Private Sub Command1_Click( )Dim ret_date As dateret_date = InputBox("Enter the Date of Joining", "Date of Joining")If ret_date > Date Then

MsgBox "Invalid Date!! Re-enter"Else

MsgBox "Date is Valid"End If

End Sub

• Execute the form by pressing F5 . Click the Join Date button which displays an input

box. If the entered date is greater than the system date, it displays a message "InvalidDate!! Re-enter".

Page 109: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 97

Exercise 17Menu Control Array

Develop an application to create Menu Control Arrays at run time.

Solution 17

• Open a new project.

• Change the Caption Property of the Form to Menu Control Arrays.

• Add the following Menu Items to the Form:

Caption Name&File mnFile&Add mnAdd&Delete mnDeleteE&xit mnExit- mnSep

• Select the last menu item mnSep and set its Index to 0.

• Enter the following code in the declaration section of the Form.

Option ExplicitDim LastItem As Integer

• Enter the following Code in the Form_Load( ) procedure:

Private Sub Form_Load( )LastItem = 0mnDelete.Enabled = False

End Sub

• Enter the following Code in the mnAdd_Click( ) procedure:

Private Sub mnAdd_Click( )LastItem = LastItem + 1Load mnSep(LastItem)mnSep(LastItem).Caption = "ITEM" + Str(LastItem)mnDelete.Enabled = True

End Sub

Page 110: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

98 V0.1

• Enter the following Code in the mnDelete_Click( ) procedure:

Private Sub mnDelete_Click( )Unload mnSep(LastItem)LastItem = LastItem - 1If LastItem = 0 Then

mnDelete.Enable = FalseEnd If

End Sub

• Enter the following Code in the mnSep_Click( ) procedure:

Private Sub mnSep_Click(Index As Integer)MsgBox "The selected item is "+ Str(Index)

End Sub

Page 111: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 99

Exercise 18Drag and Drop

Develop an application to illustrate the Drag and Drop Operations.

Solution 18

• Create a new project.

• Add an image control and set its DragMode Property to 1-Automatic.

• Picture Property is set to "C:\VFP\Samples\Graphics\Icons\Elements\Water.Ico"

Its stretch property is set to True.

• Add a TextBox and a CommandButton in the Form.

• Write the following code in the General Declarations of the Form:

Option Explicit

• Write the following Code in the Form_DragDrop( ) procedure.

Private Sub Form_DragDrop (Source As Control, X As Single, _Y As Single, State As Integer)

Dim Info As StringInfo = "Now Dragging"Info = Info + Source.TagInfo = Info + "Over the Form"Info = Info + "State ="Info = Info + Str(State)Text1.Text = InfoEnd Sub

Page 112: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

100 V0.1

• Enter the following code in the Command1_DragOver ( ) procedure:

Private Sub Command1_DragOver (Source As Control, X As Single, _Y As Single, State As Integer)

Dim Info As StringInfo = "Now Dragging"Info = Info + Source.TagInfo = Info + "Over the Exit Button"Info = Info + "State ="Info = Info + Str(State)Text1.Text = Info

End Sub

• Enter the following code in the Command1_Click ( ) procedure:

Private Sub Command1_Click( )End

End Sub

Page 113: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 101

Exercise 19Common Dialogue Control

Design an application using the Common Dialog Control to display the Font, Save and OpenDialog Boxes without using the Action property of the Control. (Hint: Use ShowOpen,ShowSave, ShowColor Methods)

Solution 19

• Open a new project.

• Add a CommandButton, OptionButton and CommonDialog Control to your Form.

• The Index property of the OptionButton is set to 0.

• Enter the following Code in Command1_Click( ) and Form_Paint( ) procedures:

Private Sub Command1_Click( )If Option(0).Value Then

CommonDialog1.ShowOpenElseIf Option(1).Value Then

CommonDialog1.ShowSaveElseIf Option(2).Value Then

CommonDialog1.ShowColorEnd If

End Sub

Private Sub Form_Paint ( )Static FlagFormPainted As IntegerIf FlagFormPainted <> True Then

For i = 1 to 2Load Option1(i)Option1(i).Top = Option1(i-1).Top + 350Option1(i).Visible = Truenext iOption(0).Caption = "Open"Option(1).Caption = "Save"Option(2).Caption = "Color"Command1.Caption = "Show Dlg"FlagFormPainted = True

End IfEnd Sub

Page 114: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

102 V0.1

Exercise 20Drawing Points on a Form

Draw Points on a Form at random locations with Red, Blue and Green Colors. (HINT: Use Psetmethod and Rnd Functions).

Solution 20

• Open a new project.

• Add a Timer Control and Set Interval Property to 50.

• The caption property of the form is changed to "Drawing Program".

• Menu Items are added as per the following specifications:

Caption Name&File mnFile...&Points mnPoints...&Clear mnClear...- mnSep...E&xit mnExit

• Write the following Code in the General Declarations:

Option ExplicitDim Points

• Write the following code in the Form_Load( ) procedure:

Private Sub Form_Load( )Points = 0

End Sub

• Write the following code in the mnClear_Click( ) procedure:

Private Sub mnClear_Click( )Points = 0Form1.Cls

End Sub

Page 115: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 103

• Write the following code in the mnPoints_Click( ) procedure:

Private Sub mnPoints_Click( )Points = 1

End Sub

• Write the following code in the mnTimer1_Timer( ) procedure:

Private Sub Timer1_Timer( )Dim R, G, BDim X, YDim CounterIf Points = 1 Then

For Counter = 1 to 100 Step 1R = Rnd * 255G = Rnd * 255B = Rnd * 255X = Rnd * Form1.ScaleWidthY = Rnd * Form1.ScaleHeightForm1.Pset(X,Y), RGB(R,G,B)

NextEnd If

End Sub

• Write the following Code in the Exit_Click( )

Private Sub Exit_Click( )End

End Sub

Page 116: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

104 V0.1

Exercise 21Drawing Lines on a Form

Enhance the above program so that lines are drawn instead of Points.

Solution 21

• Open the above project and add a menu item mnLines to the form.

• Write the following Code to the mnLines_Click( ).

Private Sub mnLines_Click( )Dim CounterFor Counter = 1 to 100 Step 1Line - (Rnd * Form1.ScaleWidth, Rnd * Form1.ScaleHeight), RGB(0,0,0)Next

End Sub

Page 117: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 105

Exercise 22Using DrawStyle and ScaleWidth Properties

Develop a small application to draw six lines in a form using DrawStyle and ScaleWidthproperties.

Solution 22

• Open a new project.

• Write the following code in the Form_Click( ).

Private Sub Form_Click( )Dim IScaleHeight = 8For I = 0 to 5

DrawSytle = ILine(0, I+1) - (ScaleWidth, I + 1)

Next IEnd Sub

Page 118: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

106 V0.1

Exercise 23Develop a circle application

Solution 23

• Create a new project and write the following code in the Form_Click( ).

Private Sub Form_Click( )Dim CX, CY, RadiusScaleMode = 3CX = ScaleWidth / 2CY = ScaleHeight / 2If CX > CY Then Limit = CY Else Limit = CXFor Radius = 0 to Limit

Circle(CX, CY), Radius, RGB(Rnd * 255, Rnd * 255, Rnd * 255)Next Radius

End Sub

Page 119: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 107

Exercise 24Drawing thickening lines

Write a program using Line method to draw a gradually thickening Line on the Form.

Solution 24

• Create a new project and add the following code in the Form_Click( ) procedure:

Private Sub Form_CLick( )Dim IDrawWidth = 1Pset (0, ScaleHeight / 3)ForeColor = QBColor(0)For I = 1 to 15 Step 3

DrawWidth = ILine = Step(ScaleWidth / 3, 0)Next I

End Sub

Page 120: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

108 V0.1

Exercise 25Displaying File Contents

Write a program that displays the contents of the file CONFIG.SYS and AUTOEXEC.BAT.

Solution 25

• Open a new project and add a TextBox to the Form. The MultiLine property of theTextBox is set to True.

• Enter the following Code in the Form_Load( ) Procedure:

Private Sub Form_Load( )Filenum = FreeFileOpen "C:\CONFIG.SYS" For Input As filenumText1.Text = Input(LOF(filenum), filenum)Close filenum

End Sub

• Open a new project and add a TextBox to the Form. The MultiLine property of theTextBox is set to True.

• Enter the following Code in the Form_Load( ) procedure:

Private Sub Form_Load( )filenum = FreeFileOpen "C:\AUTOEXEC.BAT" For Input As filenumText1.Text = Input(LOF(filenum), filenum)Close filenum

End Sub

Page 121: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 109

Exercise 26Entering User text

Create a project that has a TextBox which allows the user to enter any text. On the form therewould be three CommandButtons: namely DISPLAY, CLEAR and EXIT. The user can type anytext in the text box. Clicking on the DISPLAY button will change the FORM CAPTION to the text

which you entered in the text box. When CLEAR is clicked, the FORM CAPTION will be cleared.Clicking on the EXIT button, will exit the program.

Solution 26:

• From the File menu, select New Project. Select Standard EXE and click on OK.

• Double click on the TextBox from the TOOL BOX. This will result in the textbox beingdisplayed on the form. Press F4 to get the properties of this TEXT BOX. Make the text

property of text box to NULL. Place this button appropriately on the form.

• Double click on the Command Button in the tool box. This will place a Command Button

on the form. Select this command button and press F4 to get the properties. Change the

Caption property from 'Command1' to 'Display'.

• Place this button appropriately on the form.

• Repeat the above step to create the CLEAR and EXIT BUTTONs.

• Now, double click on the Display button to go to the code. Type the following code:

Form1.caption = text1.text

When the program runs, if the user types any text in the text box and clicks on Displaybutton, this will result in the caption of the form getting changed to the typed text.

• Double click on the Clear button to go to the code. Type the following code:

Form1.caption = ""

When the program runs, if the user clicks on Clear button, this will result in the caption of theform getting cleared.

• Double click on the Exit button to go to the code. Type the following code:

End

When the program runs, if the user clicks on Exit, this will result in stopping the execution ofthe program.

Page 122: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

110 V0.1

Exercise 27Create a form with a Label

(Enter Text), TextBox, a CommandButton (Font).

In the Text Box, the user can type any text. Then, when the user clicks on font command button,

the form should be extended to display the rest of the form which has the following optionswhich the user can choose.

a) Choose the type of font from the Combo Box.

b) Choose the style of font from the Combo Box.

c) Choose the size of font from the Combo Box.

Also there is a choice to click on the 'underline' / the 'Strike Though' CheckBoxes. As and when

the choices on font / style / size are made, the text in the Preview label should reflect thechanges.

Clicking on the OK button, will result in the typed text being displayed in the chosen font / style

/ size. Clicking on exit will result in stopping the execution of the program.

Solution 27:

• Open a form and put a label (Enter Text) and a TextBox.

• Place a command button on the form with caption FONT.

• Choose a FRAME and place it below the font command button on the form. Change itscaption to Atributes.

• In the Attributes frame, place 3 combo boxes. Also place 3 labels with captions Font, Styleand Size.

• Also in the Attributes frame, place two check boxes with caption Underline and StrikeThrough.

• Place a label next to the 2 check boxes. This label should have a caption Preview.

• Next to this Preview label, place another label (with no caption) with border style set to 1- Fixed single.

• At the bottom of the Attributes frame, place two command buttons - OK and Exit.

Page 123: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 111

• Enter the following code in the Form_Load() event procedure.

Private Sub Form_Load()h = Form1.Heightf = Frame1.HeightFrame1.Visible = FalseForm1.Height = h - f 'initial form height before you click ‘on

font buttonEnd Sub

• Enter the following code in the Text1_Change() procedure.

Private Sub Text1_Change()Label5.Caption = Text1.Text

End Sub

• Declare two global variables f and h as follows:

Option ExplicitDim f, h As Integer 'the variable f and h are declared globally' h represents actual height of the form'f represents actual height of the frame

• Enter the code in the font click event.

Private Sub Command1_Click() 'executes when font button is clicked

Form1.Height = h 'initial form height after you click on font buttonFrame1.Visible = True

End Sub

• Choose Combo1, properties, List and type in the names of fonts (like Ariel, Times Romanetc.)

• Choose Combo2, properties, List and type in the style (like Italic, BoldItalic)

• Choose Combo3, properties, List and type in the sizes (like 8, 10, 12, 14, 16 etc etc.)

• The code for Text1 change event is as follows:

Private Sub Text1_Change()Label5.Caption = Text1.Text

End Sub

Page 124: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

112 V0.1

• The code for Combo1_LostFocus(), Combo2_LostFocus() and Combo3_LostFocus() is asfollows:

Private Sub Combo1_LostFocus() 'executes after you selected font nameLabel5.FontName = Combo1.Text

End Sub

Private Sub Combo2_LostFocus() 'executes after you selected font styleIf Combo2.Text = "Italic" Or Combo2.Text = "BoldItalic" Then

Label5.FontItalic = TrueLabel5.FontBold = False

ElseLabel5.FontItalic = FalseLabel5.FontBold = True

End IfEnd Sub

Private Sub Combo3_LostFocus() 'executes after you selected font size

Label5.FontSize = Val(Combo3.Text)End Sub

• The code for checkboxes 'under line' and strike through' are as follows:

Private Sub Check1_Click()'executes when check box Underline is checked

If (Check1.Value = 1) ThenLabel5.FontUnderline = True

ElseLabel5.FontUnderline = False

End IfEnd Sub

Private Sub Check2_Click() 'executes when check box strikethrough is checked

If (Check2.Value = 1) ThenLabel5.FontStrikethru = True

ElseLabel5.FontStrikethru = False

End IfEnd Sub

Page 125: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 113

• The code for the OK button is as follows:

Private Sub Command3_Click() 'executes after you selected Ok button

Text1.FontName = Label5.FontNameText1.FontSize = Label5.FontSizeIf Label5.FontItalic = True Then

Text1.FontBold = FalseText1.FontItalic = True

ElseText1.FontBold = TrueText1.FontItalic = False

End IfIf (Check1.Value = 1) Then

Text1.FontUnderline = TrueElse

Text1.FontUnderline = FalseEnd IfIf (Check2.Value = 1) Then

Text1.FontStrikethru = TrueElse

Text1.FontStrikethru = FalseEnd If

End Sub

• The code for Exit button is:

Private Sub Command4_Click() ' code for end buttonEnd

End Sub

Page 126: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

114 V0.1

Exercise 28Creating a Project

Create a project which accepts Basic Pay, Deductions and Allowance. The net pay should becalculated when the user clicks on the Calculate button. Clicking on the Quit button should stopthe execution of the program.

Solution 28

• Double Click on the Label option available in the toolbox. Change the caption to BASIC.Size it and Place it appropriately on the screen. Repeat the steps to create the labels forDeductions, Allowance and Net pay.

• Place 4 TextBoxes - one each in front of the 4 labels created above.

• Create 2 command Buttons - CALCULATE and QUIT.

• Double click on the CALCULATE button to view the code. Enter the following code.

Text4.Text = Val(Text1.Text) - Val(Text2.Text) + Val(Text3.Text)

This will Calculate the Net pay = Basic - Deduction + Allowance

Page 127: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 115

Exercise 29List Boxes

Create a form to display a Drive List Box, Directory List Box, File List Box and ExitCommandButton. The user can choose any drive, any directory, and then the file list box displaysthe list of .BMP files in the file list box. The user can click on any of the .BMP files to display the

graphic on the screen. Clicking on the EXIT button, quits the program.

Hint: in the file list box properties set pattern =*.bmp This allows the filelist box to display only bitmap files

Solution 29

Observe the Code:

Option Explicit

Private Sub Command1_Click() ' EXIT BUTTONEnd

End Sub

Private Sub Dir1_Change()File1.filename = Dir1.Path 'SETS THE PATH TO FILELISTBOX TO DISPLAY FILES IN 'CURRENT DIRECTORY

End Sub

Private Sub Drive1_Change()On Error Resume Next'THIS STATEMENT MOVES THE CONTROL TO THE NEXT

'STATEMENT IF AN ERROR HAD OCCURED‘IN THE CURRENT STATEMENT

Dir1.Path = Drive1.Drive 'SETS THE PATH TO ‘DIRECTORY ‘LISTBOX TO DISPLAY‘DIRECTORIES IN THE ‘CURRENT DRIVE

End Sub

Private Sub File1_DblClick()'LOADS THE IMAGE FROM THE SELECTED FILE IN THE‘FILE LIST BOXImage1.Picture = LoadPicture(Dir1.Path & "\" & File1.filename)Dir1.Visible = FalseFile1.Visible = FalseCommand1.Top = Form1.TopCommand1.Left = Form1.Width - Command1.WidthDrive1.Visible = False

End Sub

Page 128: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

116 V0.1

Exercise 30Working with List Boxes

Create a form with a TextBox, ListBox and three CommandButtons (Add, Delete, Clear). Whenyou type some text in TextBox and Click on Add button, the text should be added to the currentlist of items in the ListBox. When an item is selected from the ListBox and Delete

CommandButton is clicked, the selected item should be deleted from the list. Clicking on ClearButton should clear all the items in the list box.

Solution 30

Observe the coding:

Option ExplicitDim i As Integer

Private Sub Command1_Click()List1.AddItem (Text1.Text)'adds an item into the list from the text box

End Sub

Private Sub Command2_Click()List1.RemoveItem (i)'removes the selected item i holds the index'of the selected item which is set when you'click on list1_click

End Sub

Private Sub Command3_Click()List1.Clear' this clears the list box

End Sub

Private Sub List1_Click()i = List1.ListIndex'the selected item index is set to a'global variable i

End Sub

Page 129: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 117

Exercise 31Alarm Clock

Write an Alarm Clock Program. A frame with caption Alarm Clock should be shown whichshould display the system time in hh:mm:ss. Double Clicking on the form should enable the userto enter a time for alarm. The alarm should beep at the set time.

Solution 31

Observe the coding:

Option ExplicitDim AlarmTimeConst conMinimized = 1

Private Sub Form_Click()AlarmTime = InputBox("Enter alarm time", "VB Alarm"_, AlarmTime)If AlarmTime = "" Then Exit SubIf Not IsDate(AlarmTime) ThenMsgBox "The time you entered was not valid."Else' String returned from InputBox is a valid time, AlarmTime = CDate(AlarmTime)'so store it as a date/time value in AlarmTime.End If

End Sub

Private Sub Form_Load() AlarmTime = ""End Sub

Private Sub Form_Resize() If WindowState = conMinimized Then

'If form is minimized, display the time in a caption. SetCaptionTime

Else Caption = "Alarm Clock"

End IfEnd Sub

Private Sub SetCaptionTime() Caption = Format(Time, "Medium Time")

' Display time using medium time format.End Sub

Private Sub Timer1_Timer()Static AlarmSounded As Integer If lblTime.Caption <> CStr(Time) Then

Page 130: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

118 V0.1

' It's now a different second than the one displayed. If Time >= AlarmTime And Not AlarmSounded Then Beep MsgBox "Alarm at " & Time AlarmSounded = True ElseIf Time < AlarmTime Then AlarmSounded = False End If If WindowState = conMinimized Then

' If minimized, then update the form's Caption every ‘minute.If Minute(CDate(Caption)) <> Minute(Time) Then SetCaptionTime Else ' Otherwise, update the label Caption in the form every ‘second.

lblTime.Caption = Time End If End If

End Sub

Page 131: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 119

Exercise 32Line Drawing Software

A form should be displayed which should have an option Draw having 2 sub-options - Line andExit. When the user selects Line sub-option and then clicks the mouse anywhere on the frame,then a line should be drawn from the top left of the frame to the point where clicked. Clicking at

any next point will draw a line (joining the previous point and the next point) and so on.

Solution 32

Observe the coding:

Option Explicit

Dim flag, stflag

Private Sub exit_Click()EndEnd Sub

Private Sub Form_MouseDown(Button As Integer, Shift_ As Integer, X As Single, Y As Single)If flag = 1 Then

Line -(X, Y)Circle (X, Y), 50

End IfEnd Sub

Private Sub line_Click()flag = 1

End Sub

Page 132: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

120 V0.1

Exercise 33More on List Boxes

A frame should show a DriveListBox, a DirectoryListBox, a FileListBox and a ImageBox. The usercan select any valid drive, directory and choose any file shown in the file list box. (The filesshown will be of .txt, *.exe or .hlp types). The user can then choose any file from the list box and

drag and drop it in the image box. This will result in either execution of the .exe file, or runningthe .hlp file or displaying the txt file.

Solution 33:

Observe the coding:

Private Sub Dir1_Change() File1.Path = Dir1.PathEnd Sub

Private Sub Drive1_Change()On Error GoTo DriveErrs Dir1.Path = Drive1.Drive

Exit Sub

DriveErrs:

Select Case Err Case 68 MsgBox prompt:="Drive not ready. Please insert disk in drive.", _ buttons:=vbExclamation ' Reset path to previous drive. Drive1.Drive = Dir1.Path Exit Sub Case Else MsgBox prompt:="Application error.", buttons:=vbExclamation End Select

End Sub

Private Sub File1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y AsSingle) File1.DragIcon = Drive1.DragIcon File1.DragEnd Sub

Private Sub Form_Load() ' frmDrag.Width = 6525 ' frmDrag.Height = 3075

End Sub

Page 133: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 121

Private Sub Image1_DragDrop(Source As Control, X As Single, Y As Single)' Get the last three letters of the dragged filename. temp = Right$(File1.filename, 3)

' If dragged file is in the root, append filename. If Mid$(File1.Path, Len(File1.Path)) = "\" Then dropfile = File1.Path & File1.filename ' If dragged file is not in root, append "\" and filename. Else dropfile = File1.Path & "\" & File1.filename End If

Image1.Picture = LoadPicture("") Select Case UCase$(Trim$(temp)) Case "TXT" X = Shell("Notepad " + dropfile, 1) Case "BMP" Image1.Picture = LoadPicture(dropfile) Case "EXE" X = Shell(dropfile, 1) Case "HLP" X = Shell("WinHelp " + dropfile, 1) Case Else msg = "Try one of these file types:" msg = vbCrLf & msg & vbCrLf & vbCrLf & " .txt, .bmp, .exe,.hlp" MsgBox msg End Select

End Sub

Private Sub Image1_DragOver(Source As Control, X As Single, Y As Single, State AsInteger) Select Case State

Case 0 ' Display a new icon when the source enters the drop area. File1.DragIcon = Dir1.DragIcon Case 1

‘Display the original DragIcon when the source leaves the ‘drop area. File1.DragIcon = Drive1.DragIcon

End Select

' Note that Dir1.DragIcon and Drive1.DragIcon have been' set at design time. This allows you to load the "Enter"' and "Leave" icons for File1 at run time without requiring' that the user has those icons on disk.End Sub

Option ExplicitDim h, w, t, l, h1, flag, flag1 As Integer

Private Sub Form_Load()Dim h1h = Form1.Heightw = Form1.Widthl = Form1.Leftt = Form1.Toph1 = h

Page 134: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

122 V0.1

flag = 1flag1 = 1

End Sub

Private Sub Timer1_Timer()'Label1.Caption = "s.t " & s.Top & " hei " & ScaleHeightIf flag = 1 And s(0).Top <> 0 Then

s(0).Top = s(0).Top - 1

Elseflag = 0

If flag = 0 And s(0).Top + s(0).Height <> ScaleHeight Thens(0).Top = s(0).Top + 1Elseflag = 1End IfEnd If

If flag1 = 1 And s(1).Left <> 0 Thens(1).Left = s(1).Left - 3

Elseflag1 = 0

If flag1 = 0 And s(1).Left + s(1).Width < ScaleWidth Thens(1).Left = s(1).Left + 3

Elseflag1 = 1

End IfEnd If

End Sub

Page 135: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 123

Exercise 34A Calculator program

Solution 34

Option ExplicitDim Op1, Op2 ' Previously input operand.Dim DecimalFlag As Integer ' Decimal point present yet?Dim NumOps As Integer ' Number of operands.Dim LastInput ' Indicate type of last keypress event.Dim OpFlag ' Indicate pending operation.Dim TempReadout

' Click event procedure for C (cancel) key.' Reset the display and initializes variables.

Private Sub Cancel_Click() Readout = Format(0, "0.") Op1 = 0 Op2 = 0 Form_LoadEnd Sub

' Click event procedure for CE (cancel entry) key.Private Sub CancelEntry_Click() Readout = Format(0, "0.") DecimalFlag = False LastInput = "CE"End Sub

' Click event procedure for decimal point (.) key.

' If last keypress was an operator, initialize' readout to "0." Otherwise, append a decimal' point to the display.

Private Sub Decimal_Click() If LastInput = "NEG" Then

Readout = Format(0, "-0.") ElseIf LastInput <> "NUMS" Then

Readout = Format(0, "0.") End If

DecimalFlag = True LastInput = "NUMS"End Sub

Page 136: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

124 V0.1

' Initialization routine for the form.' Set all variables to initial values.

Private Sub Form_Load() DecimalFlag = False NumOps = 0 LastInput = "NONE" OpFlag = " " Readout = Format(0, "0.") 'Decimal.Caption = Format(0, ".")End Sub

' Click event procedure for number keys (0-9).' Append new number to the number in the display.

Private Sub Number_Click(Index As Integer)

If LastInput <> "NUMS" Then Readout = Format(0, ".") DecimalFlag = False End If

If DecimalFlag Then Readout = Readout + Number(Index).Caption Else

Readout = Left(Readout, InStr(Readout, Format(0, ".")) - 1) +Number(Index).Caption + Format(0, ".")

End If If LastInput = "NEG" Then Readout = "-" & Readout LastInput = "NUMS"End Sub

' Click event procedure for operator keys (+, -, x, /, =).' If the immediately preceeding keypress was part of a' number, increments NumOps. If one operand is present,' set Op1. If two are present, set Op1 equal to the' result of the operation on Op1 and the current' input string, and display the result.

Private Sub Operator_Click(Index As Integer) TempReadout = Readout If LastInput = "NUMS" Then NumOps = NumOps + 1End If

Select Case NumOps Case 0 If Operator(Index).Caption = "-" And LastInput <> "NEG" Then

Readout = "-" & Readout LastInput = "NEG"

End If Case 1 Op1 = Readout If Operator(Index).Caption = "-" And LastInput <> "NUMS"_ And OpFlag <>

"=" Then Readout = "-" LastInput = "NEG" End If

Page 137: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 125

Case 2 Op2 = TempReadout Select Case OpFlag Case "+" Op1 = CDbl(Op1) + CDbl(Op2) Case "-" Op1 = CDbl(Op1) - CDbl(Op2)

Case "X" Op1 = CDbl(Op1) * CDbl(Op2) Case "/"

If Op2 = 0 Then MsgBox "Can't divide by zero", 48, "Calculator" Else Op1 = CDbl(Op1) / CDbl(Op2) End If Case "=" Op1 = CDbl(Op2) Case "%" Op1 = CDbl(Op1) * CDbl(Op2) End Select Readout = Op1 NumOps = 1 End Select

If LastInput <> "NEG" Then LastInput = "OPS" OpFlag = Operator(Index).Caption End If

End Sub

' Click event procedure for percent key (%).' Compute and display a percentage of the first operand.

Private Sub Percent_Click() Readout = Readout / 100 LastInput = "Ops" OpFlag = "%" NumOps = NumOps + 1 DecimalFlag = True

End Sub

Page 138: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

126 V0.1

Exercise 35Searching

The form should show (a) A text box to enter the search criteria (b) a drive list box (c) a directorylist box (d) file list box (e) Search command button and (f) exit button. The user can enter the filesearch criteria in the search text box. Clicking on 'Search' command button will display all the

files (matching the search condition) in the file list box.

Solution 35:

Option ExplicitDim SearchFlag As Integer ' Used as flag for cancel and other operations.

Private Sub cmdExit_Click() If cmdExit.Caption = "E&xit" Then End Else ' If user chose Cancel, just end Search. SearchFlag = False End IfEnd Sub

Private Sub cmdSearch_Click()' Initialize for search, then perform recursive search.

Dim FirstPath As String, DirCount As Integer, NumFiles As IntegerDim result As Integer ' Check what the user did last. If cmdSearch.Caption = "&Reset" Then ' If just a reset,‘ initialize and exit.

ResetSearch txtSearchSpec.SetFocus Exit Sub End If

' Update dirList.Path if it is different from the currently ' selected directory, otherwise perform the search. If dirList.Path <> dirList.List(dirList.ListIndex) Then dirList.Path = dirList.List(dirList.ListIndex) Exit Sub ' Exit so user can take a look before searching. End If

' Continue with the search. Picture2.Move 0, 0 Picture1.Visible = False Picture2.Visible = True

cmdExit.Caption = "Cancel"

filList.Pattern = txtSearchSpec.Text FirstPath = dirList.Path

Page 139: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 127

DirCount = dirList.ListCount

' Start recursive direcory search. NumFiles = 0 ' Reset found files indicator. result = DirDiver(FirstPath, DirCount, "") filList.Path = dirList.Path cmdSearch.Caption = "&Reset" cmdSearch.SetFocus cmdExit.Caption = "E&xit"

End Sub

Private Function DirDiver(NewPath As String, DirCount As Integer _, BackUp As String) As Integer' Recursively search directories from NewPath down...' NewPath is searched on this recursion.' BackUp is origin of this recursion.' DirCount is number of subdirectories in this directory.Static FirstErr As IntegerDim DirsToPeek As Integer, AbandonSearch As Integer, ind As IntegerDim OldPath As String, ThePath As String, entry As StringDim retval As IntegerSearchFlag = True ' Set flag so the user can interrupt.DirDiver = False ' Set to True if there is an error.retval = DoEvents() ' Check for events (for instance, if the user ‘chooses Cancel). If SearchFlag = False Then DirDiver = True Exit Function End If On Local Error GoTo DirDriverHandler

DirsToPeek = dirList.ListCount ' How many directories ‘below this? Do While DirsToPeek > 0 And SearchFlag = True

OldPath = dirList.Path ' Save old path for next recursion.dirList.Path = NewPathIf dirList.ListCount > 0 Then

' Get to the node bottom. dirList.Path = dirList.List(DirsToPeek - 1) AbandonSearch= DirDiver((dirList.Path), DirCount%, OldPath) End If

' Go up one level in directories. DirsToPeek = DirsToPeek - 1

If AbandonSearch = True Then Exit Function Loop ' Call function to enumerate files. If filList.ListCount Then

If Len(dirList.Path) <= 3 Then ' Check for 2 bytes/character ThePath = dirList.Path ' If at root level, leave as is... Else

ThePath = dirList.Path + "\"' Otherwise put "\" ‘before the filename.

End IfFor ind = 0 To filList.ListCount - 1' Add conforming files in this directory to the list box.

entry = ThePath + filList.List(ind) lstFoundFiles.AddItem entry lblCount.Caption = Str(Val(lblCount.Caption) + 1)

Page 140: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

128 V0.1

Next ind End If

If BackUp <> "" Then ' If there is a superior directory, move it. dirList.Path = BackUp End If Exit Function

DirDriverHandler:If Err = 7 Then' If Out of Memory error occurs, assume the list box just got full.

DirDiver = True ' Create Msg and set return value AbandonSearch. MsgBox "You've filled the list box. Abandoning search..." Exit Function' Note that the exit procedure resets Err to 0.Else ' Otherwise display error message and quit. MsgBox ErrorEndEnd IfEnd Function

Private Sub DirList_Change() ' Update the file list box to synchronize with the directory list box. filList.Path = dirList.Path

End Sub

Private Sub DirList_LostFocus() dirList.Path = dirList.List(dirList.ListIndex)End Sub

Private Sub DrvList_Change() On Error GoTo DriveHandler dirList.Path = drvList.Drive Exit Sub

DriveHandler: drvList.Drive = dirList.Path Exit SubEnd Sub

Private Sub Form_Load() Picture2.Move 0, 0 Picture2.Width = WinSeek.ScaleWidth Picture2.BackColor = WinSeek.BackColor lblCount.BackColor = WinSeek.BackColor lblCriteria.BackColor = WinSeek.BackColor lblfound.BackColor = WinSeek.BackColor Picture1.Move 0, 0 Picture1.Width = WinSeek.ScaleWidth Picture1.BackColor = WinSeek.BackColorEnd Sub

Private Sub Form_Unload(Cancel As Integer) EndEnd Sub

Private Sub ResetSearch() ' Reinitialize before starting a new search.

Page 141: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Basic Practice Exercises

V0.1 129

lstFoundFiles.Clear lblCount.Caption = 0 SearchFlag = False ' Flag indicating search in progress. Picture2.Visible = False cmdSearch.Caption = "&Search" cmdExit.Caption = "E&xit" Picture1.Visible = True dirList.Path = CurDir: drvList.Drive = dirList.Path ' Reset the path.End Sub

Private Sub txtSearchSpec_Change() ' Update file list box if user changes pattern. filList.Pattern = txtSearchSpec.TextEnd Sub

Private Sub txtSearchSpec_GotFocus() txtSearchSpec.SelStart = 0 ' Highlight the current entry. txtSearchSpec.SelLength = Len(txtSearchSpec.Text)End Sub

Page 142: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Basic Practice Exercises MS Visual Basic 6 Programming Introduction

130 V0.1

Notes

Page 143: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

V0.1 131

Multiple Document Interface (MDI)

Objectives

In this Chapter, you will learn about MDI (Multiple DocumentInterface).

• Multiple-Document Interface (MDI) Applications

• Using MDI in Visual Basic

• Set the Properties

• Create a Menu

• Coding

Multiple-Document Interface (MDI) Applications

The Multiple-Document Interface lets the user create an application that maintains multipleforms within a single container form. Applications such as Word and Excel have MDI's.

In this type of application the user can display multiple documents at the same time, each being

in its own window. These document windows are contained in a parent window which providesthe workspace.

Page 144: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Multi Document Interface (MDI) MS Visual Basic 6 Programming Introduction

132 V0.1

Using MDI in Visual Basic

You can have only one MDI form in a Visual Basic application and it holds all the child forms of

the application. The child form is an ordinary form which has the MDIChild property set to Trueand you can have many child forms in the parent form.

At run time the child form(s) are displayed inside the MDI form and if minimised the icon will

still appear inside the form.

MDI's can also use dialog boxes as normal, these can be used in any application.

• Select Insert, MDI Form to create an MDI form

• Create a new form and set the MDIChild property to true to create a child form

At design time the forms are not restricted to the area within the parent and can bemanipulated like any normal form. Only at run time will they be restricted to the parent MDIform.

• Create a text box on the child form

Set the Properties

• Set the properties for the forms as follows:

Object Property Setting

MDIForm1 Caption MDI Text Writer

Form1 Caption Untitled

MDIChild True

Text1 Multiline True

Text Empty

Left 0

Top 0

Page 145: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Multi Document Interface (MDI)

V0.1 133

Create a Menu

• Create a menu as follows:

Caption Name Indented

&File MenFile No

&New MiFileNew Yes

Coding

• Now add the following code to miFileNew_Click:

Sub miFileNew_Click()Dim NewDoc As New Form1 'Create a new instance of Form1NewDoc.Show 'Display the new form

End Sub

Add the following to Form_Resize for Form1

Sun Form_Resize()Text1.Height = ScaleHeight 'Expand box to fill area.Text1.Width = ScaleWidth

End Sub

• Run the program and open a new document

• Stop the program and in the Declarations section enter the following:

Dim boolDirty As Boolean

• Add this sub routine to note when text has been changed:

Sub Text1_Change()boolDirty = True

End Sub

• When you save the form you set it back to false -assuming you have this menu choice:

Sub menFileSave()FileSaveboolDirty = False

End Sub

Page 146: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Multi Document Interface (MDI) MS Visual Basic 6 Programming Introduction

134 V0.1

Notes

Page 147: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

V0.1 135

Visual Data Manager - WorkedExample

Objectives

In this Chapter, you will learn about Visual Data Manager.

• The Data Manager Program

• Create a Database

• A Database with a One to Many Link

• Set the Key Fields

• Set the Relationship

The Data Manager Program.

You may have the Data Manager program installed with Visual Basic. This program allows youto create a database without writing the code.

After you start the program you click on the File menu and select New database. After naming ityou then create a table for each set of data. For each table you give the field names, declare thedata types and size (if text). If required you can create primary keys and set relationships.

Field Types.

The field types allowed in the Data Manager program are:

Boolean, Byte, Integer, Long Integer, Currency, Single, Double, Date/Time, Long Binary, Textand Memo.

Page 148: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Data Manager - Worked Example MS Visual Basic 6 Programming Introduction

136 V0.1

Create a Database

• Start running the data manager (Add-ins, Data Manager).

• From File menu, select New Database

• Enter Address2 as the name of the database and click OK

• In the window click on the New button to create the first new table

• Enter Addresses as the table name

• Enter Title as the fieldname, Text as the type, 4 as the size and click on the [>] button toadd the field

• Repeat for Firstname, Lastname and other fields in your address book and click OK

You can now use this database with the Data control and Visual Basic forms etc.

A Database with a One to Many Link

• Create the Database

• Select Add-Ins, Database Manager from the menus

• Select File, New Database and enter Jobs2 as the name

• Click on the OK button

• Create the Tables

• Click on the New Button

• Enter Personnel as the table name

• Enter the following Field Names, Types and Sizes:

Field Name Type Size

NINo Text 13

FirstName Text 25

LastName Text 25

• Click on the OK button

• Repeat for a Skills Table with the fields NINo, as above, and Skill - Text - 25

Page 149: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Visual Data Manager - Worked Example

V0.1 137

Set the Key Fields

To enable us to have One to Many linking we must have a key field in the Personnel tabl. Toensure the linking works properly we will also have the NINo and Skill fields in the Skills tableas key fields.

• Select the Personnel table and click on the Design button

• Click on the Indexes button and then on Add

• Type ni# in the Index Name box

• Click on NINo in the Fields in Table box

• Select Primary Index and Unique and click on the ADD(ASC) button

• Click on the OK button then Close the Indexes Box and the Table Editor

• Select the Skills table and click on the Design button

• Click on the Indexes button and then on Add

• Type nino in the Index Name box

• Click on NINo in the Fields in Table box

• Click on the ADD(ASC) button and click on the OK button

• Click on the Add button again

• Type skl in the Index Name box

• Click on Skill in the Fields in Table box

• Click on the ADD(ASC) button and click on the OK button

• Close the Indexes Box and the Table Editor

Set the Relationship

• Select the Personnel table and click on the Relations button

• The Primary Table should be Personnel, set the Related Table to Skills

• Select the Many radio button and select Enforce Referential Integrity

• Click on the OK button then click on the Close button

Page 150: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Visual Data Manager - Worked Example MS Visual Basic 6 Programming Introduction

138 V0.1

Notes

Page 151: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

V0.1 139

Database Development in VB

Objectives

In this Chapter, you will learn about Data Base Programming in VB:

• DAO - Data Access Objects

• Attaching or opening a Table Directly

• Working with Data Files

• Defining an ODBCDirect Workspace

• Creating or Setting the Default Workspace

• Connection Declaration

• Constant

• Retrieving Remote Data

• OpenRecordset Method with ODBCDirect

• Defining Validation Rules

• Rule Properties

• ValidationRule and Rule Violation Errors

• Referential Integrity

• Defining Referential Integrity Constraints

• Cascade Updates and Deletes

• Handling Referential Integrity Violations

• Transactions and Transaction Methods

• Multiple-User Issues

• Microsoft Jet Database Engine Locking

• Pessimistic Vrs. Optimistic Locking

• Unlocking

• Handling Errors on Update

• Accessing External Data

• Performance Issues

• Attaching SQL tables

Page 152: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Database Development in VB MS Visual Basic 6 Programming Introduction

140 V0.1

Data Access Programming Models

Visual Basic is also addressed as an RDE (Rapid Development Environment), because it offers

various Data Access programming models.

They include :

♦ DAO - Data Access Objects

♦ RDO - Remote Data Objects

♦ ADO - Active Data Objects

DAO - Data Access Objects

A Databases collection, contains all Database objects opened or created in a Workspace object. AWorkspace object defines a named session for a user. It contains open databases and providesmechanisms for simultaneous transactions.

Page 153: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Database Development in VB

V0.1 141

DBEngine The DBEngine object is the top level object inthe DAO object model.

Workspaces A Workspaces collection contains all active,unhidden Workspace objects of the DBEngineobject.

Workspace A Workspace object defines a named sessionfor a user.

Connections A Connections collection contains the currentConnection objects of a Workspace object.

Databases A Databases collection contains all openDatabase objects opened or created in aWorkspace object.

Groups A Groups collection contains all stored Groupobjects of a Workspace or user account(Microsoft Jet workspaces only).

Users A Users collection contains all stored Userobjects of a Workspace or Group object.(Microsoft Jet workspaces only).

Page 154: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Database Development in VB MS Visual Basic 6 Programming Introduction

142 V0.1

RDO - Remote Data Objects

Remote Data objects and collections provide a framework for using code to create and

manipulate components of a remote ODBC database system. Objects and collections haveproperties that describe the characteristics of database components and methods that you use tomanipulate them. Using the containment framework, you create relationships among objects and

collections, and these relationships represent the logical structure of your database system.

rdoEngine - The rdoEngine object represents the remote data source. As the top-level object, itcontains all other objects in the hierarchy of Remote Data Objects (RDO).

rdoEnvironment - An rdoEnvironment object defines a logical set of connections andtransaction scope for a particular user name

rdoconnection - An rdoConnection object represents an open connection to a remote data source

and a specific database on that data source, or an allocated but as yet unconnected object, whichcan be used to subsequently establish a connection.

rdoQuery - The rdoQuery object is used to manage SQL queries requiring the use of input,

output or input/output parameters.

rdocolumn - An rdoColumn object represents a column of data with a common data type and acommon set of properties.

rdoParameter - An rdoParameter object represents a parameter associated with an rdoQueryobject.

rdoresultset - An rdoResultset object represents the rows that result from running a query

rdotable - An rdoTable object represents the stored definition of a base table or an SQL view.

rdopreparedstatement - An rdoPreparedStatement object is a prepared query definition.

Page 155: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Database Development in VB

V0.1 143

ADO - ActiveX Data Objects

The new Data Access Programming model in Visual Basic 6.0 is the ADO.

The bridge between the data providers and data consumers is through data sources created usingMicrosoft ActiveX Data Objects (ADO), which is the primary method in Visual Basic to accessdata in any data source, both relational and non-relational.

The ActiveX Data Objects, consists of seven independent objects.

Connection Object - Represents a unique session with a data source.

Recordset Object - Represents records from a data provider like altering the records in a table.

Field Object - Represent an individual field in a recordset.

Command Object - Represents a command. For example to execute a stored procedure or aparameterized query.

Parameter Object - Represents an individual parameter in a stored procedure or aparameterized query.

Property Object - Represents data - provider - specific properties.

Error Object - Represents ADO Errors.

Data Access Choices

We can access data in an external database by attaching the external database or by opening itdirectly.

Attaching a Table to Microsoft Jet Database

When an external database is attached to a Microsoft Jet database, the table's data remains in theexternal database. However, the connection information and table definition are stored in the

Microsoft Jet database. We see the table as we would any other Microsoft Jet database table,except that we cannot create a table-type recordset in an attached table. We can use MicrosoftAccess to easily attach a table to a Microsoft Jet Database. We can also attach a table using a VB

program.

Page 156: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Database Development in VB MS Visual Basic 6 Programming Introduction

144 V0.1

Opening a Table Directly

When we open an external table directly, we specify the connection information by using the

arguments of the OpenDatabase method or the Connect property of the Data control.

Sub OpenTable()

Dim wspcurrent As WorkspaceDim dbCurrent As DatabaseDim rstProducts As Recordset

Set wspcurrent = CreateWorkspace("New WorkSpace", "Admin"," ",dbUseJet)Set dbcurrent=opendatabase ("C:\Programfiles\DevStudio\VB\Nwind.mdb")Set rstproducts =dbcurrent.OpenRecsordset ("products", dbopentable)

Accessing ISAM Databases

To open an ISAM dastabase directly, set the Database argument of the Opendatabase method (orthe DatabaseName property of the Data control) to the folder name that contains the ISAMtables. If our network supports it, we can use a network path for the database name

Set the Connect property of the Database object or Data control to the type of database to beopened. The following code opens a Microsoft Visual Foxpro database directly

Public Sub OpenFoxProTable() Dim dbFox As Database Dim recAccounts As Recordset Set dbFox = OpenDatabase ("\\Foxpro\Data\AP",False,False,"Foxpro 5.0") Set recAccounts = dbFox.Openrecordset("Accounts")End Sub

To attach an ISAM database to an existing .mdb database, we must create a new TableDef objectand set the connect and SourceTablename properties of the TableDef object.

The following code attaches a Visual Foxpro table to a Microsoft Jet database. We can create anew Microsoft Jet database or use an existing one.

Dim tbdAttach as TableDef

Set mydb = OpenDatabase ("Mydb.mdb")Set tbdAttach = dbMydb.CreateTableDef ("Attached Foxpro Table")tbdAttach.Connect = "Foxpro 5.0;Database = \\Foxpro\AP"tbdAttach.SourceTableName = "Accounts"dbMydb.TableDefs.Append tbdAttach

Page 157: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Database Development in VB

V0.1 145

Once we have attached the table to a Microsoft jet database, we can open it by using the

following code.

Set Mydb = OpenDatabase ("Mydb.mdb")SetrecAttach = mydb.OpenRecordset ("Attached Foxpro Table")

Distributing the Executables

When we distribute an application that accesses an ISAM database, we must provide theappropriate ISAM drivers to the user.

Working with Data Files

We can create VB applications that work with information from standard data files rather than

with a database.

When we work with information from standard data files, we can use some of the followingoptions:

* File I/O statements

We can use standard file access statements in VB to read and write files.

* Manually import data into a database

We can use Microsoft Access to manually import a text file into a database. Microsoft Accesssupports various file formats such as fixed-length, comma-delimited, and so on.

* Programmatically import into a database

We can create a program to read a text file and add the data to a database

Private Sub Command2_Click()

Dim fhandle As Integerfhandle = Freefile()open "newcust.txt" for Input As handleDo'Read file using some input statementsLoop until EOF (fhandle)End Sub

Page 158: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Database Development in VB MS Visual Basic 6 Programming Introduction

146 V0.1

Accessing ODBC Databases

DAO version 3.5 introduces a new client/server connection technology named Open Database

Connectivity Direct (ODBCDirect). This technology establishes a connection directly to an ODBCdata source, without loading the Microsoft Jet database engine.

Defining an ODBCDirect Workspace

The technology of ODBCDirect enables us to access ODBC data sources directly by using dataaccess objects (DAO). We can use the features of this client/server connection to access adatabase quickly without loading the Microsoft jet database engine.

The first step in using ODBCDirect is to define the type of workspace we will use. We can do thisin one of two ways: by setting the default workspace type, or by defining a specific workspacetype as ODBCDirect.

Setting the Default Workspace

To set the default workspace type as ODBCDirect, we use the DefaultType property of theDBEngine object. This workspace type will then be used whenever a Workspace object is created.To define a specific workspace type as ODBCDirect, we set the DefaultType property todbUseODBC.

The following code sets the default workspace type to ODBCDirect

DBEngine.Defaulttype = dbUseODBC

Creating a Specific Workspace

We can override the default workspace setting for a specific workspace by using the typeargument of the CreateWorkspace method.

The following code creates an ODBCDirect workspace

Dim wspODBC As WorkspaceSet wspODBC=DBEngine.CreateWorkspace_ ("NewODBCWorkspace","Admin", &_ " ", dbUseODBC)

Page 159: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Database Development in VB

V0.1 147

Connecting to a Remote Data Source

Connecting to a remote data source is similar to opening a Microsoft Jet database. First we create

a workspace (such as an ODBCDirect), and then we open the data source.

To open a remote data source, we create a Connection object, just as we would create a Databaseobject to open a Microsoft Jet database. Once a connection has been created, we can retrieve data

from the remote data source.

Connection Declaration

The connection object variable refers to our connection. Use the Set statement to open theconnection. The following code opens a connection in the default workspace.

Dim conNewConnection As Connectionset conNewConnection = OpenConnection ("New", dbDriverPrompt, false, _

"ODBC; Database=pubs;UID=sa;PWD=;DSN=SQLSERVER")

OpenConnection Method

The following table lists the arguments to the OpenConnection method, and describes their use

Argument Description

Name Any string, if we specify a registered ODBC datasource name (DSN) is not included in theOpenConnection declaration, the name must refertok a valid ODBC DSN, which will also be the Nameproperty.

Options Sets various options for the connection

Readonly True or False. If True, no modifications are allowed.The default value is false

Connect An ODBC connection string

The options argument determines if and when to prompt the user to establish the connection,and whether or not to open the connection asynchronously.

You can use one of the following constants.

Page 160: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Database Development in VB MS Visual Basic 6 Programming Introduction

148 V0.1

Constant DescriptionDbDriverNoPrompt The ODBC Driver Manager uses the connection string

provided in dbname and connect. If you don'tprovide sufficient information, a run-time error occurs.

DbDriverPrompt The ODBC Driver Manager displays the ODBC DataSources dialog box, which displays any relevantinformation supplied in dbname or connect. Theconnection string is made up of the DSN that the userselects via the dialog boxes, or, if the user doesn'tspecify a DSN, the default DSN is used.

DbDriverComplete Default. If the connect argument includes all thenecessary information to complete a connection,the ODBC Driver Manager uses the string in connect.Otherwise it behaves as it does when you specifydbDriverPrompt.

DbDriverCompleteRequired This option behaves like dbDriverComplete exceptthe ODBC driver disables the prompts for anyinformation not required to complete theconnection.

DbRunAsync Execute the method asynchronously. This constantmay be used with any of the other options constants.

Retrieving Remote Data

Retrieving remote data by using ODBCDirect is very similar to retrieving data from a MicrosoftJet database. Once you establish a connection to an ODBC compliant database with ODBCDirect,we create a Recordset object by using the OpenRecordset method, just as we do when we retrieve

from a Microsoft Jet database.

OpenRecordset Method with ODBCDirect

In addition to the options available with the OpenRecordset method for a Database object, theOpenRecordset method for a Connection object enables you to retrieve records form a database.

The following arguments of the OpenRecordset method are available when using an ODBCDirectworkspace.

type* dbOpenDynamic

Opens the dynamic-type recordset that we can use to add, change or delete records from anunderlying database table or tables. A dynamic cursor can contain fields from one or more tablesin a database

optionsdbRunAsyncRuns an asynchronous queryDbExecDirect

Page 161: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Database Development in VB

V0.1 149

Runs a query by skipping SQLPrepare and calling SQLExecDirectdirectly. Use this option only when we are not opening a recordsetbased on a parameter query.

lockeditsdboptimisticValueUses optimistic concurrency based on row values.dbOptimisticBatchEnables batch optimistic updating

Page 162: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Database Development in VB MS Visual Basic 6 Programming Introduction

150 V0.1

Data Integrity

With MS Access, we can create rules and establish referential integrity constraints in a database

to help ensure data integrity. If we violate these constraints, we will receive a runtime error. Weshould provide code that traps these errors, and enables the user to correct the data and continue.

We need to define

♦ Validation Rules

♦ Referential Integrity

♦ Transactions

Defining Validation Rules

When using a Microsoft Jet Database, we can define rules that specify which data is valid for afield or a table. These rules are stored with the database, and are enforced no matter how wemodify the data.

Rule Properties

With VB we can create or view the rules of a database. The Field and Recordset objects have twoproperties that relate to rules. The following properties are supported only in Microsoft Jetdatabases.

ValidationRule

Defines the criteria for the rule.

Validation Text

Provides an error message that can be displayed if the rules are violated.

For example

Sub DisplayRule()Set rstorders = dbMydb.OpenRecordset("Order Details")Debug.Print rstorders ("Quantity").ValidationRule

Debug.Print rstorders ("Quantity").ValidationTextEnd Sub

Page 163: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Database Development in VB

V0.1 151

Rule Violation Errors

If we violate a rule when updating a record, a runtime error will occur. The ValidateOnSet

property determines when the rule violation error occurs.

If ValidateOnSet is True, a runtime error will occur when the field is set, as shown in thefollowing code.

recorders("Quantity").ValidateOnset = Truerecorders("Quantity").Value = 0recorders.Update

If ValidateOnSet is False, a runtime error will occur then the Update method is executed, asshown in the following code.

recoders("quantity").ValidateOnSet = Falserecorders("quantity").Value = 0recorders.Update

Handling Rule Violations

Generally, if a rule violation occurs, we want to allow the user to correct the data and attempt theupdate again. If we are using the Data control and we violate a rule, the Error event occurs. TheData control displays the Validation Text property and cancels the update. The user can modify

the data and click the Data control to attempt the update again.

We can add code to the Error event to take a different action when the error occurs. For example,we might display text in a caption rather than in a message box, or change the Forecolor property

of the fields to indicate that an error has occurred.

If we are using data access objects (DAO) and violate a rule, we will receive a runtime error. Weshould trap for this error and inform the user.

Private Sub cmdUpdate_Click()On Error GoTo update_errrs.Editrs("order id") = txtorder.Textrs.UpdateExit Sub

update_err :

Page 164: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Database Development in VB MS Visual Basic 6 Programming Introduction

152 V0.1

If Err.Number = 3316 ThenlblError.Caption = Err.Descriptionrs.CancelUpdateExit Sub

End IfEnd Sub

The Description property of the Err object contains the value of the Validation Text property. We

can use the CancelUpdate method to cancel the current Edit or AddNew method, and to refreshthe current record. We can either leave the user's data on the form, or update the form with thecurrent data from the database.

Referential Integrity

Referential Integrity refers to the constraints that are placed on a database to preserve the defined

relationships between tables when records are added, changed or deleted.

Defining Referential Integrity Constraints

The Microsoft Jet database engine can enforce referential integrity in a Microsoft Jet Database.

Cascade Updates and Deletes

When we have established referential integrity, we can specify the options Cascade UpdateRelated Fields and Cascade Delete Related Records. If we set these options, Microsoft JetDatabase Engine will enable the user to change and delete records, and it will automaticallychange or delete related records in related tables.

Handling Referential Integrity Violations

If we try to violate referential integrity constraints, we will receive a runtime error. We shouldtrap this error and inform the user.

Private Sub cmdDelete_Click() On Error GoTo del_err

rs.Deleters.MoveNextFillFieldsExit Subdel_err :If Err.Number = 3200 Then

lblError.Caption = "Cannot Delete customer With Orders." Exit Sub

ElseEnd If

End Sub

Page 165: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Database Development in VB

V0.1 153

Preventing Referential Integrity Violations

To prevent referential integrity violations, we can provide a list box with valid entries. If the

valid entries are too long to store in a list box, we can enable the user to enter search criteria, andthen display a list of valid entries.

Transactions

A transaction is a series of changes made to a database. We can group several database changeswithin a transaction. If all operations are successful, we commit the transaction, if any of theoperations fail, we roll back the transaction.

Transaction Methods

The transaction methods apply to the workspace object. Use the BeginTrans method beforeupdating the first record. If any subsequent update fails, use the Rollback method to undo all ofthe updates. Use the CommitTrans method after you have successfully updated the last record.

Sub cmdAddOrder_Click()On Error GoTo Addorder_Err DBEngine.WorkSapces(0).BeginTransdb.Execute "Insert into Orders...", dbFailOnErrordb.Execute "Insert into Order Details...", dbFailOnErrorDBEngine.WorkSpaces(0).CommitTranslblStatus.Caption = "Updates complete"

Exit Sub

AddOrder_Err:lblStatus.Caption = Err.DescriptionMsgbox "Not all updates successful"DBEngine.Workspaces(0).RollbackExit Sub

End Sub

Using Transactions to Improve Performance

In addition to using transactions to maintain data integrity, we can also improve performance by

enclosing an SQL Update statement in a transaction. The operations in the transaction arebuffered, and are not written to disk until the transaction is committed.

Page 166: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Database Development in VB MS Visual Basic 6 Programming Introduction

154 V0.1

Multiple-User Issues

When we allow multiple users to access a database at the same time, the database application

becomes more complex. We need to handle several errors that can occur when multiple usersaccess data.

For example:

Two users try to edit the same data: The MicroSoft Jet Database engine automatically locks datato prevent two users from editing a record at the same time. If users try to update a lockedrecord, they will receive a run-time error.

A user changes a record that another user is viewing: If a user attempts to update a record, andthe data has been modified since the Edit method was executed, the Microsoft Jet database enginewill return an error.

A user deletes a record that another user is viewing: If a user attempts to access a record that hasbeen deleted, the Microsoft Jet Database engine will return an error.

Opening a Table for Exclusive Use: To avoid problems that can occur when we allow multiple

users to access a database, we can open a table for exclusive use. Opening a table in this wayprevents other users from using the table. Although this is a fairly restrictive solution, it may beappropriate for our situation.

The options argument to the OpenRecordset method determines how a recordset is opened.

The following code opens a table for exclusive use. We are allowed to modify the Orders table,but the user is not allowed to view or modify data in the table.

Set recorders = Mydb.OpenRecordset ("Orders", dbOpentable, dbDenyRead _+ dbDenyWrite)

The following code opens a table for exclusive write. We are allowed to view & modify theOrders table, but the user is not allowed to modify data in the table.

Set recorders = Mydb.OpenRecordset ("Orders", dbOpentable, dbDenyWrite)

The following code opens a recordset in readonly mode. We are allowed to read data from theOrders table, but the user is not allowed to modify data in the table.

Set recorders = Mydb.OpenRecordset ("Orders", dbOpentable, dbReadOnly)

If we intend only to add records to a table, we use the dbAppendOnly option for betterperformance. The dbDenyRead option is available only in table-type recordsets.

Page 167: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Database Development in VB

V0.1 155

Microsoft Jet Database Engine Locking

All database management systems provide some sort of locking mechanism to prevent two users

from updating data at the same time.

The Microsoft Jet database engine provides page-level locking. Pages are blocks of records thatare 2048 bytes in size. VB stores as many records as will fit on each page. When VB locks the

page containing a record you're editing, all the other records on that page will also be locked.

Pessimistic Vrs. Optimistic Locking

The value of the LockEdits property of the Recordset object determines when a lock is placed onthe records in a recordset.

Pessimistic Locking

If the LockEdits property is True, pessimistic locking is in effect. The page containing the currentrecord is locked as soon as we use the Edit method. The page is unlocked when we use theUpdate method.

The default locking strategy locks records for a longer period of time, but ensures that once theEdit method has been executed, another user cannot change the data.

Optimistic Locking

If the LockEdits property is False, optimistic locking is in effect. The page containing the recordis locked only while the record is being updated.

Locks are in place for a shorter period of time, and multiple users can use the Edit methodwithout locking the page. However, when we use optimistic locking, we will need to handlepossible errors when the user executes the Update method.

If we do not expect users to attempt to modify the same record very often, consider settingLockEdits to False.

Page 168: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Database Development in VB MS Visual Basic 6 Programming Introduction

156 V0.1

Unlocking

The Microsoft Jet database engine marks a page to be unlocked as soon as the update completes.

However, locks are not removed until other actions are complete.

We can use the idle method of the DBEngine object with the dbFreeLocks option to suspendprocessing and allow the Microsoft Jet database engine to release locks and catch up on other

background tasks, as shown in the following code.

DBEngine.Idle dbFreeLocks'Handling Errors On Edit

Private Sub cmdEdit_Click()On Error GoTo HandleErrorrs.EditButtonEditAddModeExit Sub

HandleError :Select Case Err.NumberCase 3260 'Page currently locked

Msgbox "Record is currently locked. Try Again later."Case 3197 'data has changed

Msgbox "Data has been changed and will be refreshed"rs.Bookmark = rs.Bookmark 'getupdated dataFillFieldsrs.Edit

Case ElseMsgbox Err.Number & ": " & Err.Description

End SelectEnd Sub

Notice that if the record is locked when the user executes the Edit method, a message will be

displayed. If the data has changed, the code refreshes the form with the latest data.

The statement recorders.Bookmark = recorders.bookmark refreshes the current record in therecordset with the latest data from the database.

Page 169: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Database Development in VB

V0.1 157

Handling Errors on Update

Private Sub cmdSave_Click()Dim answer As integerOn Error GoTo HnadleError

rs.Fields ("Category Name") = txtCategoryName.Textrs.Fields ("Description") = txtDescription.Textrs.Updaters.Bookmark = rs.LastModifiedFillFieldsButtonNavigateModeExit Sub

HandleError :Select Case Err.NumberCase 3260Msgbox "Record is currently locked"Case 3197answer = Msgbox ("Data has been changed by another user, & _ OverWrite", vbYesNo)

If answer = vbYes ThenResume

Elsers.Bookmark = rs.Bookmark 'refresh other users changescmdcancel_Click

End IfCase Else

Msgbox Err.Number & ":" & Err.DescriptionEnd Select

End Sub

Handling Errors on Records Deleted by Other Users

Once our dynaset-type recordset is fully populated, if another user deletes a record from thedatabase, the pointer to the entry will not be deleted from the dynaset.

However, the deleted record will no longer be in the database, We cannot view the record, and if

we attempt to access data in that record, an error will occur.

The easiest way to handle this error is to delete the entry that points to the deleted record fromthe dynaset.

Page 170: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Database Development in VB MS Visual Basic 6 Programming Introduction

158 V0.1

Accessing External Data

We can use VB to access several indexed sequential access method (ISAM) databases, such as

dBASE, Paradox and Microsoft Visual Foxpro.

VB provides drivers for various ISAM databases. These drivers are listed in the Registry. We canalso use VB to access standard data files, such as comma-delimited text files.

Performance Issues

An application's design significantly influences its performance. When creating databaseapplications, consider the following suggestions.

Know what we are asking for

Some SQL queries are more efficient than others. For example sorting on a field that contains anindex is faster than sorting on a field that does not contain an index.

Request only the data needed

Avoid dynaset type and snapshot type recordsets on an entire table. Our application designshould enable the user to enter criteria and return a limited recordset.

Rather than selecting all columns in a record, select only the necessary columns.

Use only the functionality required

If we do not need to update the database, open the database as read-only. This improvesperformance because the Microsoft Jet database engine does not need to keep track of locks

If we do not need to update a recordset, open it as read-only.

Use transactions

Using a transaction reduces disk access to about once per transaction, instead of once per record.This can significantly improve an application's performance. We may want to grouptransactions. If a transaction is too large, it uses memory that other operations my need.

Use stored queries

In general, it is better to create stored queries than it is to use SQL in text. A stored query isprecompiled, so we save compilation time at run time. In addition, it is often easier to maintainqueries that are stored in an .mdb file, rather than created throughout our application.

If possible, use stored queries or SQL for batch operations, such as updating a group of records,rather than updating records one at a time with the Update method.

Page 171: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Database Development in VB

V0.1 159

Attach SQL tables

Attach ODBC database tables to a local .mdb database. The data definition and connectioninformation is maintained with the .mdb file, and therefore improves performance.

Write own performance test.

There are many factors that affect the performance of an application. The best way to find out if afeature will improve performance is to try it with the data in our environment.

Page 172: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Database Development in VB MS Visual Basic 6 Programming Introduction

160 V0.1

Notes

Page 173: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

V0.1 161

Example Database Programs in VB

Objectives

In this Chapter, you will learn about Data Base Programming in VB byobserving some sample exercises.

• Using Data Access Objects

• Exploring ActiveX Data Bound Controls

• Programming with RDC and RDO

• Connecting to ODBC Data Source Using Data Control

• Creating a Data Entry Form

• Using DBCombo Control

• Using the Validate Event

• Creating and Navigating a Record Set

• Adding and Editing Records

• Finding Records

• Disabling Buttons during Exit

• Using a Parameter Query

• Handling Referential Integrity Violations

• Multi User Issues

• Using ODBC Direct

Page 174: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Example Database Programs in VB MS Visual Basic 6 Programming Introduction

162 V0.1

ExerciseUsing Data Access Objects (DAO)

Create a application using DAO to manage Employees table we created in Company.MDBdatabase. The application should have the following Controls.

♦ Insert, Edit, Delete records from the table,

♦ Save and Cancel transactions made by the user,

♦ Find specific record by suppling EmpNo

♦ Employee Number should be automatically generated, (First no should be 1001)

Solution:

Creating the form

1. Start a new Visual Basic project.

2. Add controls to the form, as shown in the following illustration.

Control Property Setting

Form Name frmEmp

' Caption Employees

TextBoxs Name txtFields( )

' Index [0 - 4]

' DataSource dtaEmp

'DataField [EmpNo, EmpName, Desig, DeptNo,Salary]

Commands Name cmdInsert, cmdEdit, cmdRemove,cmdSave,cmdCancel, cmdFind,cmdExit, cmdFirst,

cmdPrevious, cmdNext,cmdLast

Caption Insert, Edit, Remove, Save, Cancel, Find,Exit,First, Previous, Next, Last

Your Form should look like this at run time:

Page 175: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Example Database Programs in VB

V0.1 163

Writing Code

3. In the General Declarations of the form type the followings:

Option Explicit

Dim Ws As WorkspaceDim Db As DatabaseDim Rs As RecordsetDim i As IntegerDim t As StringDim c As ControlDim bk

Private Sub cmdCancel_Click() Rs.Bookmark = bk Call GiveData Call OnButtonsEnd Sub

Private Sub cmdDelete_Click() If Rs.RecordCount = 0 Then Beep Exit Sub End If If MsgBox("R U Sure to Delete ?", vbYesNo + vbQuestion) = vbYes_ Then Db.Execute ("DELETE FROM Employees WHERE EmpNo =" &_ txtFields(0) & ";") Rs.Requery Call GiveData End IfEnd Sub

Private Sub cmdEdit_Click() bk = Rs.Bookmark Call OffButtons t = "EditMode"

Page 176: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Example Database Programs in VB MS Visual Basic 6 Programming Introduction

164 V0.1

txtFields(1).SetFocusEnd Sub

Private Sub cmdExit_Click() Unload MeEnd Sub

Private Sub cmdFind_Click() i = InputBox("Enter Employee Number to Find :") Rs.FindFirst ("EmpNo = " & i) If Rs.NoMatch Then MsgBox "No Such Employee" Else Call GiveData End IfEnd Sub

Private Sub cmdFirst_Click() Rs.MoveFirst Call GiveDataEnd Sub

Private Sub cmdInsert_Click() If Not Rs.BOF And Not Rs.EOF Then bk = Rs.Bookmark Call ClearText txtFields(0) = Str(NewEmpNo()) txtFields(1).SetFocus Call OffButtons t = "InsertMode"End Sub

Private Sub OffButtons() For Each c In Controls If TypeOf c Is CommandButton Then c.Enabled = False End If Next cmdCancel.Enabled = True cmdSave.Enabled = TrueEnd Sub

Private Sub OnButtons() For Each c In Controls If TypeOf c Is CommandButton Then c.Enabled = True End If Next cmdCancel.Enabled = False cmdSave.Enabled = FalseEnd Sub

Private Function NewEmpNo() As Integer Dim rsENo As Recordset Set rsENo = Db.OpenRecordset("SELECT Max(EmpNo) FROM_ Employees", dbOpenDynaset) If IsNull(rsENo(0)) Then NewEmpNo = "1001"

Page 177: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Example Database Programs in VB

V0.1 165

Else NewEmpNo = Val(rsENo(0)) + 1 End IfEnd FunctionPrivate Sub ClearText() For i = 0 To 4 txtFields(i) = "" NextEnd Sub

Private Sub cmdLast_Click() Rs.MoveLast Call GiveDataEnd Sub

Private Sub cmdNext_Click() Rs.MoveNext If Rs.EOF Then Beep Rs.MoveLast End If Call GiveDataEnd Sub

Private Sub cmdPrevious_Click() Rs.MovePrevious If Rs.BOF Then Beep Rs.MoveFirst End If Call GiveDataEnd Sub

Private Sub cmdSave_Click() If t = "InsertMode" Then Db.Execute ("INSERT INTO Employees VALUES (" & txtFields(0) _ & ",'" & txtFields(1) & "','" & txtFields(2) & "', " _ & txtFields(3) & "," & txtFields(4) & ");") ElseIf t = "EditMode" Then Db.Execute ("UPDATE Employees SET EmpName ='" & txtFields(1)_ & "',Desig ='" & txtFields(2) & "',DeptNo = " & txtFields(3) _ & ", Salary =" & txtFields(4) & " WHERE EmpNo =" _ & txtFields(0) & ";") End If Rs.Requery t = Empty Call OnButtonsEnd Sub

Private Sub Form_Load() Set Ws = DBEngine.Workspaces(0) Set Db = Ws.OpenDatabase(App.Path & "\company.mdb") Call MakeRsEnd Sub

Private Sub GiveData() For i = 0 To 4

Page 178: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Example Database Programs in VB MS Visual Basic 6 Programming Introduction

166 V0.1

txtFields(i) = Rs(i) NextEnd Sub

Private Sub MakeRs() Set Rs = Nothing Set Rs = Db.OpenRecordset("SELECT * FROM Employees _ORDER BY EmpNo", dbOpenDynaset) If Rs.BOF And Rs.EOF Then Exit Sub Else Rs.MoveNext Rs.MoveFirst Call GiveData End IfEnd Sub

4. Save the Project and press F5 to run.

Page 179: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Example Database Programs in VB

V0.1 167

ExerciseExploring ActiveX Data-Bound Controls

Create a application using ActiveX Data-Bound Controls to view and query the Employees table.The application should provide the following operations:

♦ 1. A Query Window, where SQL Statements are typed.

♦ 2. A Grid where results of query will be displayed

Solution :

Creating the form

1. Start a new Visual Basic project.

2. Add controls to the form, as shown in the following illustration.

Control Property Setting

Form Name frmAtXData

'Caption Employees Query Builder

Data Name dtaEmp

‘Database (Select Employees.MDB Database)

DBGrid Name grdEmp

' DataSource dtaEmp

TextBoxs Name txtSQL

' MultiLine True

' ScrollBars Vertical

Your Form should look like this at run time:

Page 180: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Example Database Programs in VB MS Visual Basic 6 Programming Introduction

168 V0.1

Writing Code

3. In the General Declarations of the form type the followings:

Option Explicit

Private Sub txtSQL_KeyPress(KeyAscii As Integer) On Error Resume Next If KeyAscii = 13 Then dtaEmp.RecordSource = txtSQL dtaEmp.Refresh End IfEnd Sub

4. Save the Project and press F5 to run.

Page 181: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Example Database Programs in VB

V0.1 169

ExerciseProgramming with RDC and RDO

Using Remote Data Control create a Master / Details form for the Emp, Dept tables of Oraclewhich are available in Scott, Tiger Login (if you don't have these tables, observe the structure andcreate them in oracle)

Solution:

Creating the form

1. Start a new Visual Basic project.

2. Add controls to the form, as shown in the following illustration.

Page 182: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Example Database Programs in VB MS Visual Basic 6 Programming Introduction

170 V0.1

Control Property SettingForm Name frmRDC

' Caption Master / Details Form for Emp, Dept Tables

RDC Name rdcDept

' UserName Scott

' Password Tiger

' DataSourceName ORACLE

' CursorDriver rdUseOdbc

' LockType rdConcurValues

' Prompt rdDriverNoPrompt

' SQL SELECT * FROM Dept

RDC Name rdcEmp

' UserName Scott

' Password Tiger

' DataSourceName ORACLE

' CursorDriver rdUseOdbc

' LockType rdConcurValues

' Prompt rdDriverNoPrompt

' Visible False

TextBoxs Name txtDEPTNO

' DataSource dtaDept

' DataField DeptNo

TextBoxs Name txtDNAME

' DataSource dtaDept

' DataField DNAME

TextBoxs Name txtLOC

' DataSource dtaDept

' DataField LOC

DBGrid Name grdEmp

' DataSource dtaEmp

Commands Name cmdAllEmp

' Caption All Employees

Your Form should look like this at run time:

Page 183: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Example Database Programs in VB

V0.1 171

Writing Code

3. In the General Declarations of the form type the followings:

Option Explicit

Private Sub cmdAllEmp_Click() rdcEmp.SQL = "SELECT * FROM Emp" rdcEmp.Refresh grdEmp.ReBindEnd Sub

Private Sub Form_Activate() rdcDept_RepositionEnd Sub

Private Sub rdcDept_Reposition() If txtDEPTNO = "" Then Exit Sub rdcEmp.SQL = "SELECT * FROM Emp WHERE DeptNo = " &_ txtDEPTNO rdcEmp.Refresh grdEmp.ReBind rdcDept.Caption = "Record : " & rdcDept.Resultset.AbsolutePositionEnd Sub

4. Save the Project and press F5 to run.

Page 184: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Example Database Programs in VB MS Visual Basic 6 Programming Introduction

172 V0.1

ExerciseConnecting to ODBC Data Source usingData Control

A simple form demonstrating how to connect to an ODBC data source using the Data control.

Use a DSN 'Books Available' and connect through ODBC to the PUBS database in MSSQL server.The form should have 5 text boxes to display the 'title', 'publisher', 'notes', 'price' and 'advance'from the PUBS database in MS SQL server. The Datacontrol can be used to move to first / last /

next / previous records. Clicking on the close command button will close the program.

Solution

1. Creating a DSN: Double click on the 32 bit ODBC iocn in Control panel. Choose the "UserDSN" option, and click on Add button.Choose the SQL server driver ands click on Finish. Enter

the following information:

Data Source Name (example: Books Available), Description (Books Available), server (example:ISE). Select option and enter PUBS in the Login database name.

2. Open a new form. Place a data control in the form.

3. Place textboxes to store the field values. Change the DataSource property of the textboxes to'data1'.

4. Observe the code:

Option Explicit

Private Sub cmdClose_Click() Unload MeEnd Sub

Private Sub Form_Load()'Set up the form and connect to data sourceDim db As DatabaseDim rs As RecordsetDim sSQL As String

'Center the form Me.Top = (Screen.Height - Me.Height) / 2 Me.Left = (Screen.Width - Me.Width) / 2

'Connect to the database.

Page 185: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Example Database Programs in VB

V0.1 173

Data1.Connect = "ODBC;DSN=Books Available;UID=sa;PWD="

'Set the data control's RecordSource property sSQL = _ "SELECT titles.*, publishers.* " _ & "FROM titles, publishers " _ & "WHERE publishers.pub_id = titles.pub_id " _ & "ORDER BY titles.Title ASC;" Data1.RecordSource = sSQL

'Connect each of the text boxes with the appropriate fieldname txtAdvance.DataField = "Advance" txtNotes.DataField = "Notes" txtPrice.DataField = "Price" txtPublisher.DataField = "Pub_Name" txtTitle.DataField = "Title"

End Sub

Page 186: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Example Database Programs in VB MS Visual Basic 6 Programming Introduction

174 V0.1

ExerciseCreating a Data Entry Form

In this exercise, you will use the Data Form Wizard to create a Master/Detail data-entry form byusing the Orders and Order Details tables in the Nwind.mdb database.

Solution:

Create the Orders form

1. Create a new Standard EXE project.

2. Using the Add-In Manager, load the Data Form Wizard.

The Data Form Wizard command should now appear on the Add-Ins menu.

3. On the Add-Ins menu, click Data Form Wizard.

4. Select the Data Form Wizard options, as shown in the following table.

Option ValueDatabase format AccessDatabase Name Nwind.mdbForm Master/DetailLayout Master RecordSource

Orders table

Master Fields OrderID, CustomerID, EmployeeID,OrderDate, ShipName

Detail Record Source Order Details tableDetail Fields All fields in the Order Details tableField to link Master andDetail

OrderID

Available Control AllForm Name frmOrders

5. In the Project Properties dialog box, set Startup Object to frmOrders.

6. Run the application.

Your form should resemble the following illustration.

Page 187: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Example Database Programs in VB

V0.1 175

Note: The Data Form Wizard creates a control array for all text boxeson a form. For more information about control arrays, searchon “control arrays” in the Visual Basic Help index.

Examine the form created by the Data Form Wizard

1. Quit the application, and note the following properties and events of the form. TheDatabaseName and RecordSource properties of the Data control.

The Data control event procedures, in particular the Reposition event, which ensures that theMaster/Detail records are synchronized.

The DataSource and DataField properties of each of the text boxes.

The Click event procedure for each of the command buttons.

The DataSource property of the DBGrid control.

2. Save the form as Orders.frm, and save the project as Orders.vbp.

Page 188: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Example Database Programs in VB MS Visual Basic 6 Programming Introduction

176 V0.1

ExerciseUsing the DBCombo Control

In this exercise, you will enhance the Orders form by replacing the Employee ID text box with adata-bound combo (DBCombo) control. This will enable users to select employees by namewithout having to know their ID.

Solution:

Add a data control

Open the Orders form.

2. Add a new Data control to the form.

3. Set the Name property to datEmployees.

4. Set the DatabaseName property to \Nwind.mdb.

5. Set the RecordSource property to Employees.

6. Set the Visible property to False.

The Data control is hidden because it is used only to supply information to the data-boundcombo box. The user does not interact with this control directly.

Add a DBCombo control

1. On the Orders form, replace the Employee ID text box with a data bound combo box. You willneed to add the control to the Toolbox before you use it on the form.

2. Set the RowSource and ListField properties of the data-bound combo box so it contains theEmployee Last Name. Set the RowSource property to datEmployees, and the ListField propertyto LastName.

3. Set the DataSource, DataField , and BoundColumn properties of the data-bound combo box sothat the correct data is returned to the Orders table.Set the DataSource property to datPrimaryRS(the Data control created by the Data Form Wizard), and set the DataField and BoundColumnproperties to EmployeeID.

4. Test the application.Your form should resemble the following illustration.

Page 189: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Example Database Programs in VB

V0.1 177

Page 190: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Example Database Programs in VB MS Visual Basic 6 Programming Introduction

178 V0.1

ExerciseUsing the Validate Event

In this exercise, you will use the Data control’s Validate event to confirm changes made to theOrders table.

Solution:

1. Edit the Validate event for the Data control in the Orders table.

2. If any edits have been made to the current record, use a message box to prompt the userto the save changes.

3. If the user answers No to saving changes, delete the changes by using the Saveargument.

4. Run the application.

5. Edit the ShipName field, and move to the next record.

You should be prompted to save the changes. Choose No, and check to see if the changes arecanceled.

Observe the CODE:

Dim iResponse As IntegerIf Save = True Then 'data has changed 'get rid of changes if user does not want to save iResponse = MsgBox("Save changes?", vbYesNo) If iResponse = vbNo Then Save = False End IfEnd If

Page 191: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Example Database Programs in VB

V0.1 179

ExerciseCreating and Navigating a Recordset

In this exercise, you will use data access objects (DAO) to open a database and create a recordset.

Create Categories form

1. Create a new Visual Basic Standard EXE project.

2. Name the default form frmCategories.

3. Add controls to the form, as shown in the following illustration.

Note: Because the ID data will not be edited by the user, the CategoryID field is a Label control.

Open a database and create a recordset

1. On the Categories form, declare two module-level variables, as shown in the following code:

Dim dbCurrent As DatabaseDim recCategories As Recordset

2. Set a reference to the Microsoft DAO 3.5 Object Library.

3. In Load event procedure of the Categories form, follow these steps:

a. Open \Program Files\DevStudio\VB\Nwind.mdb and save theresulting database object in the variable dbCurrent.

b. Create a recordset by using the Categories table in the Nwind.mdbdatabase, and capture the resulting Recordset object in the variablerecCategories.

Page 192: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Example Database Programs in VB MS Visual Basic 6 Programming Introduction

180 V0.1

c. Move to the first record in the recordset.

d. Read the Category ID, Category Name, and Description fields into theappropriate controls.

Observe the CODE:

Private Sub Form_Load()Set dbCurrent = OpenDatabase("C:\Program_Files\DevStudio\VB\Nwind.mdb")Set recCategories = dbCurrent.OpenRecordset("Categories")recCategories.MoveFirstFillFieldsEnd SubSub FillFields()

' this procedure will populate the fields on the form.' it will be called from multiple procedures.lblCategoryID.Caption = recCategories.Fields("CategoryID")txtCategoryName.Text _= recCategories.Fields("CategoryName")txtDescription.Text = recCategories.Fields("Description")

End Sub

4. In the form Unload event procedure, Close the database.

5. Test the application. Is the first record in the Categories table displayed correctly?

Write code for the Move Previous and Move Next buttons

1. Add code to make the Move Previous and Move Next command buttons functional.

— After a move, fill in the fields on the form with data.— Test for the beginning and the end of the recordset.

Observe the CODE:

Private Sub cmdPrevious_Click()recCategories.MovePreviousIf recCategories.BOF Then

BeeprecCategories.MoveFirst

ElseFillFields

End IfEnd Sub

Private Sub cmdNext_Click()recCategories.MoveNextIf recCategories.EOF Then

BeeprecCategories.MoveLast

Page 193: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Example Database Programs in VB

V0.1 181

ElseFillFields

End IfEnd Sub

Test the project

1. Run the form.

2. Click the Move Previous button.

3. Click the Move Next button.

You should see different Category records.

Page 194: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Example Database Programs in VB MS Visual Basic 6 Programming Introduction

182 V0.1

ExerciseAdding and Editing Records

In this exercise, you will add new records and edit existing records using various DAO methods.

Modify the form

1. Modify the Categories form by adding the command buttons shown in the followingillustration.

Write code for the Add, Edit, Save, Cancel, and Delete buttons

1. To clear the text fields and enter Add mode, write code for the Add button.

Note Because the Category ID field is a counter field, it willautomatically contain a new value as soon as you issue theAddNew method. You can then place the value for this fieldin the Category ID label. For example, execute the followingcode immediately after the AddNew method.

lblCategoryID.Caption = recCategories("CategoryID")

2. To enter Edit mode, write code for the Edit button. For more information about editingrecords, see Updating Records.

3. To write changes from the text boxes back to the recordset and update it, write code for theSave button.

4. To cancel the pending update and update the fields with the current record in the recordset,write code for the Cancel button.

Page 195: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Example Database Programs in VB

V0.1 183

5. To delete the current record, write code for the Delete button. Move to the next record andretrieve the fields.

Observe the CODE:

Private Sub cmdEdit_Click()recCategories.Edit

End SubPrivate Sub cmdSave_Click()

recCategories.Fields("Category Name") =_ txtCategoryName.TextrecCategories.Fields("Description") = _txtDescription.TextrecCategories.UpdaterecCategories.Bookmark = _recCategories.LastModified

End SubPrivate Sub cmdCancel_Click()

recCategories.CancelUpdateFillFields

End SubPrivate Sub cmdDelete_Click()

recCategories.DeleterecCategories.MoveNextIf recCategories.EOF ThenrecCategories.MoveLastEnd IfFillFields

End Sub

Test the application

1. Add a new record.

2. Cancel the Add. Is the previous information restored correctly?

3. Add and save a new record.

4. To ensure that you are on the correct record after the Add, test the Move Next and MovePrevious buttons.

5. Delete the new record.

6. Try to delete the first category.

The referential integrity constraints on this table should cause a run-time error. In a later exercise,you will trap for that error.

Page 196: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Example Database Programs in VB MS Visual Basic 6 Programming Introduction

184 V0.1

ExerciseFinding Records

In this exercise, you will let the user search for specific records in the Categories table, based ontext within the Description field.

Write code for the Find button

1. Use the InputBox function to prompt users for a string that represents a portion of theDescription field.

2. Using the string returned from the Input box, create an SQL string to select the matchingrecords from the Categories table, as shown in this example:

"select * from categories where [Description] like '*pasta*'"

3. Create a recordset based on the SQL query, and assign the results to the recCategories variable.This enables the other buttons to operate in the new recordset.

4. If no records are found (recCategories.RecordCount = 0), display a message saying that norecords were found. Otherwise, display the first record in the new recordset.

Observe the CODE:

Private Sub cmdFind_Click()Dim strSQL As StringDim strAnswer As StringstrAnswer = InputBox("Enter any portion of _the Description", "Find Records")strSQL = "select * from categories where [Description] like "_ & "'*" & strAnswer & "*'"Set recCategories = dbCurrent.OpenRecordset(strSQL)If recCategories.RecordCount = 0 Then 'no records ‘foundMsgBox "No matching records found. Displaying all records."Set recCategories = dbCurrent.OpenRecordset("Categories")Else 'at least one record was foundrecCategories.MoveFirstFillFieldsEnd IfEnd Sub

Test the application

1. Run the form.

Page 197: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Example Database Programs in VB

V0.1 185

2. Click the Find button.

3. Enter sweet in the Input box.

You should see two records that contain the text sweet in the description.

Page 198: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Example Database Programs in VB MS Visual Basic 6 Programming Introduction

186 V0.1

ExerciseUsing Queries

In this exercise, you will use a saved query to return information from the Nwind.mdb database.

Query for the ten most expensive products

1. Create a new form.

2. The saved query Ten Most Expensive Products in the Nwind.mdb database returns the tenhighest priced products. In the Form_Load event procedure on the new form, create a recordsetbased on this query, and display the results in a DBGrid control, as shown in the followingillustration.

Observe the CODE:

Private Sub Form_Load()Dim dbCurrent As DatabaseSet dbCurrent =_ DBEngine.Workspaces(0).OpenDatabase("C:\Program_Files\DevStudio\VB\Nwind.mdb")Set datProducts.Recordset = OpenRecordset("Ten Most Expensive_Products")End Sub

Test the application

1. On the Project menu, click Project Properties.

2. Change the Startup Object to the new form, and then click OK.

3. Run the form.

You should see the ten most expensive products in the grid.

Page 199: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Example Database Programs in VB

V0.1 187

ExerciseDisabling Buttons During Edit

In this exercise, you will enable and disable the appropriate command buttons while the user isnavigating or editing data on the Categories form.

Enable and disable controls

1. When a user navigates in the Categories form, disable the text boxes, and the Save and Cancelbutton, so changes cannot be made to the data unless the user selects the Edit or Add button, asshown in the following illustration.

2. When a user selects the Edit or Add button, enable the text boxes, and the Save and Cancelbuttons. Disable all other buttons on the form.

After you have finished the form, it should resemble the following illustration.

Page 200: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Example Database Programs in VB MS Visual Basic 6 Programming Introduction

188 V0.1

Observe the CODE:

Private Sub cmdEdit_Click()ButtonEditAddModers.Edit

End Sub

Sub ButtonEditAddMode()cmdSave.Enabled = TruecmdCancel.Enabled = TruecmdAdd.Enabled = FalsecmdEdit.Enabled = FalsecmdDelete.Enabled = FalsecmdFind.Enabled = FalsecmdClose.Enabled = FalsecmdPrevious.Enabled = FalsecmdNext.Enabled = FalsetxtCategoryName.Enabled = TruetxtDescription.Enabled = True

End Sub

3. In the Save and Cancel buttons, add code that:

* Enables the command buttons Add, Edit, Delete , Find, Move Previous, and Move Next.

* Disables the text boxes.

* Disables the Save and Cancel buttons.

Test the application

1. Add a new record and save your changes.

2. Edit the new record and save your changes.

3. Edit the new record again and cancel your changes.

Page 201: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Example Database Programs in VB

V0.1 189

ExerciseUsing a Parameter Query

In this exercise, you will use a parameter query to return sales information from the Nwind.mdbdatabase.

Use a parameter query

1. Create a new form that uses the Employee Sales by Country parameter query to display salesrecords in a date range, as shown in the following illustration.

The parameter names for the query are Beginning Date and Ending Date .

Observe the CODE:

Private Sub cmdExecute_Click() Dim strSQL As String Dim dbCurrent As Database Dim recSales As Recordset Dim qrySales As QueryDef

Set dbCurrent = DBEngine.Workspaces(0).OpenDatabase _ ("C:\Program Files\DevStudio\VB\Nwind.mdb")

Set qrySales = dbCurrent.QueryDefs("Employee Sales by Country") qrySales.Parameters("Beginning Date") = CDate(txtBegin) qrySales.Parameters("Ending Date") = CDate(txtEnd) Set recSales = qrySales.OpenRecordset() Set datSales.Recordset = recSalesEnd Sub

2. Test the application.

Page 202: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Example Database Programs in VB MS Visual Basic 6 Programming Introduction

190 V0.1

ExerciseHandling Referential Integrity Violations

In this exercise, you will trap a run-time error produced by violating referential integrity rules.

Check the referential integrity error

1. Open NWindAdv.vbp.

2. Run the application.

3. Try to delete the first record. What happens?

4. End the application.

Trap the referential integrity violation

1. Open the Categories form.

2. In the Click event of the Delete button, add an error-handling routine to trap and handle theerror produced above. In the handler, display a message box saying that the item was notdeleted.

HandleError:If Err.Number = 3200 Then

MsgBox "Can not delete a Category which has " & _"related products in the Products Table."

ElseMsgBox "Error " & Err.Number & ": " & Err.Description

End If

Test the application

1. Run the application.

2. Try to delete the first category. What happens?

Page 203: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Example Database Programs in VB

V0.1 191

ExerciseMulti-User Issues

In this exercise, you will trap run-time errors that occur when multiple users try to edit the samedatabase information.

Add locking options

1. Add option buttons to the Categories form, as shown in the following illustration.

2. Set the Value property of the Pessimistic option button to True.

3. To set the LockEdits property, add code to each of the option buttons.

4. Add the following code to the Save button after the Update method, and to the Cancel buttonafter the CancelUpdate method.

DBEngine.Idle dbFreeLocks

This will free any database locks that were set during the add or edit process.

5. Save the project.

Test for multi-user errors

1. Create an executable for the application.

2. Run two instances of the application.

3. Using the Pessimistic locking option for both instances, try to edit the same record in bothinstances of Visual Basic, and note the error that occurs.

The error should display as "3260: Couldn't update; currently locked by user 'name' on machine'name'."

Page 204: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Example Database Programs in VB MS Visual Basic 6 Programming Introduction

192 V0.1

4. Using the Optimistic locking option for both instances, edit the same record in both instancesof Visual Basic. In the first instance, change the Category Name and save the record.

In the second instance, change the Category Name and try to save the record. Note the error thatoccurs.

The error should display as "3197: The Microsoft Jet database engine stopped the process becauseyou and another user are attempting to change the same data at the same time."

5. In the first instance of Visual Basic, set locking to Pessimistic , and edit the first record.In thesecond instance of Visual Basic, set locking to Optimistic ,edit the first record, change theCategory Name, and save the record.

Note the error that occurs.

The error should display as "3260: Couldn't update; currently locked by user 'name' on machine'name'."

6. End both instances of the application, and close the second instance of Visual Basic.

Trap multi-user run-time errors

1. Add code to the Edit command to check for the error encountered in Step 4 of the previousprocedure, and notify the user if an error occurs.

Observe the CODE:

Private Sub cmdEdit_Click()On Error GoTo EditErrorHandler recCategories.Edit ButtonEditAddModeExit SubEditErrorHandler: Select Case Err.Number Case 3260 'page currently locked MsgBox "Record is currently locked. Try again_

later." Case 3197 'data has changed MsgBox "Data has been changed and will be_

refreshed." 'get updated data recCategories.Bookmark = recCategories.Bookmark_

FillFields recCategories.Edit

Case Else MsgBox Err.Number & ": " & Err.Description End Select

End Sub

2. Add an error-handling routine to the Save command Click event.

Page 205: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Example Database Programs in VB

V0.1 193

In the error-handling code, check for the error encountered in Step 5 of the previous procedure. Ifthe error is found, notify the user and cancel the update.

In the error-handling routine, check for the error encountered in Step 6 of the previousprocedure. If the error is found, notify the user.

Observe the CODE:

Private Sub cmdSave_Click()On Error GoTo SaveErrorHandler ' save the record recCategories.Fields("CategoryName") = txtCategoryName.Text recCategories.Fields("Description") = txtDescription.Text recCategories.Update recCategories.Bookmark = recCategories.LastModified ButtonNonEditAddMode DBEngine.Idle dbFreeLocksExit SubSaveErrorHandler: Select Case Err.Number Case 3260 MsgBox "Record is currently locked. Try Save again later _or cancel changes."

Case 3197 MsgBox "Data has been changed by another user. Your changes _have been canceled." cmdCancel_Click

Case Else MsgBox Err.Number & ": " & Err.Description

End SelectEnd Sub

3. Save the application.

4. Repeat the steps in this procedure to test the application.

Page 206: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Example Database Programs in VB MS Visual Basic 6 Programming Introduction

194 V0.1

ExerciseUsing ODBCDirect

In this exercise, you will access external data stored in a Microsoft SQL Server database by usingODBCDirect.

Query the external database

For this exercise, you will need a server running Microsoft SQL Server and its sample Pubsdatabase.

1. Create a new Visual Basic standard EXE project.

2. Create a new form with a command button and a list box.

Your form should resemble the following illustration.

3. In the Click event for the command button, do the following:

a. Create an ODBCDirect workspace.

b. Create a new connection to the workspace.

c. Create a recordset based on the Authors table.

To see a code sample of the SQL statement, click this icon.

SELECT au_lname FROM Authors ORDER BY au_lname

d. Populate the list box with the last names (field au_lname) from the Authors table.

Page 207: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

V0.1 195

Custom Controls

Objectives

In this Chapter, you will learn about some Customs Controls like (MSChart Control, SS Tab Control, Grid Control, DB Grid Control, MS FlexGrid Control, Rich Text Box Control, and Masked Edit Control).

• MS Chart Control

• SS Tab Control

• Grid Control

• DB Grid Control

• MS Flex Grid Control

• Rich Text Box Control

• Exploring Rich Text Box, Common Dialog Control

• Masked Edit Control

MS Chart Control

This control displays data graphically.

The MS Chart control supports the following features:

♦ True three-dimensional representation.

♦ Support for all major chart types.

♦ Data grid population via random data and data arrays.

The MS Chart control is associated with a data grid (DataGrid object). This data grid is a table

that holds the data being charted. The data grid can also include labels used to identify series andcategories on the chart. The person who designs the chart application fills the data grid withinformation by inserting data or by importing data from a spreadsheet or array.

Example

Open a new project and select Microsoft Chart Control. Place the Microsoft Chart Control on theform. Add a command button on the form. Enter the following code in the click event of thecommand button.

Page 208: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Custom Controls MS Visual Basic 6 Programming Introduction

196 V0.1

Private Sub Command1_Click() With Form1.MSChart1 ' Displays a 3d chart with 10 columns and 10 rows ' data. .chartType = VtChChartType3dArea .ColumnCount = 10 'set the number of columns to 10 .RowCount = 10 'set the number of rows to 10 For Column = 1 To 10 For Row = 1 To 10

.Column = Column .Row = Row Next Row Next Column End WithEnd Sub

The output must look like this,

Note: The ColumnCount Property sets the number of columns and theRowCount Property sets the number of rows. The columnproperty refers to the current column and the row propertyrefers to the current row.

Page 209: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Custom Controls

V0.1 197

SSTab Control

The SSTab control provides a group of tabs, each of which acts as a container for other controls.

Only one tab is active in the control at a time, displaying the controls it contains to the user whilehiding the controls in the other tabs.

A SSTab control is like the dividers in a notebook or the labels on a group of file folders. Using a

SSTab control, you can define multiple pages for the same area of a window or dialog box in yourapplication. Using the properties of this control, you can:

♦ Determine the number of tabs.

♦ Organize the tabs into more than one row.

♦ Set the text for each tab.

♦ Display a graphic on each tab.

♦ Determine the style of tabs used.

♦ Set the size of each tab.

At run time, users can navigate between tabs by either pressing Ctrl + Tab or by using

accelerator keys defined in the caption of each tab.

EXAMPLE: Exploring Chart and SSTab Control

In this exercise, you will create a form with Chart and SSTAB Controls to implement the use ofChart control.

Creating the form

1.Start a new Visual Basic project.

2. Add controls to the form, as shown in the following illustration.

Page 210: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Custom Controls MS Visual Basic 6 Programming Introduction

198 V0.1

Control Property Setting

Form Name frmChart

" Caption Chart Demonstration

SSTab Name tabView

" Tabs 2

" Caption (Tab1) Data

" Caption (Tab2) Chart

Chart Name chaSales

" RowCount 3

" ColumnCount 3

" RowLabel (1) Jan

" RowLabel (2) Feb

" RowLabel (3) Mar

" ColumnLabel (1) VB5

" ColumnLabel (2) VC

" ColumnLabel (3) PB5

CheckBox Name chkLegend

TextBox Name txtJanVB

TextBox Name txtFebVB

TextBox Name txtMarVB

TextBox Name txtJanVC

TextBox Name txtFebVC

TextBox Name txtMarVC

TextBox Name txtJanPB

TextBox Name txtFebPB

TextBox Name txtMarPB

Page 211: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Custom Controls

V0.1 199

Writing Code

3. In the General Declarations of the form type the followings:

Option Explicit

Private Sub chkLegend_Click()

'If Legend option is selected set the ShowLegend property of the'Chart control to true.If chkLegend.Value = vbChecked Then chaSales.ShowLegend = TrueElse chaSales.ShowLegend = FalseEnd If

End Sub

Private Sub cmdRefChart_Click()

'On pressing Refresh Chart Button, Refresh the Data property'of the Chart control with the data entered by the user in the'text boxes.chaSales.Row = 1chaSales.Column = 1chaSales.Data = txtJanVBchaSales.Row = 2chaSales.Column = 1chaSales.Data = txtFebVBchaSales.Row = 3chaSales.Column = 1chaSales.Data = txtMarVB

chaSales.Row = 1chaSales.Column = 2chaSales.Data = txtJanVCchaSales.Row = 2chaSales.Column = 2chaSales.Data = txtFebVCchaSales.Row = 3chaSales.Column = 2chaSales.Data = txtMarVC

chaSales.Row = 1chaSales.Column = 3chaSales.Data = txtJanPBchaSales.Row = 2chaSales.Column = 3chaSales.Data = txtFebPBchaSales.Row = 3chaSales.Column = 3chaSales.Data = txtMarPB

Page 212: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Custom Controls MS Visual Basic 6 Programming Introduction

200 V0.1

End Sub

4. Save the Project and press F5 to run.

Grid Control

This is the simplest grid control available in the components dialog box. This helps us to performordinary operation without bounding a table from a database.

EXAMPLE : Using Grid Control

Using the GridControl, write a program that calculates the Addition, Subtraction, Multiplicationand Division of number ranging from 1 to 12.

Solution:

• Open a new project.

• Add a Grid and 4 CommandButton Controls to the Form.

• Save the form as GridApp.Frm and the Project as FridApp.vbp.

• Change the Caption Property of the buttons to Add, Multiply, Subtract and Divide.

• Change the Name property of the buttons to cmdAdd, cmdMultiply, cmdSubtract andcmdDivide.

• Change the Caption Property of the form to (empty).

• Set the Rows and Cols property of the Grid to 13.

• Enter the following code in the Form_Load( ) procedure:

Private Sub Form_Load( )Dim a As IntegerGrid1.Row = 0For a = 1 to 12

Grid1.col = 1Grid1.Text = Str(a)

NextGrid1.col = 0For a = 1 to 12

Grid1.Row = aGrid1.Text = Str(a)

NextEnd Sub

Page 213: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Custom Controls

V0.1 201

• Enter the following code in the Click Event Procedures of the command buttons:

Private Sub cmdAdd_Click( )Form1.Caption = 'Addition Program'Dim x, yFor x = 1 To 12 Step 1

Grid1.Row = xFor y = 1 to 12 Step 1

Grid1.col = yGrid1.Text = x + y

NextNext

End Sub

Private Sub cmdSubtract_Click( )Form1.Caption = 'Subtraction Program'Dim x, yFor x = 1 To 12 Step 1

Grid1.Row = xFor y = 1 to 12 Step 1

Grid1.col = yGrid1.Text = x - y

NextNext

End Sub

Private Sub cmdDivide_Click( )Form1.Caption = 'Division Program'Dim x, yFor x = 1 To 12 Step 1

Grid1.Row = xFor y = 1 to 12 Step 1

Grid1.col = yGrid1.Text = x / y

NextNext

End Sub

Private Sub cmdMultiply_Click( )Form1.Caption = 'Multiplication Program'Dim x, yFor x = 1 To 12 Step 1

Grid1.Row = xFor y = 1 to 12 Step 1

Grid1.col = yGrid1.Text = x * y

NextNext

End Sub

Page 214: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Custom Controls MS Visual Basic 6 Programming Introduction

202 V0.1

Example

In the above Grid Control program, change the width of the grid lines from the default. Also, tryto make the grid lines invisible (Hint: Use GridlineWidth property).

Solution :

• Open the GridApp.vbp and add a CommandButton to the Form.

• Change the Caption property of the CommandButton to Width and change the Nameproperty to cmdName.

• Enter the following code in the cmdWidth_Click( ) procedure:

Private Sub cmdWidth_Click( )If Grid1.GridLineWidth < 4 Then

Grid1.GridLineWidth = Grid1.GridLineWidth + 1Else

Grid1.GridLineWidth = 1End If

End Sub

Thus, the Grid lines are made invisible by setting the GridLines property to False at design time.

Example

Write a code to display the location of the current cell and the range of the selection as user selectcells or ranges in a Grid Control.

Solution

• Open a new project and add a GridControl and two LabelControls to the Form.

• Enter the following code in the Form_Load( ) procedure:

Private Sub Form_Load( )Grid1.Cols = 6Grid1.Rows = 7End Sub

• Enter the following code in the Grid1_RowColChange( ) procedure:

Private Sub Grid1_RowColChange( )Msg = "Active Cell: " & Chr(64 + Grid1.Col)Msg = Msg & Grid1.Row

Page 215: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Custom Controls

V0.1 203

label1.Caption = MsgEnd Sub

• Enter the following code in the Grid1_SelChange( ) procedure:

Private Sub Grid1_CellChange( )Msg = "Selection: " & Chr(64 + Grid1.SelStartCol)Msg = Msg & Grid1.SelStartColMsg = Msg & ":" & Chr(64 + Grid1.SelEndCol)Msg = Msg & Grid1.SelEndRowlabel2.Caption = Msg

End Sub

DBGrid Control

This control displays and enables data manipulation of a series of rows and columns representingrecords and fields from a Recordset object.

The data-aware DBGrid control appears similar to the Grid control; however, you can set theDBGrid control's DataSource property to a Data control so that the control is automatically filledand its column headers set automatically from a Data control's Recordset object. The DBGrid

control is really a fixed collection of columns, each with an indeterminate number of rows.

Each cell of a DBGrid control can hold text values, but not linked or embedded objects. You canspecify the current cell in code, or the user can change it at run time using the mouse or the arrow

keys. Cells can be edited interactively, by typing into the cell, or programmatically. Cells can beselected individually or by row.

The Datasource like the DataControl or Microsoft Remote DataControl must be specified for this

property. Before all this, the Database name and Recordsource property of the DataControl has tobe specified. The other important properties of DBGrid include the AllowDelete property whichwhen set to true allows the user to delete a record. AllowUpdate property enables a user to

update a record. AllowAddnew property allows a user to enter new records.

Example

Open a new project. In the components select Microsoft Data Bound Grid control. Place DBGridand DataControl on the form.

Set the following property of datacontrol.

DatabaseName : C:\Program Files\DevStudio\VB\Biblio.mdbRecordsource : All TitlesSet the following property of DBGrid control.

Datasource : Data1

Page 216: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Custom Controls MS Visual Basic 6 Programming Introduction

204 V0.1

Now run the form, the DBGrid is now populated with records fetched from the Authors table.And, all this without writing a single code.

The output would look something like this

Example:

A form should display a DBGrid control, a list box, a data control and 'clear' and 'exit'buttons.The program should load the c:\program files\devstudio\vb\biblio.mdb file and display all therecords in the Dbgrid control. The user can select any record by double clicking the same, whichwill then appear in the list box. Clicking on clear will clear the list box. 'Exit' stops execution ofthe program.

Solution:

Observe the coding:

Option Explicit

Private Sub Command1_Click() List1.Clear ' Clears the listboxEnd Sub

Private Sub Command2_Click() Unload Form1 End ' Ends applicationEnd Sub

Private Sub Data1_Reposition() ' Assign the Title to the caption property Data1.Caption = Data1.Recordset("Title")

Page 217: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Custom Controls

V0.1 205

End Sub

Private Sub DBGrid1_DblClick() ' Add the title to the list List1.AddItem Data1.Recordset("Title")End Sub

MSFlexGrid Control

The MSFlexGrid control displays and operates on tabular data. It allows complete flexibility tosort, merge, and format tables containing strings and pictures. When bound to a Data control,MSFlexGrid displays read-only data.

You can put text, a picture, or both in any cell of a MSFlexGrid. The Row and Col propertiesspecify the current cell in a MSFlexGrid. You can specify the current cell in code, or the user canchange it at run time using the mouse or the arrow keys. The Text property references the

contents of the current cell.

Use the Cols and Rows properties to determine the number of columns and rows in aMSFlexGrid control.

The MSFlexGrid can display records just like DBGrid control the difference being the user cannotenter data into the cells of MSFlexGrid. But one can use the col and row property along with thetext property to assign a value to a specific cell.

Example

MSFlexGrid.Cols=5MSFlexGrid.Rows=7MSFlexGrid.Row=3MSFlexGrid.Col=2MSFlexGrid.Text="Hello"

This would display the text Hello in the cell whose row and column co-ordinate would be 3 and 2

respectively. Note that instead of specifying the row and column separately, the TextMatrixproperty can be exploited as follows,

MSFlexGrid.TextMatrix(2,3)="Hello"

This would assign the text Hello in the cell whose row and column co-ordinate would be 2 and 3respectively.

Page 218: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Custom Controls MS Visual Basic 6 Programming Introduction

206 V0.1

RichTextBox Control

The Rich Text Box control allows the user to enter and edit text while also providing more

advanced formatting features than the conventional Text Box control.

The Rich Text Box control provides a number of properties you can use to apply formatting toany portion of text within the control. To change the formatting of text, it must first be selected.

Only selected text can be assigned character and paragraph formatting. Using these properties,you can make text bold or italic, change the color, and create superscripts and subscripts. You canalso adjust paragraph formatting by setting both left and right indents, as well as hanging

indents.

The Rich Text Box control opens and saves files in both the RTF format and regular ASCII textformat. The Rich Text Box control supports both clipboard and OLE drag/drop of OLE objects.

When an object is pasted in from the clipboard, it is inserted at the current insertion point. Whenan object is dragged and dropped into the control, the insertion point will track the mouse cursoruntil the mouse button is released, causing the object to be inserted. This behavior is the same as

Microsoft Word.

To print all or part of the text in a Rich Text Box control, use the SelPrint method.

Example

Add a new project and select Microsoft Rich Text Box control from the component’s window.Place the 2 controls of the same on the form. Also place a command button on the form. The taskshall be to load a file into the first Rich Text Box in the form load event and on pressing thecommand button the text selected in the first Rich Text Box gets added to the second Rich TextBox. Set the Scroll Bar property of both the controls to 3.

Enter the following code in the code window of the form.

Private Sub Form_Load()RichTextBox1.filename = "c:\xx.rtf" ' load the file name xx.rtf into

‘RichTextBox1End Sub

Private Sub Command2_Click()RichTextBox2.Text = RichTextBox2.Text & RichTextBox1.SelText 'Add the selected text in 'RichTextBox1 to RichTextBox2

End Sub

The form would appear like this,

Page 219: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Custom Controls

V0.1 207

EXAMPLE: Exploring Rich Text Box, Common Dialog Control

In this exercise, you will create a form with Rich Text Box and Common Dialog Controls toimplement how to use windows different dialog boxes and their properties in your applicationand how to use the Rich Text Box to format text in it like a word editor tool.

Creating the form

1.Start a new Visual Basic project.

2. Add controls to the form, as shown in the following illustration.

Control Property Setting

Form Name frmRtb

RichText Box Name Rtb

' ScrollBars 3 – rtfBoth

Common Dialog Name Cd

Command Button Name cmdFileOpen

' Name cmdFileSave

' Name cmdFonts

At this point your form should look like this:

Page 220: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Custom Controls MS Visual Basic 6 Programming Introduction

208 V0.1

Writing Code

3.In the General Declarations of the form type the followings:

Option Explicit

Private Sub cmdFonts_Click()

Cd.Flags = cdlCFEffects + cdlCFBoth Cd.ShowFont

With Rtb .SelBold = Cd.FontBold .SelFontName = Cd.FontName .SelFontSize = Cd.FontSize .SelItalic = Cd.FontItalic .SelStrikeThru = Cd.FontStrikethru .SelUnderline = Cd.FontUnderline .SelColor = Cd.Color End With

End Sub

Private Sub cmdOpenFile_Click() On Error GoTo foErr Cd.DialogTitle = "Open File" Cd.Filter = "Text File|*.TXT|Rich Text File|*.RTF" Cd.ShowOpen If Cd.FilterIndex = 1 Then Rtb.LoadFile Cd.filename, rtfText ElseIf Cd.FilterIndex = 2 Then Rtb.LoadFile Cd.filename, rtfRTF End If Me.Caption = Cd.filename

Page 221: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Custom Controls

V0.1 209

foErr: If Err.Number = 321 Then MsgBox "This file cannot be opened", vbCritical Exit Sub End IfEnd Sub

Private Sub cmdSaveFile_Click() Cd.Filter = "Text File|*.TXT|Rich Text File|*.RTF" Cd.ShowSave If Cd.FilterIndex = 1 Then Rtb.SaveFile Cd.filename, rtfText ElseIf Cd.FilterIndex = 2 Then Rtb.SaveFile Cd.filename, rtfRTF End IfEnd Sub

Private Sub Form_Resize() If Me.WindowState = vbMinimized Then Exit Sub Rtb.Height = Me.Height - 1260 Rtb.Width = Me.Width - 285 cmdOpenFile.Top = Me.Height - 915 cmdSaveFile.Top = Me.Height - 915 cmdFonts.Top = Me.Height - 915End Sub

4. Save the Project and press F5 to run.

MS FlexiGrid Control

EXAMPLE: Exploring FlexiGrid Control

In this example, you will create a form with MS FlexiGrid Control to implement the use ofColumn Merging, new properties and methods that makes you easy to work with this Grid thanany other grid controls.

Creating the form

1.Start a new Visual Basic project.

2.Add controls to the form, as shown in the follwing illustration.

Page 222: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Custom Controls MS Visual Basic 6 Programming Introduction

210 V0.1

Control Property Setting

Form Name frmFGrid

" Caption FlexiGrid Demonstration

MSFlexiGrid

Name grd

' Cols 4

' Rows 25

ComboBox

Name cboDept

' Visible False

' List [Administration, Sales, Purchase,

Production, Marketing]

' Name cboDesig

' Visible False

' List [Manager, Assistant, Accountant, Programmer, Clerk]

CheckBox

Name chkMergDept

' Name chkMergDesig

' Style 1 – Graphical

Button Name CmdExit

At this point your form should look like this:

Page 223: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Custom Controls

V0.1 211

Writing Code

3. In the General Declarations of the form type the followings:

Option Explicit

Private Sub chkMergDept_Click() If chkMergDept = vbChecked Then grd.MergeCells = flexMergeFree grd.MergeCol(0) = True Else grd.MergeCol(0) = False End IfEnd Sub

Private Sub chkMergDesig_Click() If chkMergDesig = vbChecked Then grd.MergeCells = flexMergeFree grd.MergeCol(1) = True Else grd.MergeCol(1) = False End IfEnd Sub

Private Sub cmdExit_Click() Unload MeEnd Sub

Private Sub Form_Load() grd.TextMatrix(0, 0) = "Department" grd.TextMatrix(0, 1) = "Designation" grd.TextMatrix(0, 2) = "Employee" grd.TextMatrix(0, 3) = "Salary" grd.ColWidth(0) = 1200 grd.ColWidth(1) = 1200 grd.ColWidth(2) = 1200 grd.ColWidth(3) = 1000 grd_EnterCellEnd Sub

Private Sub grd_EnterCell() If grd.Col = 0 Then 'Department txtData.Visible = False cboDesig.Visible = False cboDept.Visible = True cboDept.Text = grd.Text cboDept.Left = grd.CellLeft + grd.Left cboDept.Top = grd.CellTop + grd.Top cboDept.Width = grd.CellWidth Exit Sub End If

Page 224: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Custom Controls MS Visual Basic 6 Programming Introduction

212 V0.1

If grd.Col = 1 Then 'Designation cboDept.Visible = False txtData.Visible = False cboDesig.Visible = True cboDesig.Text = grd.Text cboDesig.Left = grd.CellLeft + grd.Left cboDesig.Top = grd.CellTop + grd.Top cboDesig.Width = grd.CellWidth Exit Sub End If If grd.Col = 2 Or grd.Col = 3 Then 'Employee and Salary cboDept.Visible = False txtData.Visible = True cboDesig.Visible = False txtData = grd.Text txtData.Left = grd.CellLeft + grd.Left txtData.Top = grd.CellTop + grd.Top txtData.Width = grd.CellWidth Exit Sub End IfEnd Sub

Private Sub grd_LeaveCell() If grd.Col = 0 Then grd.Text = cboDept If grd.Col = 1 Then grd.Text = cboDesig If grd.Col = 2 Or grd.Col = 3 Then grd.Text = txtDataEnd Sub

4. Save the Project and press F5 to run.

Masked Edit Control

The Masked Edit control provides restricted data input as well as formatted data output. Thiscontrol supplies visual clues about the type of data being entered or displayed.

The Masked Edit control generally behaves as a standard text box control with enhancements foroptional masked input and formatted output. If you don't use an input mask, the Masked Editcontrol behaves much like a standard text box, except for its dynamic data exchange (DDE)

capability.

If you define an input mask using the Mask property, each character position in the Masked Editcontrol maps to either a placeholder of a specified type or a literal character. Literal characters, or

literals, can give visual cues about the type of data being used. For example, the parenthesessurrounding the area code of a telephone number are literals: (206).

If you attempt to enter a character that conflicts with the input mask, the control generates a

ValidationError event. The input mask prevents you from entering invalid characters into thecontrol.

Page 225: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Custom Controls

V0.1 213

The Masked Edit control has three bound properties: DataChanged, DataField, and DataSource.

This means that it can be linked to a data control and display field values for the current record inthe recordset. The Masked Edit control can also write out values to the recordset.

When the value of the field referenced by the DataField property is read, it is converted to a Text

property string, if possible. If the recordset is updatable, the string is converted to the data type ofthe field.

To clear the Text property when you have a mask defined, you first need to set the Mask

property to an empty string, and then the Text property to an empty string:

MaskedEdit1.Mask = ""MaskedEdit1.Text = ""

When you define an input mask, the Masked Edit control behaves differently from the standardtext box. The insertion point automatically skips over literal as you enter data or move theinsertion point.

When you insert or delete a character, all non-literal characters to the right of the insertion pointare shifted, as necessary. If shifting these characters leads to a validation error, the insertion ordeletion is prevented, and a Validation Error event is triggered.

Suppose the Mask property is defined as "?###", and the current value of the Text property is"A12." If you attempt to insert the letter "B" to the left of the letter "A," the "A" would shift to theright. Since the second value of the input mask requires a number, the letter "A" would cause the

control to generate a Validation Error event.

The Masked Edit control also validates the values of the Text property at run time. If you set theText property so that it conflicts with the input mask, the control generates a run-time error.

You may select text in the same way as for a standard text box control. When selected text isdeleted, the control attempts to shift the remaining characters to the right of the selection.However, any remaining character that might cause a validation error during this shift is deleted,

and no Validation Error event is generated.

Normally, when a selection in the Masked Edit control is copied onto the Clipboard, the entireselection, including literals, is transferred onto the Clipboard. You can use the ClipMode

property to transfer only user-entered data onto the Clipboard — literal characters that are partof the input mask are not copied.

Example

Following is an example for entering date in dd/mm/yyyy (12/09/1998) format.

Open a new project and from the component window, add the Microsoft Masked Edit Control.Set the Mask property of the Masked Edit Control to ##/##/####. Note that # denotes that itcan accept any digit.

Page 226: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Custom Controls MS Visual Basic 6 Programming Introduction

214 V0.1

The possible settings for mask are,

Mask character Description# Digit placeholder.. Decimal placeholder., Thousands separator.: Time separator./ Date separator.\ Treat the next character in the mask string as a literal.& Character placeholder.

Page 227: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

V0.1 215

MS Windows Common Controls

Objectives

In this Chapter, you will learn about MS Windows Common Controls(like Tool Bar, Status Bar, Progress Bar, Slider Control, ListView, Tree View, Image List and Tab Strip Control).

• Tool Bar Control

• Status Bar Control

• Exploring Tool Bar and Status Bar Control

• Progress Bar

• Slider Control

• Exploring Progress Bar, Slider, Up Down Controls

• List View Control

• Tree View Control

• Exploring List View and Tree View Control

• Image List Control

• Tab Strip Control

Toolbar Control

A Toolbar control contains a collection of Button objects used to create a toolbar that is associatedwith an application.

Typically, a toolbar contains buttons that correspond to items in an application's menu, providing

a graphic interface for the user to access an application's most frequently used functions andcommands.

The Toolbar control allows you to create toolbars by adding Button objects to a Buttons

collection. Each Button object can have optional text or an image, or both, supplied by anassociated ImageList control. You can display an image on a button with the Image property, ordisplay text with the Caption property, or both, for each Button object. At design time, you can

add Button objects to the control using the Properties Page of the Toolbar control. At run time,you can add or remove buttons from the Buttons collection using the Add and Remove methods.

Page 228: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Windows Common Controls MS Visual Basic 6 Programming Introduction

216 V0.1

To program the Toolbar, add code to the ButtonClick event to respond to the selected button.

You can also determine the behavior and appearance of each Button object using the Styleproperty. For example, if four buttons are assigned the ButtonGroup style, only one button canbe pressed at any time and at least one button is always pressed.

You can create space for other controls on the toolbar by assigning a Button object thePlaceHolder style, then positioning a control over the placeholder. For example, to place a drop-down combo box on a toolbar at design time, add a Button object with the PlaceHolder style and

size it as wide as a ComboBox control. Then place a ComboBox control on the placeholder.

Double clicking a toolbar at run time invokes the Customize Toolbar dialog box, which allowsthe user to hide, display, or rearrange toolbar buttons. To enable or disable the dialog box, use

the AllowCustomize property. You can also invoke the Customize Toolbar dialog box using theCustomize method. If you wish to save and restore the state of a toolbar, or allow the user to doso, two methods are provided: the SaveToolbar and RestoreToolbar methods. The Change event,

generated when a toolbar is altered, is typically used to invoke the SaveToolbar method.

Example:

Write a program, which uses the ToolBar in your application. The Toolbar should have Editoptions like Cut, Copy and Paste. Place a Text Box on the form. Text typed in the text box shouldbe cut or copied to the clipboard in the user clicks on the Cut or Copy options of the toolbar. Thecontent copied to the clip board is pasted in the text box, when ever the user clicks the Pasteoption of the tool bar.

1. Open a standard Exe project. Choose Microsoft Windows Common Controls 5.0 from Project -> Components. This loads the controls like status bar, toolbar, Slider, Progress Bar, ImageList,TreeView, ListView and Tabstrip controls.

2. Select the Toolbar control and select the property sheet for the toolbar control. Click on theButton tab and insert 3 buttons by clicking ‘Insert Button’.

3. Set the caption, key, Index and tag as follows:

Index Caption Key Tag1 Cut BtnCut 12 Copy BtnCopy 23 Paste BtnPaste 3

4. Write the following code in the toolbar Button Click event

Private Sub Toolbar1_ButtonClick(ByVal Button As ComctlLib.Button) Select Case Button.Key Case "btnCopy": Clipboard.Clear Clipboard.SetText Text1.SelText Case "btnCut": Clipboard.Clear

Page 229: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction MS Windows Common Controls

V0.1 217

Clipboard.SetText Text1.SelText Text1.Text = " " Case "btnPaste": Text1.SelText = Clipboard.GetText() End Select

End Sub

Status Bar Control

A StatusBar control provides a window, usually at the bottom of a parent form, through whichan application can display various kinds of status data. The StatusBar can be divided up into a

maximum of sixteen Panel objects that are contained in a Panels collection.

A StatusBar control consists of Panel objects, each of which can contain text and/or a picture.Properties to control the appearance of individual panels include Width, Alignment (of text and

pictures), and Bevel. Additionally, you can use one of seven values of the Style property toautomatically display common data such as date, time, and keyboard states.

At design time, you can create panels and customize their appearance by setting values in the

Panel tab of the Properties Page of the StatusBar control. At run time, the Panel objects can bereconfigured to reflect different functions, depending on the state of the application. For detailedinformation about the properties, events, and methods of Panel objects, see the Panel Object and

Panels Collection topics.

A StatusBar control typically displays information about an object being viewed on the form, theobject's components, or contextual information that relates to that object's operation. The

StatusBar, along with other controls such as the Toolbar control, gives you the tools to create aninterface that is economical and yet rich in information.

Page 230: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Windows Common Controls MS Visual Basic 6 Programming Introduction

218 V0.1

EXAMPLE: Exploring Toolbar, Statusbar Control

In this exercise, you will create a form with Toolbar, Statusbar and Command Button controls to

implement the use of Toolbar and Statusbar so as to navigate their sub objects Button and Panel.

Creating the form

1. Start a new Visual Basic project.

2. Add controls to the form, as shown below.

Control Property Setting

Form Name frmSbTb

' Caption Statusbar & ToolbarDemo

Statusbar Name Sb

' Stype 0 – Normal

Toolbar Name Tb

' Border Style 1 - Fixed Single

Command Name cmdAddBtn

' Caption Add Button

Command Name cmdDelBtn

' Caption Delete Button

Command Name cmdAddPnl

' Caption Add Panel

Command Name cmdDelPnl

' Caption Delete Panel

At this point your form should look like this:

Page 231: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction MS Windows Common Controls

V0.1 219

Writing Code

3. In the General Declarations of the form type the followings:

Option Explicit

Private Sub cmdAddBtn_Click() Static i As Integer Dim c As String i = i + 1 c = InputBox("Enter Button Title") Tb.Buttons.Add i, , cEnd Sub

Private Sub cmdAddBtn_GotFocus() Sb.Panels(1).Text = "Click to Add a Button to the Toolbar"End Sub

Private Sub cmdAddPnl_Click() Static i As Integer Dim c As String i = i + 1 If Sb.Panels.Count = 16 Then MsgBox "You can add only 16 Panels in a Statusbar" Exit Sub End If c = InputBox("Enter Panel Title") Sb.Panels.Add i, , c Sb.Panels(i).AutoSize = sbrSpringEnd Sub

Private Sub cmdAddPnl_GotFocus()Sb.Panels(1).Text = "Click to Add a Panel to the Statusbar"End Sub

Private Sub cmdDelBtn_Click() Dim i As Integer i = InputBox("Enter Button No. to Delete") Tb.Buttons.Remove iEnd Sub

Private Sub cmdDelBtn_GotFocus()Sb.Panels(1).Text = "Click to Delete a Button from the Toolbar"End Sub

Private Sub cmdDelPnl_Click() Dim i As Integer i = InputBox("Enter Panel No. to Delete") Sb.Panels.Remove iEnd Sub

Private Sub cmdDelPnl_GotFocus()

Page 232: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Windows Common Controls MS Visual Basic 6 Programming Introduction

220 V0.1

Sb.Panels(1).Text = "Click to Delete a Panel from the Statusbar"End Sub

Private Sub Sb_PanelClick(ByVal Panel As ComctlLib.Panel) MsgBox "You Have Clicked " & Panel.TextEnd Sub

Private Sub Tb_ButtonClick(ByVal Button As ComctlLib.Button) MsgBox "You Have Clicked " & Button.CaptionEnd Sub

4. Save the Project and press F5 to run.

Progress Bar

The ProgressBar control shows the progress of a lengthy operation by filling a rectangle with

chunks from left to right.

The ProgressBar control monitors an operation's progress toward completion.

A ProgressBar control has a range and a current position. The range represents the entire

duration of the operation. The current position represents the progress the application has madetoward completing the operation. The Max and Min properties set the limits of the range. TheValue property specifies the current position within that range. Because chunks are used to fill in

the control, the amount filled in only approximates the Value property's current setting. Based onthe control's size, the Value property determines when to display the next chunk.

The ProgressBar control's Height and Width properties determine the number and size of the

chunks that fill the control. The more chunks, the more accurately the control portrays anoperation's progress. To increase the number of chunks displayed, decrease the control's Heightor increase its Width. The BorderStyle property setting also affects the number and size of the

chunks. To accommodate a border, the chunk size becomes smaller.

You can use the Align property with the ProgressBar control to automatically position it at thetop or bottom of the form.

Example

The following code counts to 10 one second at a time. If the BusyCancel property is checked thefunction stops.

Place the progress bar on the form. Place a command button called Action and in the click evententer the following code.

Private Sub cmdActionClick( )Dim nLoopCtr as integerDim nStyle as integer

Page 233: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction MS Windows Common Controls

V0.1 221

For nLoopCtr = 1 to 10form1.barcaption = "Processing Step " & Trim$(CStr(nLoopCtr)) & " of 10 "form1.Barpercent = nLoopCtr * 10DoEventsnext nLoopCtrEnd Sub

Slider Control

A Slider control is a window containing a slider and optional tick marks. You can move the sliderby dragging it, clicking the mouse to either side of the slider, or using the keyboard.

Slider controls are useful when you want to select a discrete value or a set of consecutive valuesin a range. For example, you could use a Slider to set the size of a displayed image by moving theslider to a given tick mark rather than by typing a number. To select a range of values, set the

SelectRange property to True, and program the control to select a range when the SHIFT key isdown.

The Slider control can be oriented either horizontally or vertically.

Example:

This example matches the width of a TextBox control to that of a Slider control.

The user can increase or decrease the value of the slider. The text box width will changeaccordingly.

Solution

1. Open a new Standard exe project.

2. Using the Project – Components menu option, select the Microsoft Windows CommonControl 5.0.

3. Double click on the slider control to place it on the form. Position the control on the form.

4. Place a text box on the form (below the slider control).

Option Explicit

Private Sub Form_Load()Text1.Width = 4500 ' Set a minimum width for the TextBox.Slider1.Left = Text1.Left ' Align the Slider to the TextBox.' Match the width of the Slider to the TextBox.Slider1.Max = Text1.Width' Place the Slider a little below the Textbox.Slider1.Top = Text1.Top + Text1.Height + 50' Set TickFrequency to a fraction of the Max value.Slider1.TickFrequency = Slider1.Max * 0.1'SetLargeChange and SmallChange value to a fraction of Max.

Page 234: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Windows Common Controls MS Visual Basic 6 Programming Introduction

222 V0.1

Slider1.LargeChange = Slider1.Max * 0.1Slider1.SmallChange = Slider1.Max * 0.01

End Sub

Private Sub Slider1_Change()' If the slider is under 1/3 the size of the textbox, no change.' Else, match the width of the textbox to the Slider's value.If Slider1.Value > Slider1.Max / 3 Then

Text1.Width = Slider1.ValueEnd If

End Sub

EXAMPLE: Exploring Progressbar, Slider, UpDown Controls

In this exercise, you will create a Game Application that will demonstrate the use of Progressbar,Slider, and UpDown Controls.

Creating the form

1. Start a new Visual Basic project.

2. Add controls to the form, as shown in the following illustration.

Page 235: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction MS Windows Common Controls

V0.1 223

Control Property Setting

Form Name frmPbSldUd

' Caption Game of Concentration

Progressbar Name Pb

' Min 1

' Max 60

Slider Name Sld

' Min 1

' Max 60

' LargeChange 5

' SmallChange 1

Updown Name Ud

' Min 1

' Max 60

' Buddy Control txtNums

' Buddy Property Text

TextBox Name txtNums

Command Name cmdStart

' Caption Start

Command Name cmdHelp

' Caption Help

Label Name lblScore

At this point your form should look like this:

Writing Code

3. In the General Declarations of the form type the followings:

Page 236: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Windows Common Controls MS Visual Basic 6 Programming Introduction

224 V0.1

Option ExplicitDim i As Integer

Private Sub cmdHelp_Click() MsgBox "Press 'Start' to start a New game " & vbLf + vbLf _ & "A Dialog box asking Number of seconds you " & vbLf _ & "Wish to play will appear, enter no. of seconds. " & vbLf + vbLf _ & "Game is to observe the current value of the Slider " & vbLf _ & "And select that value in the TextBox." & vbLf + vbLf _ & "Among You whoever is getting more score is the winner."End Sub

Private Sub cmdStart_Click() On Error GoTo ErrHand If cmdStart.Caption = "Start" Then cmdStart.Caption = "Stop" i = InputBox("Enter How Many Seconds You Want to Play ") Pb.Max = i Label1 = i Timer1.Enabled = True Pb.Visible = True Label1.Visible = True Timer2.Enabled = True Else cmdStart.Caption = "Start" Timer1.Enabled = False Pb.Visible = False Label1.Visible = False Timer2.Enabled = False End If

ErrHand: MsgBox "Error - Quitting" Exit SubEnd Sub

Private Sub Timer1_Timer() If Pb = i Then Timer1.Enabled = False Timer2.Enabled = False Exit Sub End If Pb = Pb + 1 Label1 = Label1 - 1End Sub

Private Sub Timer2_Timer() If Sld = 60 Then Sld = 1 Sld = Sld + 1End Sub

Private Sub txtNums_Change()

Page 237: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction MS Windows Common Controls

V0.1 225

If txtNums = Sld Then lblScore = Val(lblScore) + 1 End IfEnd Sub

4. Save the Project and press F5 to run.

List View Control

The ListView control displays items using one of four different views. You can arrange items into

columns with or without column headings as well as display accompanying icons and text.

With a ListView control, you can organize list entries, called ListItem objects, into one of fourdifferent views:

♦ Large (standard) Icons

♦ Small Icons

♦ List

♦ Report

The View property determines which view the control uses to display the items in the list. Youcan also control whether the labels associated with items in the list wrap to more than one line

using the LabelWrap property. In addition, you can manage how items in the list are sorted andhow selected items appear.

The ListView control contains ListItem and ColumnHeader objects. A ListItem object defines the

various characteristics of items in the ListView control, such as:

♦ A brief description of the item.

♦ Icons that may appear with the item, supplied by an ImageList control.

♦ Additional pieces of text, called subitems, associated with a ListItem object that you candisplay in Report view.

You can choose to display column headings in the ListView control using the

HideColumnHeaders property. They can be added at both design and run time. At design time,you can use the Column Headers tab of the ListView Control Properties dialog box. At run time,use the Add method to add a ColumnHeader object to the ColumnHeaders collection.

TreeView Control

A TreeView control displays a hierarchical list of Node objects, each of which consists of a label

and an optional bitmap. A TreeView is typically used to display the headings in a document, the

Page 238: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Windows Common Controls MS Visual Basic 6 Programming Introduction

226 V0.1

entries in an index, the files and directories on a disk, or any other kind of information that might

usefully be displayed as a hierarchy.

After creating a TreeView control, you can add, remove, arrange, and otherwise manipulateNode objects by setting properties and invoking methods. You can programmatically expand and

collapse Node objects to display or hide all child nodes. Three events, the Collapse, Expand, andNodeClick event, also provide programming functionality.

You can navigate through a tree in code by retrieving a reference to Node objects using Root,

Parent, Child, FirstSibling, Next, Previous, and LastSibling properties. Users can navigatethrough a tree using the keyboard as well. UP ARROW and DOWN ARROW keys cycledownward through all expanded Node objects. Node objects are selected from left to right, and

top to bottom. At the bottom of a tree, the selection jumps back to the top of the tree, scrolling thewindow if necessary. RIGHT ARROW and LEFT ARROW keys also tab through expanded Nodeobjects, but if the RIGHT ARROW key is pressed while an unexpanded Node is selected, the

Node expands; a second press will move the selection to the next Node. Conversely, pressing theLEFT ARROW key while an expanded Node has the focus collapses the Node. If a user pressesan ANSI key, the focus will jump to the nearest Node that begins with that letter. Subsequent

pressings of the key will cause the selection to cycle downward through all expanded nodes thatbegin with that letter.

Several styles are available which alter the appearance of the control. Node objects can appear in

one of eight combinations of text, bitmaps, lines, and plus/minus signs.

The TreeView control uses the ImageList control, specified by the ImageList property, to store thebitmaps and icons that are displayed in Node objects. A TreeView control can use only one

ImageList at a time. This means that every item in the TreeView control will have an equal-sizedimage next to it when the TreeView control's Style property is set to a style which displaysimages.

EXAMPLE: Exploring List View and Tree View Controls

In this exercise, you will create an application to manage employee details and explore the use ofList View and Tree View controls.

Creating the form

1. Start a new Visual Basic project.

2. Add controls to the form, as shown in the follwing illustration.

Page 239: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction MS Windows Common Controls

V0.1 227

Control Property Setting

Form Name frmLv

' Caption List / Tree View Demo

ImageList Name IL1

' Size 32 * 32

ImageList Name IL2

' Size 16 * 16

List View Name Lv

' Large Icons IL1

' Small Icons IL2

Tree View Name Tv

' Image List 2

TabStrip Name SSTab1

' Tabs 2

TextBox Name txtEName

' Name txtSalary

' Name txtDeds

' Name txtAllws

ComboBox Name cboDesig

' List [Manager, Assistant,Clerk, Executive,Programer,Trainee]OptionButton

Name optView( )

' Index (0 - 3)

' Caption Icons, List, Small Icons,Report

OptionButton Name optArr( )

' Index (0 - 2)

' Caption None, Left, Top

Command Name cmdAdd

' Caption Add

Command Name cmdRemove

' Caption Remove

When you run your application your form should look like this:

Page 240: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Windows Common Controls MS Visual Basic 6 Programming Introduction

228 V0.1

Page 241: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction MS Windows Common Controls

V0.1 229

Writing Code

3. In the General Declarations of the form type the followings:

Option Explicit

Private Sub cmdAdd_Click() Static i As Integer i = i + 1 Lv.ListItems.Add i, "K" & i, txtEName, 1, 1 Lv.ListItems(i).SubItems(1) = cboDesig Lv.ListItems(i).SubItems(2) = txtSalary Lv.ListItems(i).SubItems(3) = txtDeds Lv.ListItems(i).SubItems(4) = txtAllws Lv.ListItems(i).SubItems(5) = Val(txtSalary) + Val(txtAllws) - Val(txtDeds) If cboDesig.ListIndex = 0 Then Tv.Nodes.Add "Mgr", tvwChild, , txtEName, 1 ElseIf cboDesig.ListIndex = 1 Then Tv.Nodes.Add "Ast", tvwChild, , txtEName, 1 ElseIf cboDesig.ListIndex = 2 Then Tv.Nodes.Add "Crk", tvwChild, , txtEName, 1 ElseIf cboDesig.ListIndex = 3 Then Tv.Nodes.Add "Exc", tvwChild, , txtEName, 1 ElseIf cboDesig.ListIndex = 4 Then Tv.Nodes.Add "Prg", tvwChild, , txtEName, 1 ElseIf cboDesig.ListIndex = 5 Then Tv.Nodes.Add "Trn", tvwChild, , txtEName, 1 End IfEnd Sub

Private Sub cmdRemove_Click() Lv.ListItems.Remove Lv.SelectedItem.IndexEnd Sub

Private Sub Form_Load() Tv.Nodes.Add , , "Main", "Designations", 3 Tv.Nodes.Add "Main", tvwChild, "Mgr", "Manager", 2 Tv.Nodes.Add "Main", tvwChild, "Ast", "Assistant", 2 Tv.Nodes.Add "Main", tvwChild, "Crk", "Clerk", 2 Tv.Nodes.Add "Main", tvwChild, "Exc", "Executive", 2 Tv.Nodes.Add "Main", tvwChild, "Prg", "Programer", 2 Tv.Nodes.Add "Main", tvwChild, "Trn", "Trainee", 2End Sub

Private Sub optArr_Click(Index As Integer) Lv.Arrange = IndexEnd Sub

Private Sub optView_Click(Index As Integer) Lv.View = IndexEnd Sub

4. Save the Project and press F5 to run.

Page 242: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Windows Common Controls MS Visual Basic 6 Programming Introduction

230 V0.1

ImageList Control

An ImageList control contains a collection of ListImage objects, each of which can be referred to

by its index or key. The ImageList control is not meant to be used alone, but as a centralrepository to conveniently supply other controls with images.

You can use the ImageList control with any control that assigns a Picture object to a Picture

property. For example, the following code assigns the first ListImage object in a ListImagescollection to the Picture property of a newly created StatusBar panel:

Dim pnlX As PanelSet pnlX = StatusBar1.Panels.Add() ' Add a new Panel object.Set pnlX.Picture = ImageList1.ListImages(1).Picture ' Set Picture.

Images of different sizes can be added to an ImageList control, but it constrains them all to be thesame size. The size of the ListImage objects is determined by one of the following:

♦ The setting of ImageWidth and ImageHeight properties before any images are added.

♦ The dimensions of the first image added.

At design time, you can add images using the General tab of the ImageList Control Propertiesdialog box. At run time, you can add images using the Add method for the ListImages collection.

Besides storing Picture objects, the ImageList control can also perform graphical operations on

images before assigning them to other controls. For example, the Overlay method creates acomposite image from two different images.

Example:

Use the ImageList Control to add a list of images to any container control.

Solution

1. Select the ImageList Control from the Microsoft Common Controls list and place thecontrol on the form.

2. Right click on the ImageList Control and choose properties. Select the images tab, anduse Insert Pictures to add 4 pictures (" bmp" or " ico" files).

3. Place a picture box on the form. Place 4 command buttons on the form.

4. Observe the following code:

Page 243: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction MS Windows Common Controls

V0.1 231

Option Explicit

Private Sub Command1_Click()Picture1.Picture = ImageList1.Overlay(1, 1)

End Sub

Private Sub Command2_Click()Picture1.Picture = ImageList1.Overlay(2, 2)End Sub

Private Sub Command3_Click()Picture1.Picture = ImageList1.Overlay(3, 3)

End Sub

Private Sub Command4_Click()Picture1.Picture = ImageList1.Overlay(4, 4)

End Sub

Page 244: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Windows Common Controls MS Visual Basic 6 Programming Introduction

232 V0.1

TabStrip Control

A TabStrip control is like the dividers in a notebook or the labels on a group of file folders. By

using a TabStrip control, you can define multiple pages for the same area of a window or dialogbox in your application.

Example: Write a VB application using TabStrip Control.

1. Select the TabStrip Control from the Microsoft Common Controls list and place thecontrol on the form.

2. Right click on the TabStrip Control and choose properties. Using the Insert tab choiceunder the Tab option, add 3 indexes.

3. Set the following:

Index Caption Tag

1 Department one

2 Items two

3 Branches three

4. Place three text boxes on the tab strip control.

5. Observe the following code:

Private Sub TabStrip1_Click()If TabStrip1.SelectedItem.Tag = "one" ThenText1.Text = "sales dept"Text2.Text = "purchase dept"Text3.Text = "admin dept"ElseIf TabStrip1.SelectedItem.Tag = "two" ThenText1.Text = "Key Board"Text2.Text = "Monitor"Text3.Text = "Hard Disk"ElseIf TabStrip1.SelectedItem.Tag = "three" ThenText1.Text = "Londoni"Text2.Text = "New York"Text3.Text = "Singapore"

End If

End Sub

Page 245: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

V0.1 233

OLE – Object Linking and Embedding

Objectives

In this Chapter, you will learn about OLE – Object Linking andEmbedding.

• OLE in Visual Basic

• OLE Terminology

• Inserting an OLE Object

• Inserting OLE Objects at Design Time

• Using Paste Special Method at Design Time

• Properties, Methods and Events of OLE Container Control

• Example of Object -> Insert Command

• Create Object Statement

• Get Object Statement

OLE (Object Linking & Embedding.)

OLE is a technique that acts as a bridge between Windows application to share / transfer Data. Ithelps Windows application to cooperate in manipulation and better presentation of Data. Eachwindow that supports OLE becomes a component of it.

OLE in Visual Basic

In Visual Basic, all the custom controls in the Tool Palette are linked through OLE 2.0. OLElessens programmer’s time and effort by integrating the features in many applications together

and provides an easy way to present Data. In Visual Basic the complexity of OLE is hidden byOLE container control.

Page 246: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

OLE - Object Linking and Embedding MS Visual Basic 6 Programming Introduction

234 V0.1

OLE Terminology

Container & Servers:

OLE interactions allow two Windows application known as Container & Severs. Any Windowsapplication that Exposes the Data Objects to one or more Windows application is called a OLEServer.

That application which receives or utilizes and controls the Data Objects supplied by the OLEServer is termed as the OLE Container.

OLE Objects

OLE Objects refers to the unit of Data that is involved in OLE interaction.

Linking and Embedding

In OLE it is only possible to either Link or Embed on an OLE Object to the OLE Container. Themain difference between Linking and Embedding is where the Data is Stored and whether otherapplications have access to it.

In both linking & Embedding the Data Object is displayed in the OLE container and can be editedusing the Server application.

Page 247: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction OLE - Object Linking and Embedding

V0.1 235

Embedding

A separate copy of the data object is created and stored along with the container application's

data file, any modifications made to the data object through the Server application is not reflectedin the Container applications object.

Linking

The Data Object is stored as a part of the Server applications data file and only a link is setbetween the object in the Server application and the container application .The Containerapplication only stores the link information along with it and not the copy of the data object. So

there is no separate copy of the data object created and the data object is shared between the twoapplications thus making modifications done to the object through Server application reflect inthe Container application.

Inserting an OLE Object :

OLE Objects can be inserted in three methods. Linking & Embedding apply to all these threemethods.

Paste Special Method:

This is possible only if a valid OLE Object is present in the clipboard. The OLE Object canbe copied from any server application to the clipboard

Create New Object Method:

By just specifying the name of the server application & using the command and tools of it, objectscan be created. In this method Linking is not possible.

Create Object from Existing one:

By just specifying the server application and the filename the object can be created. Bothembedding and Linking is possible.

Page 248: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

OLE - Object Linking and Embedding MS Visual Basic 6 Programming Introduction

236 V0.1

Inserting OLE Objects at Design Time

To Insert a OLE Object at Design Time perform the following steps:

Step 1: Place an OLE container control on the form.

Step 2: Visual Basic will automatically display the Insert Object dialog box.

Step 3: To create a blank Object, select a type of object from list, then click OK button.Step 4: The Server application associated with the selected object will start and a blank object willbe displayed in the OLE control. Use the applications command and tools to work and then clickoutside to return to VB.

Step 5: To insert an object from an existing file, choose CREATE FROM FILE option fromINSERT OBJECT dialog box. To Link, click the LINK option

Page 249: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction OLE - Object Linking and Embedding

V0.1 237

Using Paste Special method at Design Time

To use Paste special method at design time, perform the following steps

Step 1: Place an OLE Control on the form.

Step 2: Start the server application and select the data that has to be linked or embedded.

Step 3: In the server application select CUT from the EDIT menu.

Step 4: Switch to VB.

Step 5: Right click on OLE control and select PASTE SPECIAL from the menu.

Step 6: Select the PASTE option to embed the object or PASTE LINK to link the object.

Step 7: Click OK button.

Page 250: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

OLE - Object Linking and Embedding MS Visual Basic 6 Programming Introduction

238 V0.1

Properties, Methods and Events of OLE ContainerControl

The most salient feature of the OLE is automatic updating of linked control from both thedirections. The necessity of using this method depends on the update options property of theOLE container control. The possible settings of this property are

0--Automatic(default) The OLE Control is updated whenever the linked data changes.

1—Frozen The OLE Control is updated whenever the user saves the linked datafrom within the server application.

2--Manual The OLE Client

These properties are available only to the linked objects and not to the embedded objects.

Example of Object –> Insert Command

This example illustrates how a user can select the Object => Insert command to display the InsertObject dialog box. Use this dialog box to insert a new object or an object from an existing file. TheObject when activated displays the server applications menu, enabling the user to edit the objectfrom the VB program. The object can be deactivated through pressing ESC key.

After inserting the object, use the FILE => SAVE command to save the object to disk under apredefined filename. The OBJECT => DELETE command enables the user to delete the object inthe OLE control and later insert another object as desired.

Page 251: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction OLE - Object Linking and Embedding

V0.1 239

Code in Form Module:

Option explicit:Const OLE_Embedded =1 'Constant for OLE Object typeConst File_Name ="OLE_DEMO.DAT" 'Constant for OLE File Name'Global VariablesDim DataSaved ,ObjectPresent as Boolean

Code in Form Load Event

Dim Filenum as Long ,Reply as IntegerObjectPresent = False

DataSaved = True

' To check for existence of OLE Data file , if present give option to load it

If Dir$(File_Name)<>"True"Reply = Msgbox ("load OLE Data file from disk ",VByesno + Vb Question,"Load Object"If Reply = VbYes then

Screen.MousePointer =11

Page 252: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

OLE - Object Linking and Embedding MS Visual Basic 6 Programming Introduction

240 V0.1

filenum = FreeFileopen File_name for Binary as # FilenumOLE1.ReadFromFile FileNumObjectPresent = TrueClose # FIleNumScreen.MousePointer = 0

End If

End If

Code in Form Resize Event

'Size the OLE control to the form SizeOLE1.move 0,0 Form1.ScaleWidth,Form1.ScaleHeight

Code in File Menu Click

'Enable the save command if and only if the object is present in the OLE control

if ObjectPresent = TruemnuFileSave.Enabled = True

elseMnuFileSave.Enabled = False

End If

Code in File => Exit Click

Dim Reply as integerif not DataSaved thenReply = Msgbox ("Save the OLE Object " .VbYesNo + Vb Question ,"Save _

Object")If Reply = VbYes then

Call SaveObjectElseExit Subend if

end if

Code in File => Save click

Call SaveObject

Code In Object => Insert Object Click

Dim Reply as integerIf ObjectPresent = True then

Reply = Msgbox (" Delete Current Object ")Exit Sub

Else

Page 253: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction OLE - Object Linking and Embedding

V0.1 241

Call MenuDelete_ClickEnd ifOLE1.OLETpeAllowed = OLE_EmbeddedForm1.OLE1.InsertObjDigObjectPresent = TrueDataSaved =FalseScreen.MousePointer = 0

Code In Menu Object click

if ObjectPresent thenmnuDelete = True

ElsemnuDelete = F;ase

End if

Code in OLE_DblClick

DataSaved = Flase

Code in OLE_Updated

DataSaved = False

Code in mnu Delete_click

Dim Reply as integer

If Not DataSaved thenReply = Msgbox ("Save before Quitiing")

Exit SubEnd If

Call SaveObject

OLE1.DeleteObjectPresent = FalseDataSaved = True

Code in SaveObject

Dim Filenum as IntegerFilenum = FreefileOpen FileName for Binary As # FilenumOLE!.FileNumber = Filenum

Page 254: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

OLE - Object Linking and Embedding MS Visual Basic 6 Programming Introduction

242 V0.1

OLE1.SavetoFIle FileNumDartSaved = TrueClose #Filenum

Example

Write an application where an OLE control is used to activate a calendar control.

• Open the project.

• Drag and Drop the OLE Control on the form.

• A dialog appears on the form having two options. One to create new and the other tocreate from file. Select the Calendar Control from the list and click on the OK button.

• Press F5 to run.

Page 255: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction OLE - Object Linking and Embedding

V0.1 243

Create Object Statement

Write an application to dynamically load an MS Excel application to the form while the form is

activated.

1. Open the project.

2. Go to the reference dialog box and select Microsoft Excel Object Library 8.0.

3. Write the following code in the general declaration of the form.

This code starts the application creating the object, in this case, a Microsoft Excel spreadsheet.Once an object is created, you reference it in code using the object variable you defined. In the

following example, you access properties and methods of the new object using the objectvariable, ExcelSheet, and other Microsoft Excel objects, including the Application object and theCells collection.

Dim xlApp As Excel.ApplicationDim xlBook As Excel.WorkbookDim xlSheet As Excel.WorkSheet

Private Sub Form_Load()Set xlApp = CreateObject("Excel.Application")Set xlBook = xlApp.Workbooks.AddSet xlSheet = xlBook.Worksheets(1)

ExcelSheet.Application.Visible = TrueExcelSheet.Cells(1, 1).Value = "This was tested by innovation software solutions"ExcelSheet.SaveAs "C:\ TEST.DOC"ExcelSheet.Application.QuitEnd Sub

Private Sub Form_Unlaod()Set ExcelSheet = NothingEnd Sub

Page 256: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

OLE - Object Linking and Embedding MS Visual Basic 6 Programming Introduction

244 V0.1

Get Object Statement

Write an application to dynamically load a MS Word application to the form while the form is

activated.

1. Open the project.

2. Go to the reference dialog box and select Microsoft Word Object Library 8.0.

3. Write the following code in the general declaration of the form and run the form.

This code starts the application creating the object, in this case, a Microsoft Word . Once an objectis created, you reference it in code using the object variable you defined.

Dim wdApp As Word.Application

Private Sub Form_Load()Set wdApp = GetObject("", "Word.Application") wdApp.visible = trueEnd Sub

Private Sub Form_Unload()Set wdApp = Nothing

End Sub

Example:

Load a BMP file in the OLE control and modify it at run time to illustrate that Visual basicProgram can be used as a front-end application.

Page 257: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction OLE - Object Linking and Embedding

V0.1 245

Solution

• Open a new project and save it.

• Add an OLE control to the form, which displays an Insert Object Dialog Box.

• Select the Create from file option. Click on the Browse button, which displays a Browsedialog box.

• Select the desired file and click on the OK Button.

• Run the VB application by pressing F5 . Double click on the OLE Control.

The PaintBrush application is loaded on to the screen. Make the desired changes in thePaintBrush and select the Exit option from the File menu. Note that these changes are reflected inthe OLE control as well.

Example:

Using OLE, try to load the Windows WRITE application.

Page 258: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

OLE - Object Linking and Embedding MS Visual Basic 6 Programming Introduction

246 V0.1

Solution

• Open a new project and save it.

• Change the Caption property of the Form to OLE Application and the Caption propertyof the CommandButton to Write.

• Add an OLE Control to the form, which displays an Insert Object Dialog Box.

• Click on the cancel button.

• Enter the following Code in the Command_Click procedure.

Private Sub Comand1_Click( )OLE1.CreateLink "write.exe"

End Sub

Run the application by pressing F5 . Click the Write Button which places the WRITE.EXE in the

Control.

Double click on the OLE Control. This loads the WRITE application and you can create necessarywrite text files or modify existing files and save the same.

Page 259: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

V0.1 247

Data Reports

Objectives

In this Chapter, you will learn about Data Reports in Visual Basic.

• Features of Data Report Designer

• Data report Control

• Adding a Data Environment

• Property Tab of Command Object

• Creating a Simple Data Report

• Calling a Data Report through Form

• Calling a Data Report using Master Detail Relationship

• Data Report Events

• Data Report Methods

• Exporting a Report using Object Key

Data Report in Microsoft Visual Basic 6.0

The Microsoft Data Report designer is a versatile data report generator that features the ability tocreate hierarchical reports. Used in conjunction with a data source such as the Data Environmentdesigner, you can create reports from several different relational tables. To create data report in

VB6.0 use the Data Environment designer.

Features of Data Report Designer

The Data Report designer has several features:

Drag-and-Drop Functionality for Fields—Drag fields from the Microsoft Data Environment

designer to the Data Report designer. When you do this, Visual Basic automatically creates a textbox control on the data report and sets the DataMember and DataField properties of the droppedfield. You can also drag a Command object from the Data Environment designer to the Data

Report designer. In that case, for each of the fields contained by the Command object, a text boxcontrol will be created on the data report; the DataMember and DataField property for each textbox will be set to the appropriate values.

Page 260: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Data Reports MS Visual Basic 6 Programming Introduction

248 V0.1

Toolbox Controls —The Data Report designer features its own set of controls. When a Data

Report designer is added to a project, the controls are automatically created on a new Toolbox tabnamed DataReport. Most of the controls are functionally identical to Visual Basic intrinsiccontrols, and include a Label, Shape, Image, TextBox, and Line control. The sixth control, the

Function control, automatically generates one of four kinds of information: Sum, Average,Minimum, or Maximum.

Print Preview—Preview the report by using the Show method. The data report is then generated

and displayed in its own window.

Print Reports—Print a report programmatically by calling the PrintReport method. When thedata report is in preview mode, users can also print by clicking the printer icon on the toolbar.

File Export—Export the data report information using the ExportReport method. Formats forexport include HTML and text.

Export Templates—You can create a collection of file templates to be used with the ExportReport

method. This is useful for exporting reports in a variety of formats, each tailored to the reporttype.

Asynchonous Operation—The DataReport object's PrintReport and ExportReport methods are

asynchronous operations. Using the ProcessingTimeout event, you can monitor the state of theseoperations and cancel any that are taking too long.

Data Report Controls

When a new Data Report designer is added to a project, the following controls are automaticallyplaced in the Toolbox tab named DataReport:

TextBox Control (RptTextBox)—allows you to format text, or assign a DataFormat.

Label Control (RptLabel)—allows you to place labels on the report to identify fields or sections.

Page 261: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Data Reports

V0.1 249

Image Control (RptImage)—enables you to place graphics on your report. Note that this control

cannot be bound to a data field.

Line Control (RptLine)—lets you draw rules on the report to further distinguish sections.

Shape Control (RptShape)—enables you to place rectangles, triangles, or circles (and ovals) on a

report.

Function Control (RptFunction)—a special text box that calculates values as the report isgenerated.

Adding a Data Environment

At design time, you can use the Data Environment designer to create a DataEnvironment object.

The DataEnvironment object can include Connection and Command objects, hierarchies(relationships between Command objects), groupings, and aggregates.

Before you can access the Data Environment designer, you must reference it in Visual Basic.

To reference the Data Environment designer:

• From the Project menu, select References

• From the References dialogue box, select Data Environment 1.0, and then click OK

To add a Data Environment designer object to a new Visual Basic project :

• Create a new Standard EXE project

• From the Project menu, choose Add Data Environment.

The new Data Environment designer is added to your Visual Basic project, this designer windowappears with a Connection object. To connect with database, select connection and right click forconnection properties and choose your data provider from the data provider list. (Refer the givenbelow picture)

Page 262: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Data Reports MS Visual Basic 6 Programming Introduction

250 V0.1

After choosing the data provider, click on next to get another property tab called Connection.For Use data source name property, select your user data source name and fill user name andpassword according to your data source. Then Click on Test Connection to verify your datasource name, user name and password.

After making connection with database, add a command object (refer given below picture) toexecute your valid SQL statements.

Page 263: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Data Reports

V0.1 251

After adding a command object, choose properties of that command to select our database object(i.e. stored procedure or table or view or synonym).

There are two ways in which you can get rows from table/view/synonym.

You can set Database object property as table/view/synonym , and Object name property astable/view/synonym name. [refer the picture given below].

Alternatively, you can enter valid select statements. [refer the picture given below].

Page 264: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Data Reports MS Visual Basic 6 Programming Introduction

252 V0.1

Property Tab of Command Object

Now we will discuss about other property tab of command object.

Parameters

This collection which can contain list of parameters which can be created by user. We can passone or more than one parameters for our valid select statements or stored procedures. (Seepicture1 and picture2). Also we can set initial value for passing parameters while design timeitself in the property of Value.

Picture1

Page 265: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Data Reports

V0.1 253

Picture2

Relation

This property tab enables us to present the data with master detail relationship. We can makerelationship between master and detail tables through Relation Definition.

Grouping

This property tab enables us to present the data group-wise. We can make any group against thetable/view/synonym column(s).

Aggregates

Using this property tab, we can use some aggregate functions like sum, min, max, etc.

Advanced

Using this property tab, we can set cursor and locking type, cursor location, cache size,command timeout and maximum records.

Page 266: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Data Reports MS Visual Basic 6 Programming Introduction

254 V0.1

Creating a Simple Data Report

Till that we have learnt how add a data environment and set its properties, let us create a simple

report from a table called customer.

The SQL statement is

select customer_id, name, phone_number, credit_limit from customer

Add a data report (through Project option in the standard menu bar in visual basic 6.0). Set dataenvironment name in Data Source property of the data report and set command name in Data

Member property of data report.

(Example Data Source=Data Environment1 Data Member=Command1).

Now, place four RptTextBox contols in details part of the data report. We can display proper titleinformation and footer information in the report by adding RptLabel controls in Report Header,Page Header, Report Footer and Page Footer parts of data report. The data format of controls isused to change the Format and type of text1 content according to table columns. Set the DataMember and Data Field property for four RptText Boxes.

For Text1

Data Member = Command1 Data Field =CUSTOMER_ID

Page 267: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Data Reports

V0.1 255

For Text2

Text2.Data Member = Command1 Text2.Data Field =NAME

For Text3

Data Member = Command1 Data Field =PHONE_NUMBER

For Text4

Data Member = Command1Data Field =CREDIT_LIMIT

Page 268: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Data Reports MS Visual Basic 6 Programming Introduction

256 V0.1

Running the Report

In General Tab of project properties, set Start up project as Data Report1. Press F5 to run your

application.

Now you would get the reports as shown below:

To pass the data report to printer click on the printer icon .

To Export the above report to HTML file click on the export icon.

Calling a Data Report through Form

To call the above data report through form, add a form through Addform property of Project in

standard menu bar and place a command button named command1 in the form.

Write the following the code in the event of click for command1

Private Sub Command1_Click() DataReport1.Show

End Sub

Page 269: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Data Reports

V0.1 257

Then press F5 , click on Command1.

Now you can get the reports as given below

Creating a data report using master details relationship

Add a data environment in your application and set its connection properties. After making the

connection with database successfully, add two command objects named Dept_cmd andEmp_cmd through properties of connection.

For Dept_cmd command Object, the SQL statement is

Select * from Dept

For Emp_cmd command Object, the SQL statement is

Select empno,ename,deptno,sal,job from emp

Select properties of Emp_cmd, and set the Relation properties (as given below) and press OK.

Page 270: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Data Reports MS Visual Basic 6 Programming Introduction

258 V0.1

Now the Dept_cmd and Emp_cmd objects have the details as follows.

Add a data report through the project property of standard menu bar. Right click the mouse indata report and select Insert Group Header/Footer to add one group header part.

Page 271: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Data Reports

V0.1 259

Add one group header part in data report2 and set the Data Source property of Data report1 asData Environment1 and Data Member property Data report1 as Dept_cmd.

Fill the group header part by dragging all available columns from Dept_cmd object and fill theDetail part of data report by dragging all available columns from Emp_cmd command object.

Page 272: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Data Reports MS Visual Basic 6 Programming Introduction

260 V0.1

Press F5 to get the master detail report as given below:

Page 273: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Data Reports

V0.1 261

Data Report Events

Event Description

Initialize Occurs after the query has completed, and controlsare sited on the form.

Resize Occurs when the designer is first displayed or whenthe window state of an object changes.

Activate Occurs when the designer becomes the activewindow.

ProcessingTimeout Occurs approximately once every second until allprocessing has ended. Use this event to determine ifprocessing has taken too long, and to cancel theprocessing. Note: This event will not occur until thequery has completed. See below.

Deactivate Occurs when the designer is no longer the activewindow. Use this event to determine if the user hasclicked another form or designer.

QueryClose Occurs before the designer is terminated. Set theCancel argument to True to cancel termination. TheCloseMode argument returns the type of action that iscausing the termination.

Terminate Occurs when all references to the designer havebeen set to 0.

Data Report Methods

Exporting a Data Report

The ExportReport method is used to export any report as a text file or as an HTML file. Thismethod does not support the exporting of images or graphic shapes.

ExportFormat Objects

The ExportReport method is designed to work with the ExportFormats collection. EachExportFormat object in the collection represents a separate format for the report.

Four Default ExportFormat Objects

By default, the ExportFormats collection contains four members. The four members and theirassociated file filters are shown below:

Page 274: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Data Reports MS Visual Basic 6 Programming Introduction

262 V0.1

Object File Filter Description

ExportFormats(1) *.htm, *.html HTML

ExportFormats(2) *.htm, *.html Unicode HTML

ExportFormats(3) *.txt Text

ExportFormats(4) *.txt Unicode Text

The key property values are used to specify a default type. By setting one of the following fourmembers, you can export a report.

Object Key Constant

ExportFormats(1) key_def_HTML RptKeyHTML

ExportFormats(2) Key_def_UnicodeHTML_UTF8 rptKeyUnicodeHTML_UTF8

ExportFormats(3) key_def_Text RptKeyText

ExportFormats(4) key_def_UnicodeText RptKeyUnicodeText

Page 275: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Data Reports

V0.1 263

Exporting a Report using Object key

The syntax for the ExportReport method is:

object.ExportReport(ExportFormat, filename, Overwrite, ShowDialog, Range,PageFrom, PageTo)

The ExportReport method syntax has these parts:

Part Description

object An object expression that evaluates to an object in the AppliesTo list.

ExportFormat

The ExportFormat object to be used. The argument can be anobject reference, or a string key that specifies one of themembers of the ExportFormats collection as shown in Settings. Ifnot specified, the Export dialog box will be displayed.

filename A string expression that evaluates the name of the file. If notspecified, the Export dialog box will be displayed.

overwrite A boolean expression that determines if the file will beoverwritten.

ShowDialog

A boolean expression that determines if the Save As dialog boxwill be displayed. If no ExportFormat object or filename isspecified, the Export dialog box will be displayed, even if thisargument is set to False.

Range Sets an integer that determines if all the pages in the report, or arange of pages will be exported.

PageFrom A numeric expression that specifies the page where the exportwill start.

PageTo A numeric expression that specifies the page where the exportwill end.

After preparing the datareport, name it as datareport1. Add a form through Project properties ofstandard menu bar and place a command button in that form. Set the name property of thecommand button as Export_Rpt.

Write the following the code in the click event of Export_Rpt command button and then press F5

to run.

private sub Export_Rpt_click()DataReport1.ExportReport rptKeyText, "C:\Reports\Sale_report", True, ,_rptRangeAllPagesEnd Sub

Now your report details will be saved in the file named C:\Reports\Sale_report.txt.

Page 276: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Data Reports MS Visual Basic 6 Programming Introduction

264 V0.1

Printing a Data Report

The syntax for the PrintReport method is:

object.PrintReport(ShowDialog, Range, PageFrom, PageTo)

Part Description

object Required. An object expression that evaluates to an objectin the Applies To list.

ShowDialog A boolean expression that determines if the Print dialog boxis shown.

Range Sets an integer that determines if all the pages in the reportor a range of pages will be printed.

PageFrom An integer that sets the page from which to start printing.

PageTo An integer that sets the page at which to stop printing.

Example:

After preparing the datareport, name it as datareport2. Add a form through Project properties ofstandard menu bar and place a command button in that form. Change the name property of thecommand button as Print_Rpt.

Write the following the code in the click event of Print_Rpt command button and then press F5

to run.

Private Sub Print_Rpt_click() DataReport2.PrintReport False, rptRangeAllPagesEnd Sub

The above example prints the report without displaying the dialog box.

Page 277: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

V0.1 265

Advanced ActiveX Controls & WIN API

Objectives

In this Chapter, you will learn about some Advanced ActiveX controlslike Animation Control, Winsock Control, Internet /Transfer Control and Web Browser Control. You will alsolearn about accessing the Microsoft Windows API inVisual Basic.

• Animation Control

• Winsock Control

• Internet / Transfer Control

• Web Browser Control

• Accessing the Microsoft Windows API in VB

• WIN API Example: Locating the Windows Folder

• WIN API Example: Creating a top most window

Advanced ActiveX Controls:

Animation Control

The Animation control allows you to create buttons which display animations, such as .avi files,

when clicked. The control can play only AVI files that have no sound. In addition, the Animationcontrol can display only uncompressed.avi files or .avi files that have been compressed usingRun-Length Encoding (RLE).

Example

Write an application having a form and an animation control on the form.

• Open a project.

• Add an Animation control and two command buttons on the form by dragging andplacing the controls on the form.

• Write the following code and then press F5 to run the program.

Page 278: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Advanced ActiveX Controls & WIN API MS Visual Basic 6 Programming Introduction

266 V0.1

Private Sub Command1_Click()Animation1.Open ("c:\winnt\clock.avi")Animation1.PlayEnd Sub

Private Sub Command2_Click()Animation1.StopEnd Sub

Winsock Control

The Winsock control, invisible to the user, provides easy access to TCP and UDP networkservices. To write client or server applications you do not need to understand the details of TCPor to call low level Winsock APIs. By setting properties and invoking methods of the control, you

can easily connect to a remote machine and exchange data in both directions.

TCP Basics

The Transfer Control Protocol allows you to create and maintain a connection to a remotecomputer. Using the connection, both computers can stream data between themselves.

If you are creating a client application, you must know the server computer's name or IP address(RemoteHost property), as well as the port (RemotePort property) on which it will be "listening."Then invoke the ‘Connect method’.

If you are creating a server application, set a port (LocalPort property) on which to listen, andinvoke the ‘Listen method’. When the client computer requests a connection, theConnectionRequest event will occur. To complete the connection, invoke the ‘Accept method’within the ConnectionRequest event.

Once a connection has been made, either computer can send and receive data. To send data,invoke the ‘SendData method’. Whenever data is received, the DataArrival event occurs. Invokethe ‘GetData method’ within the DataArrival event to retrieve the data.

Page 279: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Advanced ActiveX Controls & WIN API

V0.1 267

UDP Basics

The User Datagram Protocol (UDP) is a connectionless protocol. Unlike TCP operations,computers do not establish a connection. Also, a UDP application can be either a client or aserver.

To transmit data, first set the client computer's LocalPort property. The server computer thenneeds only to set the RemoteHost to the Internet address of the client computer, and theRemotePort property to the same port as the client computer's LocalPort property, and invokethe SendData method to begin sending messages. The client computer then uses the GetDatamethod within the DataArrival event to retrieve the sent messages.

Example

Write a sample application using Winsock control to communicate between the server and theclient.

To create a TCP server

• Create a new Standard EXE project.

• Change the name of the default form to frmServer.

• Change the caption of the form to "TCP Server."

• Place a Winsock control on the form and change its name to tcpServer.

• Add two TextBox controls to the form. Name the first txtSendData, and the secondtxtOutput.

• Add the following code:

Private Sub Form_Load()' Set the LocalPort property to an integer.' Then invoke the Listen method.tcpServer.LocalPort = 1001tcpServer.ListenfrmClient.Show ' Show the client form.End Sub

Private Sub tcpServer_ConnectionRequest _(ByVal requestID As Long)‘ Check if the control's State is closed. If not,' close the connection before accepting the new' connection.If tcpServer.State <> sckClosed Then _tcpServer.Close' Accept the request with the requestID' parameter.tcpServer.Accept requestIDEnd Sub

Page 280: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Advanced ActiveX Controls & WIN API MS Visual Basic 6 Programming Introduction

268 V0.1

Private Sub txtSendData_Change()' The TextBox control named txtSendData' contains the data to be sent. Whenever the user' types into the textbox, the string is sent' using the SendData method.tcpServer.SendData txtSendData.TextEnd Sub

Private Sub tcpServer_DataArrival _(ByVal bytesTotal As Long)' Declare a variable for the incoming data.' Invoke the GetData method and set the Text' property of a TextBox named txtOutput to' the data.Dim strData As StringtcpServer.GetData strDatatxtOutput.Text = strDataEnd Sub

The above creates a simple server application. However, to complete the scenario, you must alsocreate a client application.

To create a TCP client

• Add a new form to the project, and name it frmClient.

• Change the caption of the form to TCP Client.

• Add a Winsock control to the form and name it tcpClient.

• Add two TextBox controls to frmClient. Name the first txtSend, and the secondtxtOutput.

• Draw a CommandButton control on the form and name it cmdConnect.

• Change the caption of the CommandButton control to Connect.

• Add the code below to the form.

Be sure to change the value of the RemoteHost property to the friendly name of your computer.

Private Sub Form_Load()' The name of the Winsock control is tcpClient.' Note: to specify a remote host, you can use' either the IP address (ex: "121.111.1.1") or' the computer's "friendly" name, as shown here.tcpClient.RemoteHost = "RemoteComputerName"tcpClient.RemotePort = 1001End Sub

Page 281: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Advanced ActiveX Controls & WIN API

V0.1 269

Private Sub cmdConnect_Click()' Invoke the Connect method to initiate a' connection.tcpClient.ConnectEnd Sub

Private Sub txtSendData_Change()tcpClient.SendData txtSend.TextEnd Sub

Private Sub tcpClient_DataArrival _(ByVal bytesTotal As Long)Dim strData As StringtcpClient.GetData strDatatxtOutput.Text = strDataEnd Sub

Page 282: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Advanced ActiveX Controls & WIN API MS Visual Basic 6 Programming Introduction

270 V0.1

Internet/Transfer Control

The Internet Transfer control provides implementation of two of the most widely used protocols

on the Internet, HyperText Transfer Protocol (HTTP) and File Transfer Protocol (FTP).

With the HTTP protocol, you can connect to World Wide Web servers to retrieve HTMLdocuments. With the FTP protocol, you can log on to FTP servers to download and upload files.

The UserName and Password properties allow you to log on to private servers that requireauthentication. Otherwise, you can connect to public FTP servers and download files. FTPcommands, CD and GET, are supported through the Execute method.

Example

This example show the working principles of Internet transfer control where a Internet page isopened along with a password and username

• Open a project.

• Add the internet transfer control and a command button on the form.

• Write the following code and then press F5 to run.

Private Sub Command1_Click()Inet1.URL = "https://csn.emea.compaq.com/CSN/login.asp"Inet1.Password = "plus"Inet1.UserName = "user"End Sub

Page 283: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Advanced ActiveX Controls & WIN API

V0.1 271

Web Browser Control

Using the Web Browser Control, developers can access examples from a common code repository

deployed internally as HTML pages, or use their Internet access to reach third partyprogramming sites.

Write an application, which uses the web browser control to open a web page.

• 1. Open a project.

• 2. Add the web browser control and a command button on the form.

• 3. Write the following code and then press F5 to run.

Private Sub Command1_Click()WebBrowser1.Navigate ("http://www.InnovationSoftware.com")

End Sub

Page 284: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Advanced ActiveX Controls & WIN API MS Visual Basic 6 Programming Introduction

272 V0.1

Accessing the Microsoft Windows API

You can gain access to the Windows API (or other outside DLLs) by declaring the external

procedures within your Visual Basic application. After you declare a procedure, you can use itlike any other language feature in the product.

The most commonly used set of external procedures are those that make up Microsoft Windows

itself. The Windows API contains thousands of functions, subs, types, and constants that you candeclare and use in your projects. These procedures are written in the C language, however, sothey must be declared before you can use them with Visual Basic. The declarations for DLL

procedures can become fairly complex. While you can translate these yourself, the easiest way toaccess the Windows API is by using the predefined declares included with Visual Basic.

The file Win32api.txt, located in the \Winapi subdirectory of the main Visual Basic directory,

contains declarations for many of the Windows API procedures commonly used in Visual Basic.To use a function, type, or other feature from this file, simply copy it to your Visual Basicmodule. You can view and copy procedures from Win32api.txt by using the API Viewer

application, or by loading the file in any text editor.

Using the API Viewer Application

The API Viewer application enables you to browse through the declares, constants, and typesincluded in any text file or Microsoft Jet database. After you find the procedure you want, you

can copy the code to the Clipboard and paste it into your Visual Basic application.

To view an API file

• From the Add-Ins menu, open the Add-In Manager and load API Viewer.

• From the Add-Ins menu, select API Viewer

• Open the text or database file you want to view.

• To load a text file into the viewer, click File -> Load Text File and choose the file youwant to view. (Example Win32api.txt)

OR

• To load a database file, click File -> Load Database File . (Example Win32api.mdb).

• Select the type of item you want to view from the API Types list.

Page 285: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Advanced ActiveX Controls & WIN API

V0.1 273

To add procedures to your Visual Basic code

• Click the procedure you want to copy in the Available Items list.

• Click Add. The item appears in the Selected Items list.

• Indicate the scope of the item by clicking Public or Private in the Declare Scope group.

• To remove an entry from the Selected Items list box, click the item and click Remove.

• To remove all entries from the Selected Items list box, click Clear.

To copy the selected items to the clipboard

• Click Copy. All of the items in the Selected Items list will be copied.

• Open your Visual Basic project and go to the module in which you want to place the APIinformation.

• Position the insertion point where you want to paste the declarations, constants, and / ortypes, and then choose Edit / Paste .

Viewing the Win32api.txt file with a Text Editor

You can also load the Win32api.txt file in a text editor, such as Microsoft Word or Word Pad, tolocate the procedures you want to use. Again, you just copy the procedures from the file to a

Visual Basic module to use them in your application.

WIN API Example: Locating the Windows Folder

In this exercise, you will use the Windows API function GetWindowsDirectory to find the folderthat contains Microsoft Windows.

Create a form

• Create a new Standard EXE project.

• Save the project.

• Add controls to the form, as shown below.

Page 286: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Advanced ActiveX Controls & WIN API MS Visual Basic 6 Programming Introduction

274 V0.1

Declare a procedure

• Add a standard module to the project

• From the API Viewer, copy the GetWindowsDirectory Declare statement

• Paste the Declare statement into the new module

Create an event procedure

• Create a Click event procedure for the Windows Directory button.

• In the event procedure, add code that will display the path to the Windows folder in amessage box.

Observe the CODE:

'DLL DeclarationsDeclare Function GetWindowsDirectory Lib "kernel32" _ Alias "GetWindowsDirectoryA" (ByVal lpBuffer As String, _ ByVal nSize As Long) As Long

Private Sub cmdWinDir_Click() Dim WinDir As String Dim ReturnSize As Long WinDir = String(255, 0) 'fill string w/nulls 'call API to get win directory and capture the 'size of the return string ReturnSize = GetWindowsDirectory(lpBuffer:=WinDir, _ nSize:=Len(WinDir)) 'trim the string down to the correct size WinDir = Left(WinDir, ReturnSize) MsgBox "The Windows directory is: " & WinDirEnd Sub

• Save and test the project

WIN API EXAMPLE: Creating a Topmost Window

In this exercise, you will use the Windows API function SetWindowPos to create a window orform that remains on top of other windows, regardless of the current focus.

• Create a new project.

• Save the project.

• Add controls to the form, as shown below:

Page 287: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Advanced ActiveX Controls & WIN API

V0.1 275

• Create event procedures for the Topmost window and Non-topmost window optionbuttons

Observe the CODE:

Private Sub optNonTopmost_Click()

SetWindowPos frmtopmost.hwnd, _ HWND_NOTOPMOST, 0, 0, 0, 0, FLAGS

End SubPrivate Sub optTopmost_Click()

SetWindowPos frmtopmost.hwnd, _ HWND_TOPMOST, 0, 0, 0, 0, FLAGS

End Sub

• Save and test the application

Page 288: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Advanced ActiveX Controls & WIN API MS Visual Basic 6 Programming Introduction

276 V0.1

Notes

Page 289: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

V0.1 277

Validating Input and Handling Errors

Objectives

In this chapter , you will learn about Tools for Debugging, ValidatingField Information, Validating Form Information, Using theQueryUnload Event and Handling run-time Errors.

• Tools for Debugging

• Validating Field Information

• Validating form Information

• Using the QueryUnload Event

• Handling run-time Errors

• Err Object Properties

• Disabling Error Handling

• Compiling an Application

Validating Input and Handling Errors

As you develop VB applications, it is important to debug code and to handle any errors thatmight occur. It is also important to prevent as many of these errors as possible by validatinginput to our application.

Tools for Debugging

VB provides interactive tools for finding run-time errors and errors in program logic. We canaccess all of the debugging tools by using the Debug menu or the Debug tool bar.

VB debugging support includes:

♦ Break Points and break expressions

♦ Watch expressions

♦ Step options

♦ Call Stack

♦ Immediate Window

Page 290: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Validating Input and Handling Errors MS Visual Basic 6 Programming Introduction

278 V0.1

♦ Locals Window

Break Points and break expressions

Set a breakpoint to stop a program while it is running. We can set a breakpoint at design time orat run time while in break mode

Watch expressions

Use watch expressions to monitor a particular variable or expression. The value of each watchexpression is updated at breakpoints.

Step options

Use the step options to run portions of our code either one statement or one procedure at a time.

Call Stack

Use the Call stack to view all active procedure calls and trace the execution of series of nestedprocedures.

Immediate Window

In break mode, we can test an executable statement by typing it in the immediate window. VBruns the statement immediately so that we can evaluate our code.

Locals Window

This window automatically displays all of the declared variables in the current procedure, alongwith their values.

Validating Field Information

Some data entry errors can be prevented and the usability of the application improved byvalidating information at field level as it is entered. Field validation options include:

Restricting Choices with Controls

One way to ensure valid input is to restrict the number of options from which a user can choose.For example, we can use a list box to let users select a product name on a form, because usersmust choose from a predefined list, they cannot enter an invalid product name.

We can also use radio buttons for a small number of mutually exclusive options, or user checkboxes for Boolean choices.

Using the MaxLength Property

The MaxLength property determines the maximum length of a string in a text box. The systemsteps when the user tries to type a string that exceeds the maximum length. If we want to displayan error message, we need to trap the keystroke in the key press event.

Page 291: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Validating Input and Handling Errors

V0.1 279

Using the Locked Property

The Locked property determines if users can modify data in a text box. If locked is True, userscan only view and copy data in a text box.

Using the KeyPress Event to Validate Data

You can use the KeyPress, KeyDown, KeyUp events to validate data as the user types. We canprevent the user from entering certain characters. We can also modify data as it is entered.

The KeyPress event occurs whenever the user enters a standard ASCII character. This does notinclude most of the special keys, such as function keys, the arrow keys or the Del keys. Torespond to these keys, use the KeyDown and KeyUp events.

The following codes changes characters to uppercase as the user types

Sub Text1_KeyPress (KeyAscii as Integer)KeyAscii = Asc(UCase(chr(KeyAscii)))

End Sub

Validating Form Information

In addition to using field-level techniques to validate data as it is entered, we can write code thatvalidates the data in all fields on a form at the same time. We can accomplish this by disabling

the OK button on a form until the user has filled in all the fields. To test each keystroke enteredon a form, set the form's KeyPreview property to True. The form receives the keyboard eventfirst, and then the control receives the event.

Private Sub Form_Load()Me.KeyPreview = TruecmdOK.Enabled = False

End Sub

Private Sub Form_KeyUp(KeyCode As Integer, Shift As Integer)Dim curcontrol As Control

For Each curcontrol in ControlsIf TypeOf curcontrol is TextBox Then If curcontrol.Text = " "Then

cmdOK.Enabled = FalseExit Sub

End ifEnd if

Next cmdOk.Enabled = TrueEnd Sub

Page 292: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Validating Input and Handling Errors MS Visual Basic 6 Programming Introduction

280 V0.1

Validating All Fields on a Form

An easy way to validate all fields on a form at the same time is to put the validation code in the

Click event of the OK button. In this scenario, the application allows the user to complete theform, and then it validates all fields. The application sets the focus to the first field that containsinvalid data.

Private Sub cmdOK_Click()If Not (IsNumeric(txtDeptNo.Text)) Then

MsgBox "Invalid dept.Number"txtDept.SetFocus

ElseMsgBox "Data is OK"Unload Me

End ifEnd Sub

Using the QueryUnload Event

The QueryUnload event occurs just before the Unload event when the form is unloaded. TheQueryUnload event enables us to determine how an Unload event was initiated, and to cancelthe Unload event. This is useful when a user has not completed the data entry on a form, or

when we would like to prompt the user to save changes before closing the form

The QueryUnload event has the following two arguments

♦ The UnLoadMode argument indicates how the Unload event was initiated.

♦ The Cancel argument cancels the Unload event. If Cancel is set to true, the applicationremains as it was, before the Unload was attempted.

The following code cancels the Unload event and prompts the user before closing the form

Private Sub Form_QueryUnLoad(Cancel As Integer, UnLoadMode as Integer)Dim iresult as Integer

iresult = MsgBox("Are you sure you want to quit", vbYesNo)If iresult = vbNo Then

cancel = TrueEnd If

End Sub

Page 293: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Validating Input and Handling Errors

V0.1 281

Handling run-time Errors

No matter how well we design our application, runtime errors will occur, user forgets to put disk

in disk drives, systems run low on memory, and files are not located etc. By adding effectiveerror handling code to our application, we create a more robust application.

Understanding the Error Handling Process

The error handling process involves the three following steps.

1. Enable an error trap that specifies where execution will branch to when an error occurs.

2. Write the error handling code.

3. Exit the error handling code.

The On Error GoTo statement enables an error trap and specifies where the execution will jumpto when an error occurs. If a run-time error occurs, execution jumps to the label indicated by theOn Error GoTo statement. The error handler, runs error handling code, followed by a Resumestatement that indicates where processing should continue.

The following code shows how to use the On Error GoTo and Resume statements

Private Sub Command1_Click()Dim AppName As String On Error GoTo CheckError

Appname = InputBox (" Enter application name ")Shell AppName

Exit SubCheckError :if err.Number = 53 Then If MsgBox ("Application not Found... Try Again", vbYesNo) = vbYes Then AppName = InputBox("Enter application name")

Resume Else

Resume Next End IfElse

MsgBox "Unknown Error"EndifEnd Sub

Page 294: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Validating Input and Handling Errors MS Visual Basic 6 Programming Introduction

282 V0.1

Err Object Properties

The Number property is an integer that indicates the last error that occurred. To determine

which error has occurred, we check the value of Err.Number. In some cases, we can correct anerror and allow processing to continue without interrupting the user. Other wise, we must notifythe user of an error, and take some action based on the user's response

The Description property is a string that contains a description of the error.

The source property contains the name of the object application that generated the error. This ishelpful when using Automation.

Err Object Methods

The Clear method sets the values of Err.Number back to zero. We use the clear method primarilywhen we handle in-line errors.

The Raise method causes an error. We use the Raise method to pass an error back to a callingprocedure, or to test our own error handling code.

For example:

Err.Raise 53 'File not found Error

Resume Options

To specify where our application will continue processing after handling an error, we use theResume statement. The following table lists the three types of Resume statements available in VB

Statement Description

Resume Return to the statement that caused the error.Use Resume to repeat an operation aftercorrecting the error.

Resume Next Return to the statement immediately followingthe statement that caused the error.

Resume line or label If there is no Resume statement, the procedurewill exit.

Page 295: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Validating Input and Handling Errors

V0.1 283

Disabling Error Handling

It can be difficult to debug code that has error handling enabled. VB may execute error-handling

code when we want to enter Break mode and debug the application. VB provides options todisable error handling when debugging.

To change how errors are handled

• On the Tools menu, select Options

• On the General tab, under Error Trapping , click the option we want, and then click OK.

This table describes the error handling options that are available under Error Trapping on theGeneral tab.

Option Description

Break on All Errors If we click this option, VB ignores any OnError statements and enters Break mode ifany run-time errors occur.

Break in Class Module Set this option when debugging an ActiveXcomponent. This causes the ActiveXcomponent to enter Break mode ratherthan passing the error back to the clientapplication.

Break on UnhandledErrors

VB enters Break mode on any error forwhich we do not supply specific error-handling code.

Page 296: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Validating Input and Handling Errors MS Visual Basic 6 Programming Introduction

284 V0.1

Compiling an Application

Once we have finished creating an application, we can create an executable file for our users.

To create an EXE file,

• On the File menu, select Make <ProjectName>.exe

• Enter the name for the executable file

• To add version-specific information: In the Make EXE File dialogue box, click theOptions button. On the Make tab, type the version number and text for the versioninformation, and then click OK

In addition to the executable file, we must provide various DLLs and other files to users. Weshould create a Setup program using Application Setup Wizard that installs our application ontothe user's computer.

Compiling to Native Code

If we have the Professional Edition or Enterprise Edition of VB, we can compile our code either instandard VB Pseudo-code (p-code) format or in native code format. Native code compilationprovides several options for optimizing and debugging that are not available with p-code. If we

compile by p-code, at runtime VB translates each p-code statement to native code. By compilingdirectly to native code format, we eliminate the intermediate p-code step.

To compile a project to native code

• In the Project window, select the project we want to compile

• On the Project menu, select Project Properties

• In the Project Properties dialogue box, click the Compile tab

• Select the compile options you want to use, and then click OK

We can also click the Advanced Optimizations button for additional native code options.

Page 297: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

V0.1 285

Reading and Writing Files

Objectives

In this Chapter, you will learn about reading and writing files in VisualBasic. You will learn to create sequential files, createrandom access disk files, write information to disk andread information from disk.

• Handling Files

• Reading and Writing Files

• File Functions

• Binary and Sequential Files

• Sequential Access

• Text Files on Disk

• A Text File Program

• Open, Save and Close Files - Random Access

• Writing to a File - Random Access

• Reading Files - Random Access

• Writing Changes Back to Disk - Random Access

• Closing Files - Random Access

• Binary Access

Handling Files

A file is simply a series of related bytes located on a disk. When your program accesses a file it

must assume what the bytes are supposed to represent.

Visual Basic allows three types of access:- Sequential, Random and Binary.

Sequential Access is for plain ASCII text or a text formatting sequence.

Random Access assumes a file is composed of a set of equal length records and is stored asbinary information.

Binary files allow you to store data in any format. It is similar to Random but no assumptions are

made about the data type or record length. You must know precisely how the data is written tothe file to retrieve it correctly.

Page 298: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Reading and Writing Files MS Visual Basic 6 Programming Introduction

286 V0.1

When handling files in Visual Basic you will find it easier if you can work with database files or

design your application to use database files. Thus you will not need to provide direct file accessbut instead use a data control to read and write data to and from a database file.

Reading and Writing Files

Visual Basic works with files in a different way from other programs. There are a number ofways that Visual Basic handles files, in this instance we will be using Random Access which

allows you to treat the file as an array. You can write the elements to this file and read them backin any order by providing an index for the element you want to read or write.

Before we add information to our address book we will look at ways of saving and retrieving

data.

The Command to open a file is Open!

File Functions

The following functions can be used with all three types of file.

Dir FileLen LOF

EOF FreeFile Seek

FileCopy GetAttr SetAttr

FileDateTime Loc

In addition the following is a list of statements available for each type.

Statement Sequential Random Binary

Close ü ü ü

Get ü ü

Input() ü ü

Input # ü

Line Input# ü

Open ü ü ü

Print # ü

Put ü ü

Type...End Type ü

Write # ü

Page 299: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Reading and Writing Files

V0.1 287

Binary and Sequential Files

Visual Basic provides two other modes for opening files; Binary and Sequential. Binary access

mode allows you to write groups of bytes anywhere in the file. This mode gives you most controlover a file but requires a lot of work. Binary files use the Get and Put statements to read andwrite data.

Sequential files allow you to read a file from start to finish, one line at a time. This is useful if youwant to read lines of text, but you don’t need to go backward through the file. The statements towrite lines are Print# or Write# and those to read lines are Input# or LineInput#.

Sequential Access

This type of access works best when you wish to process files consisting of text e.g. text editor orsimple word processor.

With this type you can open it for Input, Output or Append with the following:

Open file For [Input|Output|Append] As filenumber [Len = buffersize]

If opening for input it must already exist otherwise an error occurs. If you open a non-existent file

for Output or Append however the open statement will first create the file then open it.

After opening you must close it with the Close statement before using it for another operation.

Text Files on Disk

You can use the following style of coding when creating and saving an ASCII file.

Dim FreeNumFreeNum = FreeFileOpen “C:\Primary Data\Myfile.txt” For Output As FreeNum

To place text in the file you use the Print statement:

Open “C:\ABC\Myfile.txt” For Output As FreeNumPrint FreeNum, “This is line 1”Print FreeNum, “This is line 2”Print FreeNum, “This is line 3”

You can add data to a text file by opening it for Append:

Open “C:\ABC\Myfile.txt” For Append As FreeNumPrint FreeNum, “This is another line”Print FreeNum, “This is the next line”

Page 300: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Reading and Writing Files MS Visual Basic 6 Programming Introduction

288 V0.1

To read information from a file you would use the following:

Dim FileContents as StringOpen “C:\ABC\Myfile.txt” For Input As FreeNumFileContents = Input$(LOF(FreeNum), FreeNum)

You cannot manipulate text in a file directly. To change the contents of a file you open it for

Input, read in the text, modify the text, open the file for Output and write the modified text backto the file.

A Text File Program

Create a Form containing a multi-line text box (Text1). Create a Menu containing the commandsOpen, Save and Exit. Add a CommonDialog Control.

Coding for Open:

Dim ThisFile As StringCommonDialog1.Filter = “Text Files (*.txt)|*.txt”CommonDialog1.FilterIndex = 1CommonDialog1.Action = 1ThisFile = CommonDialog1.FilenameOpen ThisFile for Input As #1Text1.Text = Input$(LOF(1), 1)Close #1

Coding for Save:

Open CommonDialog1.Filename for Output As #1Print #1, Text1.TextClose #1Text1.Text = “”

Coding for Exit:

End

Add a menu choice for Save As and one to Close the file, asking if you wish to save it.

Coding for Save As:

CommonDialog1.ShowSaveOpen CommonDialog1.Filename for Output As #1Print #1, Text1.TextClose #1

Page 301: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Reading and Writing Files

V0.1 289

Open, Save and Close Files - Random Access

Add the following code to the Form_Load Event handler:

open "\test.dat" as #1beepend

The code will now be shown as:

Sub Form_Load()Open "\test.dat" For Random As #1BeepEnd

End Sub

The full Open command is:

Open file$ [For Mode] [Access acc] [lock] As [#]filenumber% [len = reclen]

For Random

This command means we can use the random-access mode to read/write files and they will betreated similar to an array of records with the exception that the first record is number 1.

As [#]filenumber%

Specifies which file number you will need to use to refer to the file after you open it. Initially weshall use #1.

[Len = reclen]

Specifies the length of each record in the random access file. The default is 128 bytes which wewill later change to the size of the address book type.

One other thing to note is that when you open a file you should also close it when you arefinished. The command is:

Close [[#]filenumber%]] [,[#]filenumber%]]...

If you do not provide any numbers it will close all files. It is usually better to explicitly close eachfile you opened.

• Run the program and you will create the file test.dat, the computer will beep and theprogram will terminate.

• Use Explorer or File Manager to check that test.dat exists in the root directory. It will alsobe zero length.

When we opened it we specified #1 so we can refer to this when we close it. We also put thename in quotes since the filename is a string.

Page 302: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Reading and Writing Files MS Visual Basic 6 Programming Introduction

290 V0.1

Writing to a File - Random Access

The command to write to a file is Put which writes a single element (or record) to a disk file.

The command writes variables rather than raw data to a disk file i.e. it cannot write a string ornumber. To overcome this you need to create a variable, assign the element (record) to it and Putthe variable.

The format is:

Put [#]filenumber%, [recordnumber&], recordvariableType the new version as follows:

Sub Form_LoadOpen "\test.dat" For Random As #1test$ = "This is a test file."Put #1, 1, test$BeepEnd

End Sub

Run this program now, open a DOS window and use the DOS Type command to display the

contents.

At the DOS prompt type:

type \test.dat

When you do so you will notice a ¶ character and a space at the start of the text string. The ¶character has an ASCII value of 20 and the space 0. These two characters tell Visual Basic that the

string has 20 characters in it!

Page 303: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Reading and Writing Files

V0.1 291

Reading Files - Random Access

The command used to read from files is Get. Now that we have data in our test.dat file we can

use it to read back the information using the Get command.

To read the file from disk we need to modify the Form_Load event. Initially we will simplyremove the Beep and End commands. When you run the program you will open a form which is

empty. The form because it does not have a container for the text i.e. a Text box.

Close the form to return to design mode and draw a text box on the form. This can be any sizebut must have the name Text1.

The code for Form_Load will also need to be rewritten as follows:

Sub Form_Load()Open "\test.dat" For Random As #1 'Open the fileGet #1, 1, test$ 'Read the stringText1.Text = test$ 'Place the text in Text1

End Sub

When you run this program the text box on your form will display the text you wrote to disk.

Writing Changes Back to Disk - Random Access

If you make any changes to the text and close the form the changes will not be written back todisk.

To make this happen we need to make a minor change to the Form_Unload event. This uses thePut command to save the text back to disk and is written thus:

Sub Form_Unload()test$ = Text1.TextPut #1, 1, test$

End Sub

Run the program a couple of times, changing the text, to ensure it works.

With this technique you can write single strings up to 126 characters to a file. The default length

was stated to be 128 but remember the two initial characters stating the actual length.

If you opened the file using a larger Len parameter you could write files up to this defined lengthminus 2.

Page 304: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Reading and Writing Files MS Visual Basic 6 Programming Introduction

292 V0.1

Closing Files - Random Access

Having learned to create, open, read and write files there is one last thing that you should also do

and that is Close your files. Visual Basic will close all your files when you exit but it is goodpractice to include a Close statement in your program to explicitly close any data files it mayhave opened.

This statement can be added to the Form_Unload event just above the End Sub thus:

Sub Form_Unload()test$ = Text1.TextPut #1, 1, test$Close #1

End Sub

This closes file number 1 which you opened, hence the reason for using numbers when you openfiles.

Binary Access

Binary access gives you complete control over a file since the bytes can represent anything e.g.

variable-length records. It is most useful where you need to keep file size small.

You open with the statement:

Open file For Binary As filenumber

It does not support the Len qualifier.

When writing to Random files you used the Type statement with records of fixed length

(FirstName As String * 20).

For Binary files you do not need this and can declare the type:

Type PersonID As IntegerSalary As CurrencyFirstName As StringLastName As String

End Type

Public Empl As Person ‘Defines a record

Each employee record in the file will now be stored as the exact number of bytes required

because the fields are variable length. The drawback is the you cannot access files randomly - youmust access them sequentially. You can seek directly to a specified byte position but there is noway of knowing which record is at which position.

Page 305: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

V0.1 293

Client/Server Architecture

Objectives

In this Chapter, you will learn about Client/Server Architecture. Also,you will get an introduction to the types of binding.

• The Typical Monolithic Application Architecture

• Client/Server Architecture (Two - Tier)

• Three Tier Architecture

• Types Of Binding

The Typical Monolithic Application Architecture

In the beginning, there was the mainframe. Mainframes usually were capable of serving largenumber of users and had the advantage of being centrally managed.

Software systems written for mainframe were often monolithic - that is, the user interface,

business logic, and data access functionality were all contained in one large application. Becausethe dumb terminals used to access mainframes did not do any of their own processing, the entireapplication ran in the mainframe itself.

Client/Server Architecture (Two-tier Architecture)

Using the Client/Server architecture many applications do not require the massive power ofmainframes, and because Client/Server architecture was capable of moving much of theprocessing load to the desktop PC, these smaller WINDOWS-NT based server machines were

often more cost-effective than mainframes.

.Also, these machines were much more affordable to small business than mainframes, whichwere often simply out of reach for companies with relatively small bank account balances. Still

another benefit was the empowerment of individual departments within an organization todeploy and manage their own Applications and a PC was capable of performing any other tasksindependently of the mainframes.

Two-tier Client/Server Applications typically distributed the components of the application sothat the database would reside on the server, the user interface would reside on the client, and

Page 306: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Client/Server Architecture MS Visual Basic 6 Programming Introduction

294 V0.1

the business logic would reside in either or both components. When changes were made to parts

of the client component, new copies of the client component had to be distributed to each user.

Three Tier Architecture

Two-tier architecture has its own faults. For example, because database access functionality andbusiness logic were often contained in the client component, any changes to the business logic,database access, or even the database itself, often required the deployment of a new client

component to all the users of the application.

The problems with the traditional client/server architecture were addressed by the multi-tierclient/server architecture. Conceptually, an application can have any number of tiers, but the

most popular multi-tier architecture is three-tier, which partitions the system into three logicaltiers: the user interface layer, the business rules layer, and the database access layer.

Multi-tier client/server architecture reduces application process by providing more insulation

and separation between layers. The user interface layer communicates with the user on one sideand the database access layer on the other. Thus, changes in the database access layer will notaffect the user interface layer because they are insulated from each other.

An application or component that uses objects, provided by another component is called a client.

Components are characterized by their location relative to clients. An out-of-process component isan .EXE file that runs in its own process, with its own thread of execution. Communication

between a client and an out-of-process component is therefore called cross-process or out-of-processcommunication.

An in-process component, such as a .DLL or .OCX file, runs in the same process as the client. It

provides the fastest way of accessing objects, because property and method calls don't have to bemarshaled across process boundaries. However, an in-process component must use the client'sthread of execution.

Components provide reusable code in the form of objects. An application that uses a component'scode, by creating objects and calling their properties and methods, is referred to as a client.

Components can run either In-Process or Out-of-Process with respect to the clients that use their

objects. An in-process component, or ActiveX DLL, runs in another application's process. Theclient may be the application itself, or another in-process component that the application is using.

Binding is the process of setting up a property or method call that's to be made using a particular

object variable. It's part of the overhead of calling the property or method.

Page 307: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Client/Server Architecture

V0.1 295

The time required to call a procedure depends on two factors:

1. The time required to perform a task, the procedure was designed to do, such as finding thedeterminant of a matrix.

2. The overhead time required to place the arguments on the stack, invoke the procedure, and

return.

Types of Binding

There are two main types of binding in Automation — late binding and early binding. Earlybinding is further divided into two types, referred to as DispID binding and Vtable binding. Latebinding is the slowest, and Vtable binding is the fastest.

Late Binding

When you declare a variable As Object or As Variant, Visual Basic cannot determine at compiletime what sort of object reference the variable will contain. Therefore, Visual Basic must use latebinding to determine at run time whether the actual object has the properties and methods you callusing the variable.

Each time you invoke a property or method with late binding, Visual Basic passes the membername to the GetIDsOfNames method of the object's IDispatch interface. GetIDsOfNames returnsthe dispatch ID, or DispID, of the member. Visual Basic invokes the member by passing theDispID to the Invoke method of the IDispatch interface.

For an out-of-process component, this means an extra cross-process method call, essentiallydoubling the call overhead.

Early Binding

If Visual Basic can tell at compile time what object a property or method belongs to, it can lookup the DispID or Vtable address of the member in the type library. There's no need to callGetIDsOfNames.

When you declare a variable of a specific class — for example, As Widget — the variable can onlycontain a reference to an object of that class. Visual Basic can use early binding for any propertyor method calls made using that variable.

This is the recommended way to declare object variables in Visual Basic components andapplications.

Page 308: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Client/Server Architecture MS Visual Basic 6 Programming Introduction

296 V0.1

VTable Binding

In the fastest form of early binding, vtable binding , Visual Basic uses an offset into a virtualfunction table, or vtable. Visual Basic use vtable binding whenever possible.

Objects created from Visual Basic class modules support all three forms of binding, because theyhave dual interfaces — that is, vtable interfaces derived from IDispatch.

If client applications declare variables using explicit class names, Visual Basic objects will alwaysbe vtable bound. Using vtable binding to call a method of an in-process component created withVisual Basic requires no more overhead than calling a function in a DLL.

DispID Binding

For components that have type libraries but don't support vtable binding, Visual Basic usesDispID binding. At compile time, Visual Basic looks up the DispIDs of properties and methods,so at run time there's no need to call GetIDsOfNames before calling Invoke.

Page 309: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

V0.1 297

ActiveX Code Components

Objectives

In this Chapter, you will learn about ActiveX Code Components. Youwill learn about class modules – adding a class module,creating an instance of a class, class module events andcreating methods and properties. You will learn to createVB standard EXE projects using class modules andActiveX DLL’s.

• Introduction to ActiveX Components

• Creating Objects in VB

• What is a Class Module?

• Adding a Class Module to a VB Project

• Creating an Instance of a Class

• Class Module Events

• Creating Methods

• Creating Properties

• Registering a Component

Introduction to ActiveX Components

An ActiveX component is a unit of executable code, such as an .exe, .dll or .ocx file, that followsthe ActiveX specification for providing objects. An ActiveX component exposes objects that canbe used by other applications. There are three types of ActiveX components we can create with

Visual Basic: ActiveX controls, ActiveX documents, and ActiveX code components.

ActiveX Controls

ActiveX controls formerly known as OLE controls are standard user-interface elements that allowus to rapidly assemble reusable forms and dialog boxes.

Page 310: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

ActiveX Code Components MS Visual Basic 6 Programming Introduction

298 V0.1

ActiveX Documents

ActiveX documents are ActiveX components that must be hosted and activated within a clientapplication. ActiveX document technology is an extension to OLE documents. It expands thefunctionality of visual editing of embedded objects, enabling generic shell applications, such asInternet Explorer, to host different types of documents.

ActiveX Code Components

Code components (formerly known as OLE servers) are libraries of objects. Client applicationsuse code components by creating objects from classes provided by the component. Clients call theproperties, methods, and events provided by the object. Any application that supports standardAutomation can use an ActiveX code component created in Visual Basic.

Visual Basic handles much of the complexity of creating an ActiveX code component, such ascreating a type library and registering the component automatically

Creating Objects in Visual Basic

Creating ActiveX code components involves working with class modules to define the objectsthat our component provides. Classes encapsulate the internal functionality of a component, andclients create object from instances of classes at run time.

Before creating an ActiveX code component, we'll learn how to create and use class modulewithin a single Visual Basic project.

What is a Class Module

When creating ActiveX code components, the first step is to define objects within our Visual Basicproject. These objects can then be used within our Visual Basic project or exposed to other

applications. To define an object for our component, we use a class module.

Purpose of a Class Module

A class module is a type of code module that Visual Basic provides. Each class module acts as ablueprint for an object. In other words, each class module defines one type of object. We may

have several class modules in an application. At run time, we can create an object by creating aninstance of a class. We will find class modules useful when creating any kind of ActiveX codecomponent. Class modules represent a logical object in our component. For example, we might

create an Employee class that has properties such as Employee.Lastname andEmployee.Firstname, and methods such as Employee.Hire. Our application can work withmultiple instances of an Employee object, and can create a collection of Employee objects.

Page 311: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction ActiveX Code Components

V0.1 299

Adding a Class Module to a Project

To insert a new class module in a project, click Add Class Module on the Project menu. We can

add methods, properties, and events to classes manually, or we can use the Class Builder inVisual Basic. The class builder add-in automates the processes for adding properties, methodsand events to classes

Creating an Instance of a Class

Class modules differ from standard modules in these two ways:

Class modules must be explicitly created before they can be used

We can create multiple instances of a class module.

In the project that defines a class, we can create an instance of the class with the Dim and Setstatements, as shown in the code.

Dim objMyObject1 As Class1Dim objMyObject2 As Class2

Set objMyObject1 = New Class1Set objMyObject2 = New Class2

Class Module Events

Class modules come with two built-in events: Initialize and Terminate.

To add code to the class module events, open a code window for the class, and click Class in theObject drop-down list box.

Initialize Event

The Initialize event occurs when an instance of a class is created, but before any properties havebeen set. We use the Initialize event to initialize any data used by the class, as shown

Private Sub Class_Initialixe ( )' Initialize data iDept = 5

End Sub

Page 312: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

ActiveX Code Components MS Visual Basic 6 Programming Introduction

300 V0.1

Terminate Event

The Terminate Event occurs when the object variable goes out of scope or is set to Nothing. Usethe Terminate Event to save information, unload forms or perform tasks that should occur whenthe class terminates

Private Sub Class_Terminate ( )' Any termination code

End Sub

Creating Methods

To create a method for an object, we create Public Sub or Function procedures within a class

module. When we create an instance of the class module, the Public Sub and Functionprocedures are available as methods of the resulting objects. The following code creates amethod that displays the date

Public Sub ShowDate ( )Msgbox "Date is: " & Now( )

End Sub

The following code creates a method that accepts a number and returns the number squared.

Public Funtion Square ( Num As Integer) As Integer SquateIt = Num * NumEnd Function

This code creates an instance of the class and calls the ShowDate and SquareIt methods.

Dim Demo1 As Class1Set Demo1 = New Class1Demo1.ShowDatei = Demo1.SquareIt (Num := 5)

Page 313: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction ActiveX Code Components

V0.1 301

Creating Properties

There are two ways to define a property for our object

- Define public variables

- Create public property procedures within our class module

The following code creates a Property Let and Property Get procedure that assigns a string value

and returns the value for the User property.

Private gsuser As stringPublic Property Let USer ( s As String) gsuser = UCase(s)End Property

Public Property Get User ( ) As String User = gsUserEnd Property

Setting and Retrieving a Property

Dim Demo1 As Class1Set Demo1 = New Class1Demo1.USer = "Joe" 'Calls the Let ProcedurePrint Demo1.User 'Calls Get Procedure

To create a property that returns a standard data type, define a Property Get Procedure and

Property Let procedure. To create a property that is an Object Data type, define a Property Getprocedure and a Property Set Procedure. When we read the Property, the Property Getprocedure runs. When we set the property, the Property Let procedure runs.

The Property Let procedure always contains at least one argument, which is the value for theproperty. This argument should always be the last argument in the argument list.

To create a read-only property, define a Property Get procedure without a matching Property Let

or Property Set procedure.

Page 314: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

ActiveX Code Components MS Visual Basic 6 Programming Introduction

302 V0.1

Registering a Component

Before an ActiveX code component can be used it must be registered. An ActiveX code

component is temporarily registered when we run it from Design mode. The component ispermanently registered when we:

- Run it for the first time- Install it by using a Setup program- We run it with the /Regserver command line argument.

Visual Basic registers an ActiveX DLL file when we compile it. We can also use Regsvr32.exe to

register the DLL file as shown below.

Regsvr32.exe mydll.dll

Page 315: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction ActiveX Code Components

V0.1 303

ExerciseClass Module and Business Rules

Consider a Payroll Application. Write a VB application having a business rule that loans toemployees should be sanctioned based on their designations. (For example – US $ 500 or US $1000 or US $ 10000 – based on employee designation).

Solution:

• Open a new standard .EXE project.

• Open a Class Module from project menu and name it as emp.

• Write the following code in emp Class module.

Option ExplicitDim en As rdoEnvironmentDim Qd As rdoQueryDim Cn As rdoConnectionDim Rs As rdoResultsetDim SQL As StringDim a1 As Integer, b1 As String, c1 As String, d1 As Integer, e1 As String

Public Sub nextr() Rs.MoveNextEnd SubPublic Sub last() Rs.MoveLastEnd Sub

Public Sub pre() Rs.MovePreviousEnd Sub

Public Sub first() Rs.MoveFirstEnd Sub

Public Sub delete() If Not (Rs.EOF And Rs.BOF) Then Rs.delete End If Rs.MoveFirstEnd Sub

Page 316: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

ActiveX Code Components MS Visual Basic 6 Programming Introduction

304 V0.1

Public Sub edit() Rs.editEnd Sub

Public Sub save() Rs.Update Rs.Requery Rs.MoveFirstEnd Sub

Friend Sub add() Rs.AddNewEnd Sub

Public Sub getdb(a As Integer, b As String, c As String, d As Integer, e As _String) If Not (Rs.EOF And Rs.BOF) Then If Not (Rs.EOF) Then If Not (Rs.BOF) Then a = Rs(0) b = Rs(1) c = Rs(2) d = Rs(3) e = Rs(4) Else MsgBox "BOF" End If Else MsgBox "EOF" End If Else MsgBox "No Records Found In Database" End IfEnd Sub

Public Sub filldb(a As Integer, b As String, c As String, d As Integer, e As _String) Rs(0) = a Rs(1) = b Rs(2) = c Rs(3) = d Rs(4) = eEnd Sub

Public Sub connect() Set en = rdoEnvironments(0) Set Cn = en.OpenConnection("cat",_ "UID=;PWD=;DATABASE=master;"&_ "Driver={SQL Server};SERVER=Betav486") Set Qd = Cn.CreateQuery("emp", "Select * from emppay") Set Rs = Qd.OpenResultset(rdOpenDynamic, rdConcurValues)End Sub

Public Sub cancel() Rs.cancel Rs.Requery Rs.MoveFirstEnd Sub

Page 317: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction ActiveX Code Components

V0.1 305

Public Property Let desig(ByVal vData As String)'used when assigning a value to the property, on the left side of an assignment.'Syntax: X.desig = 5 Rs(4) = vDataEnd Property

Public Property Get desig() As String'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.desig desig = Rs(4)End Property

Public Property Let salary(ByVal vData As Integer)'used when assigning a value to the property, on the left side of an assignment.'Syntax: X.salary = 5 Rs(3) = vDataEnd Property

Public Property Get salary() As Integer'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.salary salary = Rs(3)End Property

Public Property Let sex(ByVal vData As String)'used when assigning a value to the property, on the left side of an assignment.'Syntax: X.sex = 5 Rs(2) = vDataEnd Property

Public Property Get sex() As String'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.sex sex = Rs(2)End Property

Public Property Let name(ByVal vData As String)'used when assigning a value to the property, on the left side of an assignment.'Syntax: X.name = 5 Rs(1) = vDataEnd Property

Public Property Get name() As String'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.name name = Rs(1)End Property

Public Property Let empno(ByVal vData As Integer)'used when assigning a value to the property, on the left side of an assignment.'Syntax: X.empno = 5 Rs(0) = vDataEnd Property

Page 318: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

ActiveX Code Components MS Visual Basic 6 Programming Introduction

306 V0.1

Public Property Get empno() As Integer'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.empno empno = Rs(0)End Property

• Now Design your form by placing controls on it as shown in the next page.

Page 319: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction ActiveX Code Components

V0.1 307

• Write the following code in the form1 and name it as emp.

Option ExplicitDim s As New empDim a As Integer, b As String, c As String, d As Integer, e As String

Private Sub cmdadd_Click() Text1 = "" Text2 = "" Text3 = "" Text4 = "" Text5 = "" Text1.SetFocus s.add cmdsave.Enabled = True cmdedit.Enabled = False cmdexit.Enabled = False cmdadd.Enabled = False Frame1.Enabled = False cmddelete.Enabled = FalseEnd Sub

Private Sub cmdcancel_Click() s.cancel filltxt cmdsave.Enabled = False cmdedit.Enabled = True cmdexit.Enabled = True cmdadd.Enabled = True Frame1.Enabled = True cmddelete.Enabled = TrueEnd Sub

Private Sub cmddelete_Click() s.deleteEnd Sub

Private Sub cmdedit_Click() s.edit cmdsave.Enabled = True cmdedit.Enabled = False cmdexit.Enabled = False cmdadd.Enabled = False Frame1.Enabled = False cmddelete.Enabled = FalseEnd Sub

Private Sub cmdexit_Click() Unload MeEnd Sub

Private Sub cmdfirst_Click() s.first filltxtEnd Sub

Page 320: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

ActiveX Code Components MS Visual Basic 6 Programming Introduction

308 V0.1

Private Sub cmdlast_Click() s.last filltxtEnd Sub

Private Sub cmdnext_Click() s.nextr filltxtEnd Sub

Private Sub cmdpre_Click() s.pre filltxtEnd Sub

Private Sub cmdsave_Click()Dim z As String filldb s.save z = MsgBox("Do You Require Loan", vbYesNoCancel, "Loan") If z = vbYes Then Form2.Show Form2.ZOrder End If filltxt cmdsave.Enabled = False cmdedit.Enabled = True cmdexit.Enabled = True cmdadd.Enabled = True Frame1.Enabled = True cmddelete.Enabled = TrueEnd Sub

Private Sub Form_Load() s.connect filltxt cmdsave.Enabled = FalseEnd Sub

Public Sub filltxt() s.getdb a, b, c, d, e Text1.Text = a Text2 = b Text3 = c Text4 = d Text5 = eEnd Sub

Public Sub filldb() a = Val(Text1.Text) b = Text2 c = Text3 d = Val(Text4) e = Text5 s.filldb a, b, c, d, eEnd Sub

Page 321: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction ActiveX Code Components

V0.1 309

Private Sub Text5_lostfocus() cmdsave.SetFocusEnd Sub

• Now create a new Form from project menu and name it as loan.

• Now create a new Class Module from project menu and name it as loan.

• Write the following code in loan Class Module,

Option ExplicitDim en As rdoEnvironmentDim Qd As rdoQueryDim q1 As rdoQueryDim Cn As rdoConnectionDim Rs As rdoResultsetDim r1 As rdoResultsetDim SQL As StringDim a1 As Integer, b1 As String, c1 As Integer

Public Sub getdb(a As Integer, b As String, c As Integer)rsno

a = r1(0) b = r1(1) If Trim(UCase(b)) = Trim(UCase("Analyist")) Then c = 5000 ElseIf Trim(UCase(b)) = Trim(UCase("Programmer")) Then c = 2500 ElseIf Trim(UCase(b)) = Trim(UCase("Manager")) Then c = 7000 ElseIf Trim(UCase(b)) = Trim(UCase("Trainee")) Then c = 2000 Else MsgBox "Loan Is Not Allowed For '" & b & " '" End If Rs.AddNew filldb a, b, c Rs.UpdateEnd Sub

Public Sub filldb(a As Integer, b As String, c As Integer) Rs(0) = a Rs(1) = b Rs(2) = cEnd Sub

Public Sub connect() Set en = rdoEnvironments(0) Set Cn = en.OpenConnection("cat", "UID=;PWD=;DATABASE=master;" & "Driver={SQLServer};SERVER=Betav486") Set Qd = Cn.CreateQuery("loan", "Select * from loan") Set Rs = Qd.OpenResultset(rdOpenDynamic, rdConcurValues)End Sub

Page 322: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

ActiveX Code Components MS Visual Basic 6 Programming Introduction

310 V0.1

Public Property Let loan(ByVal vData As Integer)'used when assigning a value to the property, on the left side of an assignment.'Syntax: X.loan = 5 Rs(2) = vDataEnd Property

Public Property Get loan() As Integer'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.loan loan = Rs(1)End Property

Public Property Let desig(ByVal vData As String)'used when assigning a value to the property, on the left side of an assignment.'Syntax: X.desig = 5 Rs(1) = vDataEnd Property

Public Property Get desig() As String'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.desig desig = r1(1)End Property

Public Property Let empno(ByVal vData As Integer)'used when assigning a value to the property, on the left side of an assignment.'Syntax: X.empno = 5 Rs(0) = vDataEnd Property

Public Property Get empno() As Integer'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.empno empno = r1(0)End Property

Public Sub rsno() Set q1 = Cn.CreateQuery("mat", "select empno,designation from emppay _where empno=" & Form1.Text1.Text) Set r1 = q1.OpenResultset(rdOpenDynamic, rdConcurValues) MsgBox r1(0) & " " & r1(1)End Sub

• Design the loan Form as shown below:

Page 323: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction ActiveX Code Components

V0.1 311

• Write the following code in loan Form.

Option ExplicitDim l As New loanDim a As Integer, b As String, c As Integer

Private Sub cmdexit_Click() Unload MeEnd Sub

Private Sub Form_Load() l.connect filltxtEnd Sub

Public Sub filltxt() l.getdb a, b, c Text1.Text = a Text2.Text = b Text3.Text = cEnd Sub

• Save the project and run it.

Page 324: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

ActiveX Code Components MS Visual Basic 6 Programming Introduction

312 V0.1

ExerciseVB Standard EXE Project using Class Modules

Write a VB Standard EXE application using Class Module to update the employee salary.

Solution:

• Open New Standerd.EXE Project

• Create Class Module from Project Menu

• Add following code in the class module

Option ExplicitDim en As rdoEnvironmentDim Qd As rdoQueryDim Cn As rdoConnectionDim Rs As rdoResultsetDim SQL As StringDim a1 As Integer, b1 As Integer, c1 As Integer, d1 As Integer, e1 As Integer, f1 As Integer, g1 AsIntegerPublic Sub nextr() Rs.MoveNextEnd SubPublic Sub last() Rs.MoveLastEnd Sub

Public Sub pre() Rs.MovePreviousEnd Sub

Public Sub first() Rs.MoveFirstEnd Sub

Public Sub delete() If Not (Rs.EOF And Rs.BOF) Then Rs.delete End If Rs.MoveFirstEnd Sub

Public Sub edit() Rs.editEnd Sub

Public Sub save()

Page 325: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction ActiveX Code Components

V0.1 313

Rs.Update Rs.Requery Rs.MoveFirstEnd Sub

Friend Sub add() Rs.AddNewEnd Sub

Public Sub getdb(a As Integer, b As Integer, c As Integer, d As Integer, e As _Integer, f As Integer, g As Integer) If Not (Rs.EOF And Rs.BOF) Then If Not (Rs.EOF) Then If Not (Rs.BOF) Then a = Rs(0) b = Rs(1) c = Rs(2) d = Rs(3) e = Rs(4) f = Rs(5) g = Rs(6) Else MsgBox "BOF" End If Else MsgBox "EOF" End If Else MsgBox "No Records Found In Database" End IfEnd Sub

Public Sub filldb(a As Integer, b As Integer, c As Integer, d As Integer, _ e As Integer, f As Integer, g As Integer) Rs(0) = a Rs(1) = b Rs(2) = c Rs(3) = d Rs(4) = e Rs(5) = f Rs(6) = g End Sub

Public Sub connect() Set en = rdoEnvironments(0) Set Cn = en.OpenConnection("cat"_, "UID=;PWD=;DATABASE=master;"&_"Driver={SQL Server};SERVER=Betav486") Set Qd = Cn.CreateQuery("salary", "Select * from salary") Set Rs = Qd.OpenResultset(rdOpenDynamic, rdConcurValues) 'getdb a1, b1, c1, d1, e1, f1, g1End Sub

Public Property Let gross(ByVal vData As Integer)'used when assigning a value to the property, on the left side of an assignment.'Syntax: X.gross = 5 Rs(6) = vDataEnd Property

Page 326: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

ActiveX Code Components MS Visual Basic 6 Programming Introduction

314 V0.1

Public Property Get gross() As Integer'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.gross gross = Rs(6)End Property

Public Property Let spallow(ByVal vData As Integer)'used when assigning a value to the property, on the left side of an assignment.'Syntax: X.spallow = 5 Rs(5) = vDataEnd Property

Public Property Get spallow() As Integer'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.spallow spallow = Rs(5)End Property

Public Property Let convey(ByVal vData As Integer)'used when assigning a value to the property, on the left side of an assignment.'Syntax: X.convey = 5 Rs(4) = vDataEnd Property

Public Property Get convey() As Integer'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.convey convey = Rs(4)End Property

Public Property Let hra(ByVal vData As Integer)'used when assigning a value to the property, on the left side of an assignment.'Syntax: X.hra = 5 Rs(3) = vDataEnd Property

Public Property Get hra() As Integer'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.hra hra = Rs(3)End Property

Public Property Let da(ByVal vData As Integer)'used when assigning a value to the property, on the left side of an assignment.'Syntax: X.da = 5 Rs(2) = vData End Property

Public Property Get da() As Integer'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.da da = Rs(2)End Property

Public Property Let basic(ByVal vData As Integer)'used when assigning a value to the property, on the left side of an assignment.

Page 327: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction ActiveX Code Components

V0.1 315

'Syntax: X.basic = 5 Rs(1) = vDataEnd Property

Public Property Get basic() As Integer'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.basic basic = Rs(1)End Property

Public Property Let empno(ByVal vData As Integer)'used when assigning a value to the property, on the left side of an assignment.'Syntax: X.empno = 5 Rs(0) = vDataEnd Property

Public Property Get empno() As Integer'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.empno empno = Rs(0) End Property

Public Sub cancel() Rs.cancel Rs.Requery Rs.MoveFirstEnd Sub

• Go to design mode of form and place the controls as shown

• Write following code.

Page 328: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

ActiveX Code Components MS Visual Basic 6 Programming Introduction

316 V0.1

Option ExplicitDim s As New salaryDim a As Integer, b As Integer, c As Integer, d As Integer, e As Integer, f As Integer, g As Integer

Private Sub cmdadd_Click() Text1 = "" Text2 = "" Text3 = "" Text4 = "" Text5 = "" Text6 = "" Text7 = "" Text1.SetFocus s.add cmdsave.Enabled = True cmdedit.Enabled = False cmdexit.Enabled = False cmdadd.Enabled = False Frame1.Enabled = False cmddelete.Enabled = FalseEnd Sub

Private Sub cmdcancel_Click() s.cancel filltxt cmdsave.Enabled = False cmdedit.Enabled = True cmdexit.Enabled = True cmdadd.Enabled = True Frame1.Enabled = True cmddelete.Enabled = TrueEnd Sub

Private Sub cmddelete_Click() s.deleteEnd Sub

Private Sub cmdedit_Click() s.edit cmdsave.Enabled = True cmdedit.Enabled = False cmdexit.Enabled = False cmdadd.Enabled = False Frame1.Enabled = False cmddelete.Enabled = FalseEnd Sub

Page 329: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction ActiveX Code Components

V0.1 317

Private Sub cmdexit_Click() Unload MeEnd Sub

Private Sub cmdfirst_Click() s.first filltxtEnd Sub

Private Sub cmdlast_Click() s.last filltxtEnd Sub

Private Sub cmdnext_Click() s.nextr filltxtEnd SubPrivate Sub cmdpre_Click() s.pre filltxtEnd Sub

Private Sub cmdsave_Click() filldb s.save filltxt cmdsave.Enabled = False cmdedit.Enabled = True cmdexit.Enabled = True cmdadd.Enabled = True Frame1.Enabled = True cmddelete.Enabled = TrueEnd Sub

Private Sub Form_Load() s.connect filltxt cmdsave.Enabled = FalseEnd Sub

Public Sub filltxt() s.getdb a, b, c, d, e, f, g Text1.Text = a Text2 = b Text3 = c Text4 = d Text5 = e Text6 = f Text7 = gEnd Sub

Page 330: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

ActiveX Code Components MS Visual Basic 6 Programming Introduction

318 V0.1

Public Sub filldb() a = Val(Text1.Text) b = Val(Text2) c = Val(Text3) d = Val(Text4) e = Val(Text5) f = Val(Text6) g = Val(Text7) s.filldb a, b, c, d, e, f, gEnd Sub

Private Sub Text6_lostfocus() Text7.Text = Val(Val(Text2.Text) + Val(Text3.Text) + Val(Text4.Text)_ + Val(Text5.Text) + Val(Text6.Text))End Sub

Private Sub Text7_lostfocus() cmdsave.SetFocusEnd Sub

• Save the project and run the form.

Page 331: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction ActiveX Code Components

V0.1 319

ExerciseActivex Dll (In Process)

Consider a payroll application having following tables:

Employee, department, salary and loan.

Create an ActiveX DLL which has a business rule that new loan should not be allowed to any

employee in whose name an old loan still exists.

Solution:

• Open a new ActiveX Dll project. Name the project as loanprj. Name project description asLoan checking ActiveX Dll. Name the class as LoanDll. Choose Project References andchoose Microsoft Remote Data Object 2.0 as reference.

• Declare the variables as follows:

Private e As rdoEnvironmentPrivate cn As rdoConnectionPrivate qd As rdoQueryPrivate rs As rdoResultset'local variable(s) to hold property value(s)Private mvarempno As Long 'local copyPrivate mvardeptno As Long 'local copyPrivate mvarname As String 'local copyPrivate mvarloansanc As Double 'local copyPrivate mvarloancoll As Double 'local copy

• In the Tools menu, choose add procedure and create these public properties as follows:

Public Property Let loancoll(ByVal vData As Double)'used when assigning a value to the property, on the left side of an ‘assignment.'Syntax: X.loancoll = 5 mvarloancoll = vDataEnd Property

Public Property Get loancoll() As Double'used when retrieving value of a property, on the right side of an ‘assignment.'Syntax: Debug.Print X.loancoll loancoll = mvarloancollEnd Property

Page 332: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

ActiveX Code Components MS Visual Basic 6 Programming Introduction

320 V0.1

Public Property Let loansanc(ByVal vData As Double)'used when assigning a value to the property, on the left side of an ‘assignment.'Syntax: X.loansanc = 5 mvarloansanc = vDataEnd Property

Public Property Get loansanc() As Double'used when retrieving value of a property, on the right side of an ‘assignment.'Syntax: Debug.Print X.loansanc loansanc = mvarloansancEnd Property

Public Property Let name(ByVal vData As String)'used when assigning a value to the property, on the left side of an assignment.'Syntax: X.name = 5 mvarname = vDataEnd Property

Public Property Get name() As String'used when retrieving value of a property, on the right side of an ‘assignment.'Syntax: Debug.Print X.name name = mvarnameEnd Property

Public Property Let deptno(ByVal vData As Long)'used when assigning a value to the property, on the left side of an ‘assignment.'Syntax: X.deptno = 5 mvardeptno = vDataEnd PropertyPublic Property Get deptno() As Long'used when retrieving value of a property, on the right side of an ‘assignment.'Syntax: Debug.Print X.deptno deptno = mvardeptnoEnd Property

Public Property Let empno(ByVal vData As Long)'used when assigning a value to the property, on the left side of an ‘assignment.'Syntax: X.empno = 5 mvarempno = vDataEnd Property

Public Property Get empno() As Long'used when retrieving value of a property, on the right side of an assignment.'Syntax: Debug.Print X.empno empno = mvarempnoEnd Property

• In the Tools menu, select Add Procedure and create the following private procedure anda public function

Private Sub connect()Set e = rdoEnvironments(0)e.CursorDriver = rdUseOdbcSet cn = e.OpenConnection("sunny", rdDriverPrompt, False, "uid=prasanna;pwd=dolly")End SubPublic Function check(vempno As Long) As Boolean

Page 333: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction ActiveX Code Components

V0.1 321

Dim i As IntegerconnectSet qd = cn.CreateQuery("testloan", "select *from loan ")Set rs = qd.OpenResultset(rdOpenDynamic, rdConcurValues) If (rs.BOF And rs.EOF) Then check = True Else rs.MoveFirst For i = 1 To rs.RowCount If rs![empno] = vempno Then If rs![loansanc] <> rs![loancoll] Then check = False Else check = True End If Else check = True End If rs.MoveNext Next End IfEnd Function

• Save the project and make loanprj.dll.

• Open a client application by choosing File-New-Standard exe.

• Save this project as lndllclnt.vbp. Add the following to the form.

a) Add 5 text boxes and name them as txtemp, txtdept, txtname, txtsanc, txtcoll.

b) Add 5 labels for the corresponding textboxes.

c) Add 2 commandbuttons and name them as cmdcheck, cmdexit.

d) Choose Project-References and choose Loan Checking ActiveX Dll as reference.

e) Enter the following code

Dim ln As New loanDim Res As Boolean

Private Sub cmdcheck_Click() res = ln.check(CLng(txtemp.Text)) If res Then MsgBox "The loan can be granted to this employee" txtsanc.SetFocus Else

MsgBox "Sorry,This employee has not cleared his previous loan"

Page 334: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

ActiveX Code Components MS Visual Basic 6 Programming Introduction

322 V0.1

txtemp.Text = "" txtdept.Text = "" txtname.Text = "" txtemp.setfocus End If End Sub

Private Sub cmdexit_Click() End End Sub

Private Sub txtname_LostFocus() MsgBox "please click check button for loan checking" cmdcheck.SetFocus End Sub

• Save the project and press F5 to run the client application

• Note that calculations are done 'referencing' the DLL created earlier

• Finally, the output screen will look like this indicating whether the employee is eligiblefor loan or not

Page 335: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

V0.1 323

Creating ActiveX Controls

Objectives

In this Chapter, you will learn how to create your own ActiveX Controls.

• Introduction to ActiveX Controls

• What is a Control?

• Control Classes

• Control Components

• Code Components

• UserControl Object

• Distributing Controls

• Creating an ActiveX Control

• Example: Creating an ActiveX Control for CurrencyConversion

Introduction to ActiveX Controls

ActiveX control, were formerly known as OLE controls. With Visual Basic ver 6.0 we can createActiveX controls for use in any ActiveX host, including Visual Basic and Internet Explorer.

What is a control?

Controls are reusable objects that include visual elements and code. With Visual Basic, we can

use controls to quickly create forms and dialog boxes. Controls must be placed in some type ofcontainer, like forms or an application.

Page 336: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Creating ActiveX Controls MS Visual Basic 6 Programming Introduction

324 V0.1

Control Classes

A control we create in Visual Basic is known as control class. It acts as a template for that control.

When we place a control on a form, we create an instance of that control.

Control Components

Controls can be compiled into control components, also known as .ocx files. A controlcomponent can provide more than one kind of control. A VB ActicveX control project contains

one or more .ctl files, each of which defines a separate control class. When we compile a controlproject, an .ocx file is created for the control component. A single ocx file can contain multiplecontrols.

Code Components

A Code component is an application that exposes functionality and can be used and reused by

other applications through automation. Code components differ from Control components.Control components contain visual elements that can generate events based on user action.

UserControl Object

The UserControl object is the foundation for building controls. Every ActiveX control that wecreate with VB contains a usercontrol object. Usercontrol objects contain code modules and

visual designers. When we open the user control in design mode, the object is displayed in avisual designer window. We can use the visual designer to place additional controls on theusercontrol object.

Distributing Controls

To distribute a compiled control component with an application, ActiveX controls must be

created as Public Classes. Compiled control component can be included through the Setupprogram of the application.

Page 337: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Creating ActiveX Controls

V0.1 325

Creating an ActiveX control

Following Steps are involved in building an ActiveX control:

1. Create the user interface for the control.

2. Provide the properties and methods of the control.

3. Define how the control will react to events.

4. Add property pages for the controls.

5. Debug and test the control.

Page 338: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Creating ActiveX Controls MS Visual Basic 6 Programming Introduction

326 V0.1

ExerciseCreate an ActiveX Control for Currency Conversion.

• Open a New ActiveX Control Project.

• Design the UserControl as shown below.

• Add a new Form to UserControl from project menu and name it as Currency.

• Now design the Form by placing Controls as shown.

Page 339: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Creating ActiveX Controls

V0.1 327

• Write the following code in form code window,

Option ExplicitDim mydb As Database, myws As Workspace, myset As RecordsetDim emptd As TableDefDim empflds(2) As Field

Sub newdatabase() Set myws = DBEngine.Workspaces(0) If Dir("dao.mdb") <> App.Path & "\dao.mdb" Then 'MsgBox "Database Alredy Existing" 'Kill "dao.mdb" Else Set mydb = myws.CreateDatabase(App.Path & "\dao.mdb", dbLangGeneral) Set emptd = mydb.CreateTableDef("CConvert") Set empflds(0) = emptd.CreateField("Currency", dbText) empflds(0).Size = 10 Set empflds(1) = emptd.CreateField("Rate", dbInteger) emptd.Fields.Append empflds(0) emptd.Fields.Append empflds(1) mydb.TableDefs.Append emptd MsgBox "Database Created" mydb.Close End IfEnd Sub

Private Sub cmdadd_Click() Text1.Text = "" Text2.Text = "" Text1.SetFocus enatxt False myset.AddNew cmdsave.Enabled = True cmdedit.Enabled = FalseEnd Sub

Private Sub cmdopen_Click()MsgBox "Opend Database"End Sub

Private Sub cmdedit_Click() enatxt False myset.Edit myset(0) = Text1.Text myset(1) = Val(Text2.Text) cmdsave.Enabled = True cmdadd.Enabled = FalseEnd SubPrivate Sub cmdexit_Click() Unload MeEnd Sub

Private Sub cmdfirst_Click() On Error Resume Next myset.MoveFirst filltxt

Page 340: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Creating ActiveX Controls MS Visual Basic 6 Programming Introduction

328 V0.1

End Sub

Private Sub cmdlast_Click() On Error Resume Next myset.MoveLast filltxtEnd Sub

Private Sub cmdnext_Click() On Error Resume Next myset.MoveNext filltxtEnd Sub

Private Sub cmdpre_Click() On Error Resume Next myset.MovePrevious filltxtEnd Sub

Private Sub cmdsave_Click() myset(0) = Text1.Text myset(1) = Val(Text2.Text) myset.Update myset.Requery cmdfirst_Click cmdsave.Enabled = False cmdadd.Enabled = True cmdedit.Enabled = TrueEnd Sub

Private Sub Form_Load() newdatabase opendb myset.MoveFirst Text1.Text = myset(0) Text2.Text = myset(1) cmdsave.Enabled = FalseEnd Sub

Public Sub opendb()Set mydb = DBEngine.Workspaces(0).OpenDatabase("d:\raj\dao.mdb", ,_ False)Set myset = mydb.OpenRecordset("CConvert", dbOpenDynaset)End Sub

Public Sub filltxt() Text1.Text = myset(0) Text2.Text = myset(1)End Sub

Public Sub enatxt(t As Boolean) cmdfirst.Enabled = t cmdnext.Enabled = t cmdpre.Enabled = t cmdlast.Enabled = tEnd Sub

Page 341: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Creating ActiveX Controls

V0.1 329

• Write the following code in the code window of UserControl,

Option ExplicitDim frm As New Form1Dim a1 As Integer, b1 As Integer, a3 As Integer, b3 As IntegerDim a2 As String, b2 As StringPrivate Sub cmdadd_Click() Form1.Show Form1.ZOrderEnd Sub

Private Sub DBCombo1_lostfocus() a2 = DBCombo1.Text b2 = DBCombo2.Text cal a2, b2 If a2 = b2 Then Text4.Text = Val(Text1.Text) Label1.Caption = "Convertion Of Currency From " & a2 & " To " & b2 Else Text4.Text = (a1 / b1) * Val(Text1.Text) Label1.Caption = "Convertion Of Currency From " & a2 & " To " & b2 End IfEnd Sub

Private Sub Text1_lostfocus() DBCombo2.SetFocusEnd Sub

Private Sub UserControl_Initialize() Data1.DatabaseName = App.Path & "\dao.mdb" Data2.DatabaseName = App.Path & "\dao.mdb" Data3.DatabaseName = App.Path & "\dao.mdb" Data1.RecordSource = "select * from CConvert" Data1.RefreshEnd Sub

Public Sub cal(a As String, b As String) If Trim(UCase(a)) = Trim(UCase(b)) Then Data2.RecordSource = "select rate from CConvert where currency='" & a_& "'" Data2.Refresh a1 = Data2.Recordset(0) Else Data2.RecordSource = "select rate from CConvert where currency='" & a_ & "'" Data2.Refresh Data3.RecordSource = "select rate from CConvert where currency='" & b_ & "'" Data3.Refresh a1 = Data2.Recordset(0) b1 = Data3.Recordset(0) End IfEnd Sub

Public Sub dp(a As Integer, b As Integer) Text4.Text = (a / b) * Val(Text1.Text)

Page 342: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Creating ActiveX Controls MS Visual Basic 6 Programming Introduction

330 V0.1

End Sub

• Go to Usercontrol properties in project menu and change Project Name as "Conversion"and Project Description as "Ax Currency Conversion"

• Save the project and make .OCX file.

• Now open a new Standard .EXE Project.

• Go to Components in the project menu and select "Ax Currency Conversion".

• You can see that a new control is add to your toolbox.

• Select that Control and place it on the grid.

• Save the Project and run it.

Page 343: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

V0.1 331

Creating & Using ActiveX Documents

Objectives

In this Chapter, you will learn about Visual Basic DevelopmentEnvironment. You will also create your first VB 6.0Application.

• Introduction to ActiveX Documents

• ActiveX Document Containers

• ActiveX Documents Vs Embedded Objects

• ActiveX Documents in VB

• The UserDocument Object

• Working with ActiveX Document Projects

• Elements of an ActiveX Document Project

• Creating a new ActiveX Document Project

• Converting a Standard EXE Project

• Compiling an ActiveX Document Project

• Siting an ActiveX Document

Introduction to ActiveX Documents

Initially, ActiveX documents were a proprietary Microsoft technology used by the Binderapplication included with Microsoft Office. This application enabled users to group a set ofrelated Office documents together in one application, regardless of the Office application or type

of data. In conjunction with the underlying COM technology, ActiveX objects and ActiveXdocument containers support additional interfaces that enable us to create document objects (orforms).

Page 344: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Creating and Using ActiveX Documents MS Visual Basic 6 Programming Introduction

332 V0.1

ActiveX Document Containers

The underlying OLE document technology on which ActiveX documents are based enables

objects to be hosted within a container application. A container application is also referred to asan ActiveX document container.

The primary aspect of ActiveX document functionality is its effect on the user interface. An

ActiveX document fills the display area of the container, and gives the container the ability totransform itself to look and act just like the server application. An ActiveX document container isusually a stand-alone application, such as Internet Explorer. For example, when we start

Microsoft word, we are really launching the Word application as a container for its documentobject. When we start a Word document object from Internet Explorer, Word is launched as aserver that provides the document to another container.

ActiveX Documents Vs. Embedded Objects

Having evolved from OLE document objects, ActiveX documents have significantly enhancedthe capabilities of visual editing. Visual editing is the process of editing an embedded objectwithin the window of its container by using tools from its server. Instead of activating just one

embedded object, an ActiveX document can represent an entire document within an application.

An example of this enhanced capabilities is a comparison between a Word object embedded inanother application such as Microsoft Excel, and an ActiveX document object created with Word

that opens in Internet Explorer. With the ActiveX document, we have the ability to view andprint headers and footers. With the embedded Word object, we do not have this capability. Thisis because ActiveX documents implement additional interfaces that extend the functionality of

embedded objects, and give more server functionality to the client application. In this case, Wordacts as the server application to provide an ActiveX document to the client application (InternetExplorer).

ActiveX Documents in VB

In VB, we create an ActiveX document by adding a UserDocument object to the designer

provided by VB for ActiveX documents. The UserDocument object is the foundation for allActiveX documents.

Page 345: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Creating and Using ActiveX Documents

V0.1 333

The UserDocument Object

The UserDocument Object is similar in functionality to the UserControl object, including its

support for properties and methods. Like the UserControl object the UserDocument object canfire events, support callbacks, and supply asynchronous server notification. The UserDocumentobject also implements interfaces that enable it to be hosted within a document container.

Working with ActiveX Document Projects

To create an ActiveX document, we work in an ActiveX project. VB includes templates forcreating a new ActiveX project, or we can convert an existing Standard EXE project to an ActiveXproject.

Elements of an ActiveX Document Project

We can create an ActiveX document as either an .exe or a .dll file. In either case, the ActiveX

project for the ActiveX document must contain at least one UserDocument object by default. Tocreate either of these type of files, we add controls, any additional forms, and code modules tothe UserDocument object and then add code for the controls.

When we compile the ActiveX project, an .exe or a .dll file will be created, as well as a VBdocument (.vbd) file. To open the ActiveX document in a browser such as Internet Explorer,users must be able to navigate to the .vbd file.

The following two-types of files apply to user documents

.dob files

VB stores user documents in text files with a .dob extension. These files contain the source codeand property values of the UserDocument object and its controls

.dox files

VB stores any graphical elements in files with a .dox extension. These files, such as bitmaps areused for the controls of a UserDocument object.

The .dob and .dox files define the appearance and interface of an ActiveX document, including itsproperties, events, and methods. These two files area analogous to the Standard EXE project files.frm and .frx files respectively.

Page 346: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Creating and Using ActiveX Documents MS Visual Basic 6 Programming Introduction

334 V0.1

Creating a New ActiveX Project

VB provides templates for creating a new ActiveX project. To create an ActiveX document, we

use either the ActiveX Document DLL template or the ActiveX Document EXE template.

The ActiveX projects used for ActiveX documents differ from standard EXE projects in two ways.ActiveX projects are compiled into .exe or .dll files, and contain a default Userdocument, or in the

case of an ActiveX control project, a default Usercontrol.

Converting a Existing Standard EXE Project

To convert an existing project to an ActiveX project

• From the Add-Ins menu, select ActiveX Document Migration Wizard

If this command is unavailable, use the Add-In manager to add it to the menu.

• If we want to skip the introduction screen for future use, click skip this screen in thefuture, and then click Next

• In the form selection screen, select the form that we want to convert and then click Next

• In the Options screen, select the following options, and then click Next

a. Comment out invalid code

b. Remove original forms after conversion

c. Convert to an ActiveX EXE

• In the Finished screen, click No when asked if we want to see a Summary Report after thewizard is done, click Save current settings as default , and then click finish

Compiling an ActiveX Document Project

When we create an ActiveX document as either an in-process (.dll) or out-of-process (.exe)

component, the component functions as an Automation server. An Automation server enablesother ActiveX container application to host and activate the document.

When we compile or run a project, VB creates a document (.vbd) file. The .vbd file is an OLE

structured storage, which means that data in the file can be accessed and manipulated throughstandard OLE interfaces.

Page 347: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Creating and Using ActiveX Documents

V0.1 335

Where to Site an ActiveX Document

Before we can use an ActiveX document, we must place it within a container. Connecting an

ActiveX document to its container is known as siting, which plays a key role in determiningActiveX document event behavior. Siting enables an ActiveX document to implement itsfunctionality.

To run an ActiveX document in its container

• Create a file association for the .vbd file and the container application.

• Switch to VB, and run the application. User documents and forms will not be visiblebecause the output from the project is in the .vbd file

• Switch to either My Computer or the Windows Explorer, and run the .vbd file. Thiscauses the .vbd file to be loaded into the container application.

• After making sure that the .vbd file is loaded correctly in the container application, closethe container, switch to VB, and explicitly end the application.

Page 348: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Creating and Using ActiveX Documents MS Visual Basic 6 Programming Introduction

336 V0.1

Notes

Page 349: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

V0.1 337

Appendix 1 - Standard Menu Bar

File, Edit, View, Project, Debug, Run, Query, Diagram, Tools, Add-Ins, Window and Help are the

menu options under the Standard Menu Bar.

The File menu has options for file handling. Some of the important sub-menus of the FILEmenu are as follows:

* Create a new project* Open an existing project* Add a project to an existing project group* Remove a project* Save a project* Save a form* Make the project as executable* Make the project group* Exit

The Edit menu has options for locating and editing objects. Some of the important sub-menus of the EDIT menu are as follows:

* Undo* Redo* Cut* Copy* Paste* Delete* Select all* Find* Find next* Replace

The View allows you to view the code, objects, windows etc. Some of the important sub-menus of the VIEW menu are as follows:

* Code* Object* Object browser* Immediate window* Locals window* Watch window* Project explorer* Properties window* Form layout window* Property pages* Tool box* Toolbars - debug, edit, form editor, standard, customize

Page 350: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

Appendix 1 - Standard Menu Bar MS Visual Basic 6 Programming Introduction

338 V0.1

The Project menu has options to allow the user to add new objects to the project. Some of theimportant sub-menus of the Project menu are as follows:

* Add Form* Add MDI Form* Add Module* Add Class Module* Add User Control* Add Property Page* Add User Documents* Add Web Class* Add Data Report* Add DHTML page* Add data environment* References* Components* Project properties

The Format menu provides options to arrange the objects in a project.Some of the important sub-menus of the FORMAT menu are as follows:

* Align* Make same size* Horizontal spacing* Vertical spacing* Lock Controls

The Debug menu has options to debug the project. Some of the important sub-menus of theDEBUG menu are as follows:

* Step into* Step over* Add watch* Toggle break points* Clear all break points

The Run menu has options to execute and stop our applications. Some of the important sub-menus of the RUN menu are as follows:

* Start* Break* End* Restart

The Query menu has options to write and check syntax of queries on tables. Some of theimportant sub-menus of the QUERY menu are as follows:

* Run* Verify SQL syntax* Group by* Change type* Sort ascending* Sort descending* Select all rows from table name

Page 351: MS Visual Basic 6.0 Programming Introduction · 2018-09-01 · MS Visual Basic 6 Programming Introduction V0.1 v ISO 9001 Quality in Education Historically, our aim has been to equip

MS Visual Basic 6 Programming Introduction Appendix 1 - Standard Menu Bar

V0.1 339

The Diagram menu has options to add or remove input sources and specify columns forordering the query. Some of the important sub-menus of the DIAGRAM menu are as follows:

* Add related tables* Show relationship labels* Arrange tables* Arrange selections

The Tools menu has options create sub-programs and to create user defined menus. Some ofthe important sub-menus of the TOOLS menu are as follows:

* Add procedures* Procedure attributes* Menu editor* Options* Source safe

The Add-Ins menu provides facility to add the Wizards and handling databases. Some of theimportant sub-menus of the ADD-INS menu are as follows:

* Visual Data Manager* Add-in Manager

The Window menu allows us to organize the various windows available in VB 6.0. Some ofthe important sub-menus of the WINDOWS menu are as follows:

* Tile horizontally* Tile vertically* Cascade* Arrange icons

The Help menu provides HELP on VB 6.0.