visual basic course material

161
qwertyuiopasdfghjklzxcvbnmqwertyui opasdfghjklzxcvbnmqwertyuiopasdfgh jklzxcvbnmqwertyuiopasdfghjklzxcvb nmqwertyuiopasdfghjklzxcvbnmqwer tyuiopasdfghjklzxcvbnmqwertyuiopas dfghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq wertyuiopasdfghjklzxcvbnmqwertyuio pasdfghjklzxcvbnmqwertyuiopasdfghj klzxcvbnmqwertyuiopasdfghjklzxcvbn mqwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasdf ghjklzxcvbnmqwertyuiopasdfghjklzxc vbnmqwertyuiopasdfghjklzxcvbnmrty uiopasdfghjklzxcvbnmqwertyuiopasdf ghjklzxcvbnmqwertyuiopasdfghjklzxc vbnmqwertyuiopasdfghjklzxcvbnmqw ertyuiopasdfghjklzxcvbnmqwertyuiop asdfghjklzxcvbnmqwertyuiopasdfghjkl Visual Basic BSc IT Semester Two Prof. Teena Bagga

Upload: technicianccna

Post on 05-Nov-2015

24 views

Category:

Documents


1 download

DESCRIPTION

Amity VB Course Material.

TRANSCRIPT

  • qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmrtyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjkl

    Visual Basic BSc IT

    Semester Two

    Prof. Teena Bagga

  • Amity University, UP (PAN African eNetwork Project) 2

    Preface

    Visual Basic (VB) has become such a popular programming language for several reasons.

    VB is easy to learn, which makes it an excellent tool for understanding elementary

    programming concepts. In addition, it has evolved into such a powerful and popular product

    that skilled Visual Basic programmers are in demand in the job market.

    Visual Basic is designed to allow the programmer to develop applications without the

    complexity generally associated with programming. With very little effort, the programmer can

    design a screen that holds standard elements such as buttons, check boxes, radio buttons, text

    boxes, and list boxes

    This book offers instruction in Visual Basic programming to BSc-IT students as per the

    syllabus. After having studied the book and completed the programming exercises, students

    should be able to create small to medium-sized business applications involving databases that

    run on desktops.

    It is believed effective programmers must combine theory with practice, so they can adapt to

    ever-changing computing environments. This book might not cover the breadth of topics found

    in some professional reference books, but its theoretical concepts, step-by-step learning approach

    and quiz after each chapter will make it useful in the classroom.

  • Amity University, UP (PAN African eNetwork Project) 3

    INDEX

    Chapter No. Name Page no.

    Syllabus 4

    1 Introduction to Visual Basic 6

    2 Programming Controls 37

    3 VB Standard Controls 72

    4 Working with Forms & Menues 108

    5 Database Programming 129

    References 161

    Assignments 162

  • Amity University, UP (PAN African eNetwork Project) 4

    Syllabus Objective :

    After studying this course, Students will appreciate the Event Driven programming and

    will be able to design and write small software applications using visual Basic.

    Module I

    Introduction to Visual Basic Integrated Development Environment (IDE) features, VB

    editor, Anatomy of a form, Working with form properties setting forms properties,

    Introducing form events & form methods.

    Module II

    Variables in Visual Basic: Declaring variables, Data types, The scope of a variable

    Module level variables, constants, Creating your own constants, scope of a Constant,

    converting data types, arrays, declaring arrays, fixed size arrays, dynamic arrays, Writing

    code in Visual Basic: The anatomy of a procedure, subroutine and functions, language

    constructs: for, next, the while loop, select case ,Exit statement, with structure.

    Module III

    Selecting & Using controls: Introducing to standard controls, Command buttons, Text

    buttons, Text buttons, option buttons, check boxes, frame controls, list boxes, combo

    boxes, Image objects, picture boxes, Timer, scroll bars, file system controls

    Module IV

    Working with Multiple Forms, Creating , adding, removing Forms in project, Hide, Show

    Method, Load, Unload, Statement, Me Keyword, Referring to Objects on a Different

    Forms.

  • Amity University, UP (PAN African eNetwork Project) 5

    Module -V

    Accessing Database File using ADO and ODBC, Creating the database files for use by

    Visual Basic ( Using MS-Access), Using the Data Control , setting its property, Using

    Data Control with forms, navigating the database in code ( the recordset object using the

    movenext, movepreviouse, movefirst & movelast methods , updating a database file

    ( adding, deleting , editing records ).

  • Amity University, UP (PAN African eNetwork Project) 6

    Chapter-1

    Introduction to Visual Basic

    OBJECTIVES

    After going through this lesson you will be in a position to Understand

    Event-driven programming language

    Integrated Development Environment (IDE)

    Menu Bar

    Tool Bar

    Project Explorer

    Properties window

    Form Layout Window

    Toolbox

    Form Designer

    Object Browser

    How to create and run a Visual Basic Application

  • Amity University, UP (PAN African eNetwork Project) 7

    1.1 Introduction

    Before we begin Visual Basic 6 programming, let us understand some basic

    concepts of programming. A computer program is an organized list of instructions

    that, when executed, causes the computer to behave in a predetermined manner.

    Without programs, computers are useless. Therefore, programming means

    designing or creating a set of instructions to ask the computer to carry out certain

    jobs which normally are very much faster than human beings can do.

    A lot of people think that computer CPU is a very intelligent thing, which in

    actual fact it is a dumb and inanimate object that can do nothing without human

    assistant. The microchips of a CPU can only understand two distinct electrical

    states, namely, the on and off states, or 0 and 1 codes in the binary system. So, the

    CPU only understands a combinations of 0 and 1 codes, a language which we

    called machine language. Machine language is extremely difficult to learn and it

    is not for us laymen to master it easily. Fortunately , we have many smart

    programmers who wrote interpreters and compilers that can translate human

    language-like programs such as BASIC into machine language so that the

    computer can carry out the instructions entered by the users. Machine language is

    known as the primitive language while Interpreters and compilers like Visual

    Basic are called high-level language. Some of the high level computer languages

    beside Visual Basic are Fortran, Cobol, Java, C, C++, Turbo Pascal, and etc .

    VISUAL BASIC is a high level programming language which was evolved from

    the earlier DOS version called BASIC. BASIC means Beginners' All-purpose

    Symbolic Instruction Code. It is a very easy programming language to learn. The

    codes look a lot like English Language. Different software companies produced

    different version of BASIC, such as Microsoft QBASIC, QUICKBASIC,

    GWBASIC ,IBM BASICA and so on. However, it seems people only use

    Microsoft Visual Basic today, as it is a well developed programming language

  • Amity University, UP (PAN African eNetwork Project) 8

    and supporting resources are available everywhere. Now, there are many versions

    of VB exist in the market, the most popular one and still widely used by many VB

    programmers is Visual Basic 6.

    With VB 6, you can create any program depending on your objective. For

    example, you can create educational programs to teach business, economics,

    engineering, computer science, accountancy , financial management, information

    system and more to make teaching more effective and interesting. For business,

    you can also create business programs such as inventory management system ,

    point-of-sale system, payroll system, financial program as well as accounting

    program to help manage your business and increase productivity. For those of you

    who like games and working as games programmer, you can create those

    programs as well. Indeed, there is no limit to what program you can create !

  • Amity University, UP (PAN African eNetwork Project) 9

    The advantages of Visual Basic:

    It's simple language. Things that may be difficult to program with other

    language, Can be done in Visual Basic very easily.

    Because Visual Basic is so popular, there are many good resources (Books,

    Web sites, News groups and more) that can help you learn the language.

    You can find the answers to your programming problems much more easily

    than other programming languages.

    You can find many tools (Sharewares and Freewares) on the internet that will

    Spare you some programming time. For example, if you want to ping a user

    over the internet in your program, Instead of writing the ping function

    yourself, you can download a control that does it, and use it in your program.

    Compare to other languages, Visual Basic have the widest variety of tools

    that you can download on the internet and use in your programs.

    The disadvantages of Visual Basic:

    Visual Basic is powerful language, but it's not suit for programming really

    sophisticated games.

    It's much more slower than other languages.

  • Amity University, UP (PAN African eNetwork Project) 10

    1.2 Getting Started

    Visual Basic is initiated by using the Programs option > Microsoft Visual Basic

    6.0 > Visual Basic 6.0. Clicking the Visual Basic icon, we can view a copyright

    screen enlisting the details of the license holder of the copy of Visual Basic 6.0.

    Then it opens in to a new screen as shown in figure below, with the interface

    elements Such as MenuBar, ToolBar, The New Project dialog box. These

    elements permit the user to buid different types of Visual Basic applications.

    The Visual Basic startup dialog box

  • Amity University, UP (PAN African eNetwork Project) 11

    You can choose to either start a new project, open an existing project or select a

    list of recently opened programs. A project is a collection of files that make up

    your application. There are various types of applications that we could create,

    however, we shall concentrate on creating Standard EXE programs (EXE means

    executable program). Now, click on the Standard EXE icon to go into the actual

    Visual Basic 6 programming environment.

    Application

    An application is a collection of objects that work together to accomplish

    something useful. In VB the application is called a Project. A Project could be a

    the management of a Library, the calculation of salaries, or the Payroll for 1000

    employees ... With VB 6, you can create any application depending on your

    objective. For example, if you are a college or university lecturer, you can create

    educational programs to teach business, economics, engineering, computer

    science, accountancy , financial management, information system and more to

    make teaching more effective and interesting. If you are in business, you can also

    create business programs such as inventory management system , point-of-sale

    system, payroll system, financial program as well as accounting program to help

    manage your business and increase productivity. For those of you who like games

    and working as games programmer, you can create those programs as well.

    Indeed, there is no limit to what program you can create !

    Object

    An object is a piece of software that has properties and functions that can be

    manipulated. You must be somewhat familiar with the Windows environment. A

    window is an object. It has properties: size, color, position on the screen, etc. (The

    purists among you may want to talk about a class rather than an object but, at this

    point we just want to keep it simple, and the underlying concept is the same). The

    window has functions, also called methods, that can be manipulated: change the

  • Amity University, UP (PAN African eNetwork Project) 12

    size, move it around, open it and close it. You do not have to write code to resize

    a window - you just click and drag. But somebody had to write code at some

    point. Fortunately for us, when they did they put it all in a nice little package and

    called it a window object. Now, whenever you need a window in your Project you

    can make a copy of the window object, change its properties for color or size very

    easily, and paste it where you want it. Then you can use its built-in methods to

    open it, close it when you want or resize it whenever necessary. When you create

    an application using objects and combining them to produce results, you are

    working in an object-oriented environment.

    Event-driven

    VISUAL BASIC is a VISUAL and events driven Programming Language. These

    are the main divergence from the old BASIC. In BASIC, programming is done in

    a text-only environment and the program is executed sequentially. In VB,

    programming is done in a graphical environment. In the old BASIC, you have to

    write program codes for each graphical object you wish to display it on screen,

    including its position and its color. However, In VB , you just need to drag and

    drop any graphical object anywhere on the form, and you can change its color any

    time using the properties windows.

    On the other hand, because users may click on a certain object randomly, so each

    object has to be programmed independently to be able to response to those actions

    (events). Therefore, a VB Program is made up of many subprograms, each has its

    own program codes, and each can be executed independently and at the same time

    each can be linked together in one way or another.

    Earlier to produce an application in COBOL, a procedural language, you write

    COBOL source programs, you compile them into machine code and then you run

    them via a control interface such as JCL. A program can contain 1000's of lines of

    source code and could run for hours with no human intervention. In fact, in large

    installations, a job stream can consist of a dozen programs, all automatically

  • Amity University, UP (PAN African eNetwork Project) 13

    accepting input from the previous program and producing output for the next. The

    programmer can be blissfully unaware that the program has run unless something

    catastrophic happens.

    In a VB project, the processes that occur have to be associated with events. An

    event is something that happens - the user clicks on a button, a form is opened, the

    result of a calculation is too large. The operation is event-driven because

    everything that executes does so as the result of some kind of event. The role of

    the programmer is to anticipate the events and to write the code that will be

    executed when the event occurs. A VB application is interactive in the sense that

    the user is constantly interacting with the program. The user inputs a Customer Id,

    the program checks the Id in the database and immediately brings up the

    customer's file or displays a message that the particular Id is invalid.

    Opening an existing Visual Basic project.

    Microsoft have included some freebies with visual basic to show its capabilities

    and functions. Dismantling or modifying these sample projects is a good way to

    understand what is happening at runtime. These files can be located at your

    default directory /SAMPLES/

    To Open these projects choose 'Open Project' from the 'File' menu. Then Double

    click on the samples folder to open the directory then Double click on any project

    to load it.

  • Amity University, UP (PAN African eNetwork Project) 14

    1.3 The Integrated Development Environment

    One of the most significant changes in Visual Basic 6.0 is the Integrated

    Development Environment (IDE). IDE is a term commonly used in the

    programming world to describe the interface and environment that we use to

    create our applications. It is called integrated because we can access virtually all

    of the development tools that we need from one screen called an interface. The

    IDE is also commonly referred to as the design environment, or the program.

    Before learning the Development Environment we will learn visual basic is

    somewhat like learning for a test you must know where all the functions belong

    and what their purpose is. First we will start with labelling the development

    environment. The Visual Basic IDE is made up of a number of components.

    When we start Visual Basic, we are provided with a VB project. A VB project is a

    collection of the following modules and files.

    The global module( that contains declaration and procedures)

    The form module(that contains the graphic elements of the VB

    application along with the instruction )

    The general module (that generally contains general-purpose

    instructions not pertaining to anything graphic on-screen)

    The class module(that contains the defining characteristics of a class,

    including its properties and methods)

    The resource files(that allows you to collect all of the texts and bitmaps

    for an application in one place)

    On start up, Visual Basic will displays the following windows :

    The Blank Form window

    The Project window

  • Amity University, UP (PAN African eNetwork Project) 15

    The Properties window

    It also includes a Toolbox that consists of all the controls essential for

    developing a VB Application. Controls are tools such as boxes, buttons, labels

    and other objects draw on a form to get input or display output. They also add

    visual appeal.

    Menu Bar

    Tool Bar Project

    Explorer

    Properties Windows

    Form Layout

    Tool Box

  • Amity University, UP (PAN African eNetwork Project) 16

    Lets discuss the various parts :

    Menu Bar

    Tool Bar

    Project Explorer

    Properties window

    Form Layout Window

    Toolbox

    Form Designer

    Object Browser

    Menu Bar

    Menu Bar displays the commands that are required to build an application. The

    main menu items have sub menu items that can be chosen when needed.

    Tool Bar

    The toolbars in the menu bar provide quick access to the commonly used

    commands and a button in the toolbar is clicked once to carry out the action

    represented by it.

  • Amity University, UP (PAN African eNetwork Project) 17

    Toolbox

    The Toolbox contains a set of controls that are used to place on a Form at design

    time thereby creating the user interface area. Additional controls can be included

    in the toolbox by using the Components menu item on the Project menu. A

    Toolbox is represented in figure shown below.

  • Amity University, UP (PAN African eNetwork Project) 18

    Control Description

    Pointer Provides a way to move and resize the controls form

    PictureBox Displays icons/bitmaps and metafiles. It displays text or

    acts as a visual container for other controls.

    TextBox Used to display message and enter text.

    Frame Serves as a visual and functional container for controls

    CommandButton Used to carry out the specified action when the user

    chooses it.

    CheckBox Displays a True/False or Yes/No option.

    OptionButton

    OptionButton control which is a part of an option group

    allows the user to select only one option even it displays

    mulitiple choices.

    ListBox Displays a list of items from which a user can select one.

    ComboBox

    Contains a TextBox and a ListBox. This allows the user to

    select an item from the dropdown ListBox, or to type in a

    selection in the TextBox.

    HScrollBar and

    VScrollBar

    These controls allow the user to select a value within the

    specified range of values

    Timer Executes the timer events at specified intervals of time

    DriveListBox Displays the valid disk drives and allows the user to select

    one of them.

    DirListBox Allows the user to select the directories and paths, which

    are displayed.

  • Amity University, UP (PAN African eNetwork Project) 19

    FileListBox Displays a set of files from which a user can select the

    desired one.

    Shape Used to add shape (rectangle, square or circle) to a Form

    Line Used to draw straight line to the Form

    Image Used to display images such as icons, bitmaps and

    metafiles. But less capability than the PictureBox

    Data Enables the use to connect to an existing database and

    display information from it.

    OLE Used to link or embed an object, display and manipulate

    data from other windows based applications.

    Label Displays a text that the user cannot modify or interact with.

  • Amity University, UP (PAN African eNetwork Project) 20

    Project Explorer

    On the right side of the screen, just under the tollbar, is the Project Explorer

    window. The Project Explorer as shown in in figure servres as a quick reference

    to the various elements of a project namely form, classes and modules. All of the

    object that make up the application are packed in a project. A simple project will

    typically contain one form, which is a window that is designed as part of a

    program's interface. It is possible to develop any number of forms for use in a

    program, although a program may consist of a single form. The Project explorer

    window gives you a tree-structured view of all the files inserted into the

    application. In addition to forms, the Project Explorer window also lists code

    modules and classes. You can expand these and collapse branches of the views

    to get more or less detail (Project explorer). The project explorer window

    displays forms, modules or other separators which are supported by the visual

    basic like class'es and Advanced Modules. If you want to select a form on its own

    simply double click on the project explorer window for a more detailed look. And

    it will display it where the Default form is located.

    Toggle Folder

    View Code

    View Object Project Name

    Forms Folder

    Form Module

  • Amity University, UP (PAN African eNetwork Project) 21

    Properties Window

    The Properties Window is under the Project Explorer window. The Properties

    Window exposes the various characteristics of selected objects. Each and every

    form in an application is considered an object. Now, each object in Visual Basic

    has characteristics such as color and size. Other characteristics affect not just the

    appearance of the object but the way it behaves too. All these characteristics of an

    object are called its properties. Thus, a form has properties and any controls

    placed on it will have properties too. All of these properties are displayed in the

    Properties Window.

    When you click on different controls the Properties Window changes slightly this

    is due to different controls having different functions. When you use the

    command ( ) you will find that a new set of properties come up the following

    will provide a description and a property.

  • Amity University, UP (PAN African eNetwork Project) 22

    Form Layout Window

    Form layout Window is visible in the lower right corner of the Visual Basic IDE.

    It is used to determine the initial position of the form in your application.

  • Amity University, UP (PAN African eNetwork Project) 23

    Form Designer The form designed is the main window in the middle of the screen, and in it you

    design and edit the applications user interface. The Form Designer displays two

    windows for each form :

    The Form itself(the elements of the visible user interface)

    The Code window (the code behind the elements of the form)

    To switch between the two views, click the little icons (View Code and View

    Form) at the top of the Project Explorer.

  • Amity University, UP (PAN African eNetwork Project) 24

    Object Browser

    The Object Browser allows us to browse through the various properties, events

    and methods that are made available to us. It is accessed by selecting Object

    Browser from the View menu or pressing the key F2. The left column of the

    Object Browser lists the objects and classes that are available in the projects that

    are opened and the controls that have been referenced in them. It is possible for us

    to scroll through the list and select the object or class that we wish to inspect.

    After an object is picked up from the Classes list, we can see its members

    (properties, methods and events) in the right column.

    A property is represented by a small icon that has a hand holding a piece of paper.

    Methods are denoted by little green blocks, while events are denoted by yellow

    lightning bolt icon.

  • Amity University, UP (PAN African eNetwork Project) 25

    1.4 Creating Your First Application

    In this section, we will not go into the technical aspects of Visual Basic

    programming yet, what you need to do is just try out the examples below to see

    how does in VB program look like:

    First of all, you have to launch Microsoft Visual Basic 6. Normally, a default

    form with the name Form1 will be available for you to start your new project.

    Now, double click on Form1, the source code window for Form1 as shown in

    figure

    will appear. The top of the source code window consists of a list of objects and

    their associated events or procedures. In the above figure, the object displayed is

    Form and the associated procedure is Load.

  • Amity University, UP (PAN African eNetwork Project) 26

    When you click on the object box, the drop-down list will display a list of objects

    you have inserted into your form as shown in figure

    Here, you can see a form with the name Form1, a command button with the name

    Command1, a Label with the name Label1 and a Picture Box with the name

    Picture1. Similarly, when you click on the procedure box, a list of procedures

    associated with the object will be displayed as shown in figure.

  • Amity University, UP (PAN African eNetwork Project) 27

    Some of the procedures associated with the object Form1 are Activate, Click,

    DblClick (which means Double-Click) , DragDrop, keyPress and more. Each

    object has its own set of procedures. You can always select an object and write

    codes for any of its procedure in order to perform certain tasks.

    Do not worry about the beginning and the end statements (i.e. Private Sub

    Form_Load.......End Sub.); Just key in the lines in between the above two

    statements exactly as are shown here.

    Private Sub Form_Load ( )

    Form1.show

    Print Welcome to Visual Basic tutorial

    End Sub

    In order to display the output of the program, we have to add the Form1.show

    statement like and the command Print does not mean printing using a printer but

    it means displaying the output on the computer screen.

    Once an application is loaded it can be run by click on the icon from the

    toolbar, to pause press and to terminate use . Or press F5 to run the

    program and you will get the output as shown in figure :

  • Amity University, UP (PAN African eNetwork Project) 28

    You can also perform arithmetic calculations as shown in example

    Private Sub Form_Activate ( )

    Print 20 + 10

    Print 20 - 10

    Print 20 * 10

    Print 20 / 10

    End Sub

  • Amity University, UP (PAN African eNetwork Project) 29

    VB uses * to denote the multiplication operator and / to denote the division

    operator. The output is shown in figure, where the results are arranged vertically.

    You can also use the + or the & operator to join two or more texts (string)

    together like in this example :

    Private Sub

    A = Tom

    B = likes"

    C = to"

    D = eat"

    E = burger"

    Print A + B + C + D + E

    End Sub

    Private Sub

    A = Tom

    B = likes"

  • Amity University, UP (PAN African eNetwork Project) 30

    C = to"

    D = eat"

    E = burger"

    Print A & B & C & D & E

    End Sub

    The Output of the above Example will be :

  • Amity University, UP (PAN African eNetwork Project) 31

    1.5 Save your work to disk

    Use the Windows Explorer or any desktop windows to check that all files have

    been saved. There should be one Visual Basic Project(.VBP) file and

    separate Form (.FRM) and Module (.BAS) files for each form and module used

    in the current project.

    1.6 Making *.exe To make an executable from a project choose Make project.exe from the

    'File' menu. Then click once on the Make project.exe choose a default location to

    store your executable, you can also change some advanced options by clicking on

    the Options. tag before saving your exe

    The above image will be displayed in the comment's value type some comments

    company name

    etc... The Title tag represents the caption you will see if you press Control + Alt

    + Del. And the icon is the icon that will be available on the execute icon. As you

    can see it is quite simple to understand. All the comments, data and name appear

    when you click on the compiled (execute) exe and click properties.

  • Amity University, UP (PAN African eNetwork Project) 32

    1.6 Using the Immediate Window

    You can interrupt an application by pressing Ctrl+Break or choosing Run>Break.

    The application will be interrupted but will be terminated. At the bottom of the

    screen, you will see a window named Immediate, as shown in this figure :

    When you issue Visual Basic commands in this window, they execute

    immediately. You can use the immediate window when you are designing and

    debugging applications to perform three common operations:

    Execute Visual Basic statements to perform simple tasks such as calculations

    Examines the values of the controls on the Form

    Set the values of the controls on the Form

    These are extremely useful operations during an applications design and

    debugging phase.

  • Amity University, UP (PAN African eNetwork Project) 33

    1.7 Few development techniques

    write the simplest program that you understand and make it work - even if it

    doesn't have color or fancy fonts, test it and then save it;

    make a copy of your previous working program and code one or two

    improvements in the copy - if you become stuck and can't recover, destroy the

    copy, go back to the previous version, make a new copy and start again;

    repeat for every improvement you make, using small steps so that if something

    does go wrong its easier to identify the source of the problem (if you made 12

    corrections in a program and then it doesn't work, how will you know which of

    the changes is causing the problem?)

    The user is in control. The user must feel he is in charge of the application. He

    must have a certain amount of control over such things as window size, window

    position, choice of fonts, etc. There should definitely be a "Preferences" item in

    the menu.

    Consistency is maintained throughout the application. The user can move to any

    part of the application and not have to re-learn how things work. Consistency in

    the choice of icons, in date formats, in error messages means that the user can

    concentrate on the work. As much as possible, the application should be

    consistent with Windows standard. For example, "Move to the Recycle Bin" is

    different from "Delete" - the user has come to expect that an item in the Recycle

    Bin can be recovered if need be.

    Application should be "forgiving", or "fault-tolerant". Users will make mistake. A

    single error should not bring the application crashing to the floor. If there is no

    room for errors, users will be afraid to experiment, to discover on their own how

    to do things. It will slow the learning process considerably.

  • Amity University, UP (PAN African eNetwork Project) 34

    Always supply feedback. The user should always know that something is going

    on, especially if it's in the background and may take several minutes to run.

    Display an hourglass or a progress meter or a status bar so that the user doesn't

    start to hit keys at random to get something to happen. It only takes a few seconds

    of inactivity for the user to get frustrated and think that the program is "hanging".

    Don't neglect esthetics. The visual aspect is important. The environment should be

    pleasing to the eye. The presentation style should help in understanding the

    information presented.

    Interface should be simple without being simplistic. There should be a balance

    between simplicity and functionality. Popup menus, for example, allow you to

    increase the functionality without having to encumber the screen with all kinds of

    details which are not used 95% of the time.

  • Amity University, UP (PAN African eNetwork Project) 35

    Quiz

    Q1. Visual Basic is a _________programming language.

    a. Object oriented

    b. Object Based

    c. Event driven

    d. Object Driven

    Q2. Visual Basic is ___________ language.

    a. high-level

    b. Low-level

    c. Machine-level

    d. None of the above

    Q3. In VB the application is called a

    a. File

    b. Module

    c. Project.

    d. Class

    Q4. IDE stand for

    a. Integrated Development Environment

    b. In-house Development Environment

    c. Immediate Development Environment

    d. Initial Development Environment

    Q5. The global module is

    a. that contains declaration and procedures b. that contains the graphic elements of the VB application along with the

    instruction

  • Amity University, UP (PAN African eNetwork Project) 36

    c. that generally contains general-purpose instructions not pertaining to

    anything graphic on-screen

    d. that contains the defining characteristics of a class, including its properties

    and methods

    Q6. The form module is

    a. that contains declaration and procedures

    b. that contains the graphic elements of the VB application along with the

    instruction

    c. that generally contains general-purpose instructions not pertaining to anything

    graphic on-screen

    d. that contains the defining characteristics of a class, including its properties and

    methods

    Q7. The resource files are

    a. that allows you to collect all of the texts and bitmaps for an application in one

    place

    b. that contains declaration and procedures

    c. that contains the graphic elements of the VB application along with the

    instruction

    d. that generally contains general-purpose instructions not pertaining to anything

    graphic on-screen

    Q8. OLE stands for

    a. Object Linking and Embedding

    b. Ongoing Linking and Embedding

    c. Object Linking the Environment

    d. Ongoing Locking the Environment

  • Amity University, UP (PAN African eNetwork Project) 37

    Chapter-2

    Programming Controls

    OBJECTIVES

    After going through this lesson you will be in a position to understand:

    Types of variables and constants. Variables in Visual Basic, Declaration of variables, Data types, The scope of a variable Module level variables, Constants, Creating your own constants, Scope of a Constant, Converting data types, arrays, declaring arrays, Fixed size arrays, Dynamic arrays, The anatomy of a procedure, subroutine and functions, Language constructs: for, next, the while loop, select case , Exit statement, with structure.

  • Amity University, UP (PAN African eNetwork Project) 38

    2.1 Visual Basic 6 (VB6) Modules and Operators

    Visual Basic like other languages uses building blocks such as Variables, Data

    Types, Procedures, Functions and Control Structures in its programming

    environment. This section will concentrates on the programming fundamentals of

    Visual Basic with the blocks specified.

    Modules

    Code in Visual Basic is stored in the form of modules. There are three kind of

    modules

    1. Form Modules

    2. Standard Modules and

    3. Class Modules.

  • Amity University, UP (PAN African eNetwork Project) 39

    A simple application may contain a single Form, and the code resides in that

    Form module itself. As the application grows, additional Forms are added and

    there may be a common code to be executed in several Forms. To avoid the

    duplication of code, a separate module containing a procedure is created that

    implements the common code. This is a standard Module. Class module (.CLS

    filename extension) are the foundation of the object oriented programming in

    Visual Basic. New objects can be created by writing code in class modules.

    Each module can contain:

    Declarations : May include constant, type, variable and DLL procedure

    declarations.

    Procedures : A sub function, or property procedure that contain pieces of

    code that can be executed as a unit.

  • Amity University, UP (PAN African eNetwork Project) 40

    2.2 Visual Basic 6 Variables Constant & Data types

    Variables & Constants

    A variable is a location in memory where a value can be stored during the

    execution of a Visual Basic application. Visual Basic variables are assigned

    names by the programmer when they are declared so that they can easily be

    referenced in other places in the application code.

    These values may either be declared as

    variable (in that once the value has been assigned it can be changed later in the Visual Basic code) or as

    constant (in that once the value has been assigned, it cannot be changed elsewhere in the code).

    Naming Rules

    These are the rules to follow when naming elements in VB - variables, constants,

    controls, procedures, and so on:

    A name must begin with a letter.

    May be as much as 255 characters long

    Must not contain a space or an embedded period or type-declaration

    characters used to specify a data type; these are ! # % $ & @

    Must not be a reserved word, Keywords

    The dash, although permissible, should be avoided because it may be

    confused with the minus sign. Instead of First-name use First_name or

    FirstName.

    Before learning how to declare variables and constants it is worth to understand

    the difference between variables and constants in Visual Basic. Both constants

    and variables provide a way to reserve memory locations for the storage of values

  • Amity University, UP (PAN African eNetwork Project) 41

    of various types (such as numbers, characters and strings). These memory

    locations are assigned names which can be used in Visual Basic code to reference

    these memory locations. For example, you might want to store the interest rate for

    a banking application. To do so you would declare a variable with a name of your

    choice (such as interestRate) and specify the variable as an Integer type (since it

    will be storing a number). Having declared the variable you can assign a value to

    it and read that value anywhere in your application code.

    The difference between variables and constants is that the value stored in a

    variable can be changed at any time after it has been created. The value assigned

    to a constant, as the name suggests, cannot be changed once it has been declared

    an initialized.

  • Amity University, UP (PAN African eNetwork Project) 42

    Data types in Visual Basic 6

    By default Visual Basic variables are of variant data types. The variant data type

    can store numeric, date/time or string data. When a variable is declared, a data

    type is supplied for it that determines the kind of data they can store. The

    fundamental data types in Visual Basic including variant are integer, long, single,

    double, string, currency, byte and boolean. Visual Basic supports a vast array of

    data types. Each data type has limits to the kind of information and the minimum

    and maximum values it can hold. In addition, some types can interchange with

    some other types. A list of Visual Basic's simple data types are given below.

    1. Numeric

    Byte Store integer values in the range of 0 - 255

    Integer Store integer values in the range of (-32,768) - (+ 32,767)

    Long Store integer values in the range of (- 2,147,483,468) - (+

    2,147,483,468)

    Single Store floating point value in the range of (-3.4x10-38) - (+

    3.4x1038)

    Double Store large floating value which exceeding the single data type

    value

    Currency store monetary values. It supports 4 digits to the right of decimal

    point and 15 digits to the left

    2. String

    Use to store alphanumeric values. A variable length string can store

    approximately 4 billion characters

  • Amity University, UP (PAN African eNetwork Project) 43

    3. Date

    Use to store date and time values. A variable declared as date type can store both

    date and time values and it can store date values 01/01/0100 up to 12/31/9999

    4. Boolean

    Boolean data types hold either a true or false value. These are not stored as

    numeric values and cannot be used as such. Values are internally stored as -1

    (True) and 0 (False) and any non-zero value is considered as true.

    5. Variant

    Stores any type of data and is the default Visual Basic data type. In Visual Basic

    if we declare a variable without any data type by default the data type is assigned

    as default.

  • Amity University, UP (PAN African eNetwork Project) 44

    Declaring Visual Basic Variables

    In most of the programming languages, variables must be declared in advance for

    the compiler. In Visual Basic the Variable declaration can be either Explicit or

    Implicit.

    Declaring a variable tells Visual Basic to reserve space in memory. It is not must

    that a variable should be declared before using it. Automatically whenever Visual

    Basic encounters a new variable, it assigns the default variable type and value.

    This is called implicit declaration. Though this type of declaration is easier for the

    user, to have more control over the variables, it is advisable to declare them

    explicitly. The variables are declared with a Dim statement to name the variable

    and its type. The As type clause in the Dim statement allows to define the data

    type or object type of the variable. This is called explicit declaration.

    The syntax for a simple declaration of a variable is as follows:

    Dim variableName As variableType

    In the above outline, Dim is the keyword which indicates to Visual Basic that a

    variable is being declared. variableName is the name assigned to the variable. Try

    to use a descriptive variable name and prefix the name with something which

    indicates the variable type. For example, when declaring a String variable prefix

    the name with str (e.g. strFirstName). The As keyword precedes the declaration of

    the variable type (String, Date, Integer etc).

    Syntax

    Dim variable [As Type]

    For example,

    Dim strName As String

    Dim intCounter As Integer

  • Amity University, UP (PAN African eNetwork Project) 45

    Using Option Explicit statement

    It may be convenient to declare variables implicitly, but it can lead to errors that

    may not be recognized at run time. Say, for example a variable by name intcount

    is used implicitly and is assigned to a value. In the next step, this field is

    incremented by 1 by the following statement

    Intcount = intcont + 1

    This calculation will result in intcount yielding a value of 1 as intcount would

    have been initialized to zero. This is because the intcount variable has been

    mityped as incont in the right hand side of the second variable. But Visual Basic

    does not see this as a mistake and considers it to be new variable and therefore

    gives a wrong result.

    In Visual Basic, to prevent errors of this nature, we can declare a variable by

    adding the following statement to the general declaration section of the Form.

    Option Explicit

    This forces the user to declare all the variables. The Option Explicit statement

    checks in the module for usage of any undeclared variables and reports an error to

    the user. The user can thus rectify the error on seeing this error message.

    The Option Explicit statement can be explicitly placed in the general declaration

    section of each module using the following steps.

    Click Options item in the Tools menu

    Click the Editor tab in the Options dialog box

    Check Require Variable Declaration option and then click the OK button

    To declare an Integer value named intInterestRate:

    Dim intInterestRate As Integer

  • Amity University, UP (PAN African eNetwork Project) 46

    It is also possible to declare multiple variables on the same line by separating each

    variable with a comma. When the variables are of the same type, the type

    declaration only needs to be made once at the end of the declaration:

    Dim intInterestRate, intExchangeRate As Integer

    In the case where the variables are of different types the type of variable must be

    declared at the end of each group of the same type. For example:

    Dim strCustomerName As String, intInterestRate, intExchangeRate As Integer

    Initializing Visual Basic Variables

    Visual Basic variables may be initialized either during the declaration, or after the

    declaration. Unless there is a good reason to do otherwise, it is recommended that

    variables be initialized during the declaration.

    Initialization is performed using the Visual Basic assignment operator (=). To

    initialize a single variable when it is declared:

    Dim intInterestRate As Integer = 5

    When declaring multiple variables each variable may be initialized in the

    declaration line:

    Dim strCustomerName As String = "Fred", intInterestRate = 5 As Integer,

    intExchangeRate As Integer = 10

    Assigning New Values to Visual Basic Variables

    Once a variable has been declared, a new value can be assigned to the variable at

    any time using the variable name and the assignment (=) operator. In the

    following sample Visual Basic code, a variable is declared and initialized to 10. It

    is then re-assigned the value of 20:

  • Amity University, UP (PAN African eNetwork Project) 47

    Dim intInterestRate As Integer = 10

    intInterestRate = 20

    Referencing Variable Values

    Accessing the value of a variable in Visual Basic code is as simple as typing the

    variable name. For example, the following code example adds 20 to the value of

    intInterestRate and assigns the result to the intNewRate variable:

    Dim intInterestRate As Integer = 10

    Dim intNewRate As Integer = 0

    intNewRate = intInterestRate + 20

    Understanding Variable and Constant Scope

    Variables and constants can be declared anywhere in a Visual Basic project. It is

    important to understand, therefore, that where and how the variable is declared

    dictates the scope of that variable. The scope of a variable relates to where else in

    the application source code the variable is accessible.

    There are four levels of scope of variables in VB

    Block Level Scope

    When a variable or constant is declared in a distinct code structure (such as an If

    statement or Do loop), the variable is only visible and accessible to the code

    within that structure.

  • Amity University, UP (PAN African eNetwork Project) 48

    Procedure Level Scope

    Variables and constants declared within a Visual Basic procedure (i.e. a Function

    or Subroutine) are only visible and accessible to code within that procedure For

    example, the variable intResult in the following code is only visible to code within

    the function:

    Module Level Scope

    When a variable or constant is declared outside of any procedures or code

    structures in a Module it is deemed to have module level scope. This means that

    the variable or constant is visible to all Visual Basic code contained in the same

    module, regardless of whether that code is located in a procedure or not. There is

    a section at the top of each module called the Declarations Section for this

    purpose. The Declaration section is located above all procedures and code in a

    module.

    Global Scope

    When a variable or constant is declared as global it is visible to all procedures and

    modules that comprise the application. Global variables and constants, as with

    Module level variables, must be declared outside of any procedures in the

    Declarations section and must use the Public keyword. The syntax for declaring a

    global variable is as follows:

    When a variable is declared with Procedure level scope it only exists while the

    code in the corresponding procedure is executing. Once the procedure completes,

    the variable and the variable assigned to it are destroyed. Under certain

    circumstance it may be necessary for the variable and the current value assign to it

    to persist beyond the life of the procedure. Next time the procedure is called,

    therefore, the variable still holds the value it held on the previous invocation of

    the procedure.

  • Amity University, UP (PAN African eNetwork Project) 49

    Declaring and Referencing Visual Basic Constants Constants, once declared

    and initialized cannot be changed (hence the name constant' and are declared

    using the Visual Basic Const keyword. The syntax for declaring variables is as

    follows:

    Const constName As datatype = value

    A Visual Basic constant is referenced using the name defined when the constant

    was declared.

    Const companyName As String = "Amity"

    companyLabel.Text = companyName

    Operators

    Arithmetical Operators

    Operators Description Example Result

    + Add 5+5 10

    - Substract 10-5 5

    / Divide 25/5 5

    \ Integer Division 20\3 6

    * Multiply 5*4 20

    ^ Exponent (power

    of)

    3^3 27

    Mod Remainder of

    division

    20 Mod 6 2

    & String

    concatenation

    "Teena"&"

    "&"Bagga"

    "Teena Bagga"

    Relational Operators

  • Amity University, UP (PAN African eNetwork Project) 50

    Operators Description Example Result

    > Greater than 10>8 True

    < Less than 10= Greater than or

    equal to

    20>=10 True

  • Amity University, UP (PAN African eNetwork Project) 51

    2.3 Arrays in Visual Basic

    An array is a consecutive group of memory locations that all have the same name

    and the same type. To refer to a particular location or element in the array, we

    specify the array name and the array element position number.

    The Individual elements of an array are identified using an index. Arrays have

    upper and lower bounds and the elements have to lie within those bounds. Each

    index number in an array is allocated individual memory space and therefore

    users must evade declaring arrays of larger size than required. We can declare an

    array of any of the basic data types including variant, user-defined types and

    object variables. The individual elements of an array are all of the same data type.

    In Visual Basic there are two types of arrays;

    fixed-size arrays that always remain the same size, and

    dynamic arrays whose size can change at run-time.

    You declare a visual basic array using the Dim statement. The following are

    examples of fixed arrays declared in Visual Basic:

    Dim MyIntArray(10) As Integer

    Dim MySingleArray(3 to 5) As Single

    The first example declares an array of (2-byte) integer values with 10 elements.

    The range of the array index can be 0 to 10 or 1 to 10, depending on the default

    value indicated with the Option Base statement. The second example declares an

    array of single values with 3 elements. The indexes for this second array go from

    3 to 5.

  • Amity University, UP (PAN African eNetwork Project) 52

    The dimensions of a fixed-size array cannot be changed; they remain the same

    throughout the scope of the array. Visual Basic also allows multidimensional

    arrays. For example the statement

    You declare a Visual Basic dynamic array by omitting its dimensions in the

    declaration statement:

    Dim MyDynArray() As Long

    You must then redimension the array with a ReDim statement before you use it.

    For example:

    ReDim MyDynArray(10)

    This will allocate 10 entries for array MyDynArray. You can redimension an array

    multiple times, so the following section of code is valid:

    Dim B() as long

    ReDim B(4)

    Do something with array B

    ReDim B(10)

    Do something else with array B

    Each time you execute the ReDim statement, all the values currently stored in the

    array are lost. Visual Basic resets the values to the Empty value (for Variant

    arrays), to zero (for numeric arrays), to a zero-length string (for string arrays), or

    to Nothing (for arrays of objects).

    This is useful when you want to prepare the array for new data, or when you want

    to shrink the size of the array to take up minimal memory. Sometimes you may

    want to change the size of the array without losing the data in the array. You can

  • Amity University, UP (PAN African eNetwork Project) 53

    do this by using ReDim with the Preserve keyword. For example, you can enlarge

    an array by one element without losing the values of the existing elements using

    the UBound function to refer to the upper bound:

    ReDim Preserve MyDynArray(UBound(MyDynArray) + 1)

    Only the upper bound of the last dimension in a multidimensional array can be

    changed when you use the Preserve keyword; if you change any of the other

    dimensions, or the lower bound of the last dimension, a run-time error occurs.

    Thus, you can use code like this:

    ReDim Preserve Matrix(10, UBound(Matrix, 2) + 1)

    But you cannot use this code:

    ReDim Preserve Matrix(UBound(Matrix, 1) + 1, 10)

    In Visual Basic, you can declare arrays of any standard types, including strings,

    variants, objects and User Defined Types (UDT). Arrays created in Visual Basic

    are always Safe Arrays.

  • Amity University, UP (PAN African eNetwork Project) 54

    2.4 Procedures in Visual Basic

    Visual Basic offers different types of procedures to execute small sections of

    coding in applications. The various procedures are elucidated in details in this

    section. Visual Basic programs can be broken into smaller logical components

    called Procedures. Procedures are useful for condensing repeated operations such

    as the frequently used calculations, text and control manipulation etc. The benefits

    of using procedures in programming are:

    It is easier to debug a program a program with procedures, which breaks a

    program into discrete logical limits.

    Procedures used in one program can act as building blocks for other programs

    with slight modifications.

    A Procedure can be Sub, Function or Property Procedure.

    Sub Procedures

    A sub procedure can be placed in standard, class and form modules. Each time the

    procedure is called, the statements between Sub and End Sub are executed. The

    syntax for a sub procedure is as follows:

    [Private | Public] [Static] Sub Procedurename [( arglist)] [ statements] End Sub

    arglist is a list of argument names separated by commas. Each argument acts like

    a variable in the procedure. There are two types of Sub Procedures namely

    general procedures and event procedures.

  • Amity University, UP (PAN African eNetwork Project) 55

    Event Procedures

    An event procedure is a procedure block that contains the control's actual name,

    an underscore(_), and the event name. The following syntax represents the event

    procedure for a Form_Load event.

    Private Sub Form_Load()

    ....statement block..

    End Sub

    Event Procedures acquire the declarations as Private by default.

    General Procedures

    A general procedure is declared when several event procedures perform the same

    actions. It is a good programming practice to write common statements in a

    separate procedure (general procedure) and then call them in the event procedure.

    In order to add General procedure:

    The Code window is opened for the module to which the procedure is to

    be added.

    The Add Procedure option is chosen from the Tools menu, which opens

    an Add Procedure dialog box as shown in the figure given below.

    The name of the procedure is typed in the Name textbox

    Under Type, Sub is selected to create a Sub procedure, Function to create a

    Function procedure or Property to create a Property procedure.

    Under Scope, Public is selected to create a procedure that can be invoked

    outside the module, or Private to create a procedure that can be invoked only from

    within the module.

  • Amity University, UP (PAN African eNetwork Project) 56

    We can also create a new procedure in the current module by typing Sub

    ProcedureName, Function ProcedureName, or Property ProcedureName in the

    Code window. A Function procedure returns a value and a Sub Procedure does

    not return a value.

    Function Procedures

    Functions are like sub procedures, except they return a value to the calling

    procedure. They are especially useful for taking one or more pieces of data, called

    arguments and performing some tasks with them. Then the functions returns a

    value that indicates the results of the tasks complete within the function.

    The following function procedure calculates the third side or hypotenuse of a right

    triangle, where A and B are the other two sides. It takes two arguments A and B

    (of data type Double) and finally returns the results.

    Function Hypotenuse (A As Double, B As Double) As Double Hypotenuse = sqr (A^2 + B^2) End Function

    The above function procedure is written in the general declarations section of the

    Code window. A function can also be written by selecting the Add Procedure

    dialog box from the Tools menu and by choosing the required scope and type.

  • Amity University, UP (PAN African eNetwork Project) 57

    Property Procedures

    A property procedure is used to create and manipulate custom properties. It is

    used to create read only properties for Forms, Standard modules and Class

    modules. Visual Basic provides three kind of property procedures-Property Let

    procedure that sets the value of a property, Property Get procedure that returns the

    value of a property, and Property Set procedure that sets the references to an

    object.

  • Amity University, UP (PAN African eNetwork Project) 58

    2.5 Control Statements in Visual Basic

    Control Statements are used to control the flow of program's execution. Visual

    Basic supports control structures such as if... Then, if...Then ...Else, Select...Case,

    and Loop structures such as Do While...Loop, While...Wend, For...Next etc

    method.

    If...Then selection structure

    The If...Then selection structure performs an indicated action only when the

    condition is True; otherwise the action is skipped.

    Syntax of the If...Then selection

    If Then

    statement

    End If

    e.g.: If average>75 Then txtGrade.Text = "A" End If

    If...Then...Else selection structure

    The If...Then...Else selection structure allows the programmer to specify that a different action is to be performed when the condition is True than when the

    condition is False.

    Syntax of the If...Then...Else selection

    If Then

    statements

    Else

  • Amity University, UP (PAN African eNetwork Project) 59

    statements

    End If

    e.g.: If average>50 Then txtGrade.Text = "Pass" Else txtGrade.Text = "Fail" End If

    Nested If...Then...Else selection structure

    Nested If...Then...Else selection structures test for multiple cases by placing If...Then...Else selection structures inside If...Then...Else structures.

    Syntax of the Nested If...Then...Else selection structure

    You can use Nested If either of the methods as shown above

    Method 1

    If < condition 1 > Then

    statements

    ElseIf < condition 2 > Then

    statements

    ElseIf < condition 3 > Then

    statements

    Else

    Statements

    End If

    Method 2

  • Amity University, UP (PAN African eNetwork Project) 60

    If < condition 1 > Then

    statements

    Else

    If < condition 2 > Then

    statements

    Else

    If < condition 3 > Then

    statements

    Else

    Statements

    End If

    End If

    EndIf

    e.g.: Assume you have to find the grade using nested if and display in a text box

    If average > 75 Then txtGrade.Text = "A" ElseIf average > 65 Then txtGrade.Text = "B" ElseIf average > 55 Then txtGrade.text = "C" ElseIf average > 45 Then txtGrade.Text = "S" Else txtGrade.Text = "F" End If

    Select...Case selection structure

    Select...Case structure is an alternative to If...Then...ElseIf for selectively executing a single block of statements from among multiple block of

    statements. Select...case is more convenient to use than the

  • Amity University, UP (PAN African eNetwork Project) 61

    If...Else...End If. The following program block illustrate the working of Select...Case.

    Syntax of the Select...Case selection structure

    Select Case Index Case 0 Statements Case 1 Statements End Select

    e.g.: Assume you have to find the grade using select...case and display in the text

    box

    Dim average as Integer average = txtAverage.Text Select Case average Case 100 To 75 txtGrade.Text ="A" Case 74 To 65 txtGrade.Text ="B" Case 64 To 55 txtGrade.Text ="C" Case 54 To 45 txtGrade.Text ="S" Case 44 To 0 txtGrade.Text ="F" End Select

  • Amity University, UP (PAN African eNetwork Project) 62

  • Amity University, UP (PAN African eNetwork Project) 63

    2.6 Repetition Structure in Visual Basic

    A repetition structure allows the programmer to that an action is to be repeated

    until given condition is true.

    Do While... Loop Statement

    The Do While...Loop is used to execute statements until a certain condition is

    met. The following Do Loop counts from 1 to 100.

    Dim number As Integer number = 1 Do While number

  • Amity University, UP (PAN African eNetwork Project) 64

    While... Wend Statement

    A While...Wend statement behaves like the Do While...Loop statement. The

    following While...Wend counts from 1 to 100

    Dim number As Integer number = 1 While number

  • Amity University, UP (PAN African eNetwork Project) 65

    Do...Loop While Statement

    The Do...Loop While statement first executes the statements and then test the

    condition after each execution. The following program block illustrates the

    structure:

    Dim number As Long

    number = 0

    Do

    number = number + 1

    Loop While number < 20

    The programs executes the statements between Do and Loop While structure in

    any case. Then it determines whether the counter is less than 20. If so, the

    program again executes the statements between Do and Loop While else exits the

    Loop.

  • Amity University, UP (PAN African eNetwork Project) 66

    Do Until...Loop Statement

    Unlike the Do While...Loop and While...Wend repetition structures, the Do

    Until... Loop structure tests a condition for falsity. Statements in the body of a Do

    Until...Loop are executed repeatedly as long as the loop-continuation test

    evaluates to False.

    An example for Do Until...Loop statement. The coding is typed inside the click

    event of the command button

    Dim number As Long

    number=0

    Do Until number > 10

    number = number + 1

    Print number

    Loop

    Numbers between 1 to 10 will be displayed on the form as soon as you click on

    the command button.

  • Amity University, UP (PAN African eNetwork Project) 67

    The For...Next Loop

    The For...Next Loop is another way to make loops in Visual Basic. For...Next

    repetition structure handles all the details of counter-controlled repetition. The

    following loop counts the numbers from 1 to 100:

    Dim x As Integer

    For x = 1 To 50

    Print x

    Next

    In order to count the numbers from 1 too 50 in steps of 2, the following loop can

    be used

    For x = 1 To 50 Step 2

    Print x

    Next

  • Amity University, UP (PAN African eNetwork Project) 68

    The following loop counts numbers as 1, 3, 5, 7..etc

    The above coding will display numbers vertically on the form. In order to display

    numbers horizontally the following method can be used.

    For x = 1 To 50 Print x & Space$ (2); Next

    To increase the space between the numbers increase the value inside the brackets

    after the & Space$.

    Following example is a For...Next repetition structure which is with the If

    condition used.

    Dim number As Integer For number = 1 To 10 If number = 4 Then Print "This is number 4" Else Print number End If Next

    In the output instead of number 4 you will get the "This is number 4".

  • Amity University, UP (PAN African eNetwork Project) 69

    2.7 Exit For and Exit Do Statement in Visual Basic

    A For...Next loop condition can be terminated by an Exit For statement.

    Consider the following statement block.

    Dim x As Integer

    For x = 1 To 10

    Print x

    If x = 5 Then

    Print "The program exited at x=5"

    End If

    Next

    The preceding code increments the value of x by 1 until it reaches the condition x

    = 5. The Exit For statement is executed and it terminates the For...Next loop.

    The Following statement block containing Do...While loop is terminated using

    Exit Do statement.

    Dim x As Integer

    Do While x < 10

    Print x

    x = x + 1

    If x = 5 Then

    Print "The program is exited at x=5"

    Exit Do

    End If

    Loop

  • Amity University, UP (PAN African eNetwork Project) 70

    Quiz

    Q1. Code in Visual Basic is stored in the form of

    a. Files

    b. Programes

    c. Modules.

    d. Class

    Q2. Which of the following statement is fase

    1. A name must begin with a letter.

    2. May be as much as 255 characters long

    3. Must not contain a space or an embedded period or type-declaration

    characters used to specify a data type; these are ! # % $ & @

    4. Must be a reserved word, Keywords

    a. 1

    b. 2

    c. 3

    d. 4

    Q3. The variant data type can store

    a. numeric

    b. date/time

    c. string data.

    d. All the above

    Q4. ______________ forces the user to declare all the variables.

    a. Dim

    b. Default

  • Amity University, UP (PAN African eNetwork Project) 71

    c. Option Explicit

    d. None of the above

    Q5. When a variable or constant is declared in a distinct code structure (such as an If

    statement or Do loop), the variable is only visible and accessible to the code

    within that structure. Is

    a. Block Level Scope

    b. Loop Level Scope

    c. Procedure Level Scope

    d. Module Level Scope

    Q6. _________ must be declared outside of any procedures in the Declarations section

    and must use the Public keyword.

    a. Block Level Scope

    b. Loop Level Scope

    c. Procedure Level Scope

    d. Module Level Scope

    Q7. The ____________ returns a value that indicates the results of the tasks complete.

    a. Functions

    b. Variables

    c. Loops

    d. Procedures

    Q8. Visual Basic provides _________ kind(s) of property procedures

    a. Property Let procedure that sets the value of a property

    b. Property Get procedure that returns the value of a property

    c. Property Set procedure that sets the references to an object.

    d. All the above

  • Amity University, UP (PAN African eNetwork Project) 72

    Chapter-3

    VB Standard Controls

    OBJECTIVES

    After going through this lesson you will be in a position to understand:

    Various standard Controls : o Labels o Command buttons o Text buttons o Option buttons o Check boxes o Frame controls o List boxes o Combo boxes o Image objects o Picture boxes o Timer o Scroll bars o File system controls

  • Amity University, UP (PAN African eNetwork Project) 73

    3.1 Controls in Visual Basic

    Visual Basic controls are broadly classified as:

    standard controls,

    ActiveX controls and

    insertable objects.

    Standard controls such as CommandButton, Label and Frame controls are

    contained inside .EXE file and are always included in the ToolBox which cannot

    be removed. ActiveX controls exist as separate files with either .VBX or .OCX

    extension.

    Some of these objects support OLE Automation, which allow programming

    another application's object from within Visual Basic application.

    3.2 The Control Properties

    Before writing an event procedure for the control to response to a user's input, we

    have to set certain properties for the control to determine its appearance and how

    it will work with the event procedure. We can set the properties of the controls in

    the properties window or at runtime.

    It is very important to know, how and when to set the objects' properties as it can

    help we to write a good program or we may fail to write a good program.

  • Amity University, UP (PAN African eNetwork Project) 74

    Figure above is a typical properties window for a form. We can rename the form

    caption to any name that we like best. In the properties window, the item appears

    at the top part is the object currently selected (in the above Figure, the object

    selected is Form1). At the bottom part, the items listed in the left column

    represent the names of various properties associated with the selected object while

    the items listed in the right column represent the states of the properties.

  • Amity University, UP (PAN African eNetwork Project) 75

    Properties can be set by highlighting the items in the right column then change

    them by typing or selecting the options available.

    For example, in order to change the caption, just highlight Form1 under the name

    Caption and change it to other names. We may also try to alter the appearance of

    the form by setting it to 3D or flat. Other things we can do are to change its

    foreground and background color, change the font type and font size, enable or

    disable minimize and maximize buttons and etc.

    We can also change the properties at runtime to give special effects such

    as change of color, shape, animation effect and so on. For example the following

    code will change the form color to red every time the form is loaded. VB uses

    hexadecimal system to represent the color. We can check the color codes in the

    properties windows which are showed up under ForeColor and BackColor .

    Private Sub Form_Load()

    Form1.Show

    Form1.BackColor = &H000000FF&

    End Sub

    Another example is to change the control Shape to a particular shape at runtime

    by writing the following code. This code will change the shape to a circle at

    runtime. Later we will learn how to change the shapes randomly by using the

    RND function.

    Private Sub Form_Load()

    Shape1.Shape = 3

    End Sub

    We should know how and when to set the objects' properties is very important as

    it can help we to write a good program or we may fail to write a good program.

  • Amity University, UP (PAN African eNetwork Project) 76

    Here are some important points about setting up the properties

    We should set the Caption Property of a control clearly so that a user

    knows what to do with that command. For example, in the calculator

    program, all the captions of the command buttons such as +, - , MC, MR

    are commonly found in an ordinary calculator, a user should have no

    problem in manipulating the buttons.

    A lot of programmers like to use a meaningful name for the Name

    Property may be because it is easier for them to write and read the event

    procedure and easier to debug or modify the programs later. However, it is

    not a must to do that as long as we label objects clearly and use comments

    in the program whenever we feel necessary.

    One more important property is whether the control is enabled or not

    Finally, we must also considering making the control visible or invisible at

    runtime, or when should it become visible or invisible

    TabIndex property of Controls

    Visual Basic uses the TabIndex property to determine the control that

    would receive the focus next when a tab key is pressed. Every time a tab

    key is pressed, Visual Basic looks at the value of the TabIndex for the

    control that has focus and then it scans through the controls searching for

    the next highest TabIndex number. When there are no more controls with

    higher TabIndex value, Visual Basic starts all over again with 0 and looks

    for the first control with TabIndex of 0 or higher that can accept keyboard

    input.

    By default, Visual Basic assigns a tab order to control as we draw the

    controls on the Form, except for Menu, Timer, Data, Image, Line and

    Shape controls, which are not included in tab order. At run time, invisible

    or disabled controls also cannot receive the focus although a TabIndex

    value is given. Setting the TabIndex property of controls is compulsory in

    development environment.

  • Amity University, UP (PAN African eNetwork Project) 77

    3.3 The Label Control

    This is probably the first control we will master. It is used to display static text,

    titles and screen output from operations. The important properties to remember:

    Caption - the text that is displayed in the label

    BackColor and ForeColor - colors of the background and the text

    BackStyle - Opaque or Transparent - whether the background is visible or

    not

    Font - font and size of text

    Alignment - text centered, left or right

    Multiline- True or False - if True, we can have several lines of text,

    delimited by in the label - by default, it is set to False.

  • Amity University, UP (PAN African eNetwork Project) 78

    3.5 Frame

    Some times we want to group several controls together - name and address, for

    example - we use a Frame. Frame controls are similar to Label controls in that

    they can serve as captions for those controls that don't have their own. Moreover,

    Frame controls can also (and often do) behave as containers and host other

    controls. In most cases, we only need to drop a Frame control on a form and set

    its Caption property. If we want to create a borderless frame, we can set its

    BorderStyle property to 0-None.

    Controls that are contained in the Frame control are said to be child controls.

    Moving a control at design time over a Frame controlor over any other

    container, for that matterdoesn't automatically make that control a child of the

    Frame control. After we create a Frame control, we can create a child control by

    selecting the child control's icon in the Toolbox and drawing a new instance

    inside the Frame's border. Alternatively, to make an existing control a child of a

    Frame control, we must select the control, press Ctrl+X to cut it to the Clipboard,

    select the Frame control, and press Ctrl+V to paste the control inside the Frame. If

    we don't follow this procedure and we simply move the control over the Frame,

    the two controls remain completely independent of each other, even if the other

    control appears in front of the Frame control.

    Frame controls, like all container controls, have two interesting features. If we

    move a Frame control, all the child controls go with it. If we make a container

    control disabled or invisible, all its child controls also become disabled or

    invisible. We can exploit these features to quickly change the state of a group of

    related controls.

  • Amity University, UP (PAN African eNetwork Project) 79

    3.6 PictureBox

    PictureBox controls are among the most powerful and complex items in the

    Visual Basic Toolbox window. This control is more similar to forms than to other

    controls.

    The Picture Box is one of the controls that is used to handle graphics. We can

    load a picture at design phase by clicking on the picture item in the properties

    window and select the picture from the selected folder.

    Loading images

    Once we place a PictureBox on a form, we might want to load an image in it,

    which we do by setting the Picture property in the Properties window. We can

    load images in many different graphic formats, including bitmaps (BMP), device

    independent bitmaps (DIB), metafiles (WMF), enhanced metafiles (EMF), GIF

    and JPEG compressed files, and icons (ICO and CUR). We can decide whether a

    control should display a border, resetting the BorderStyle to 0-None if necessary.

    Another property that comes handy in this phase is AutoSize: Set it to True and

    let the control automatically resize itself to fit the assigned image.

    We might want to set the Align property of a PictureBox control to something

    other than the 0-None value. By doing that, we attach the control to one of the

    four form borders and have Visual Basic automatically move and resize the

    PictureBox control when the form is resized. PictureBox controls expose a Resize

    event, so we can trap it if we need to move and resize its child controls too.

    We can do more interesting things at run time. To begin with, we can

    programmatically load any image in the control using the LoadPicture function:

    Picture1.Picture = LoadPicture("c:\windows\amity.bmp")

  • Amity University, UP (PAN African eNetwork Project) 80

    and we can clear the current image using either one of the following statements:

    ' These are equivalent.

    Picture1.Picture = LoadPicture("")

    Set Picture1.Picture = Nothing

    We can copy an image from one PictureBox control to another by assigning the

    target control's Picture property:

    Picture2.Picture = Picture1.Picture

  • Amity University, UP (PAN African eNetwork Project) 81

    3.7 Image Control

    Image controls are far less complex than PictureBox controls. They can't work as

    containers, just to hint at their biggest limitations. Nevertheless, we should always

    strive to use Image controls instead of PictureBox controls because they load

    faster and consume less memory and system resources. Remember that Image

    controls are windowless objects that are actually managed by Visual Basic

    without creating a Windows object. Image controls can load bitmaps and JPEG

    and GIF images.

    When we're working with an Image control, we typically load a bitmap into its

    Picture property either at design time or at run time using the LoadPicture

    function. Image controls don't expose the AutoSize property because by default

    they resize to display the contained image (as it happens with PictureBox controls

    set at AutoSize = True). On the other hand, Image controls support a Stretch

    property that, if True, resizes the image (distorting it if necessary) to fit the

    control. In a sense, the Stretch property somewhat remedies the lack of the

    PaintPicture method for this control. In fact, we can zoom in to or reduce an

    image by loading it in an Image control and then setting its Stretch property to

    True to change its width and height:

    ' Load a bitmap.

    Image1.Stretch = False

    Image1.Picture = LoadPicture("c:\windows\amity.bmp")

    ' Reduce it by a factor of two.

    Image1.Stretch = True

    Image1.Move 0, 0, Image1.Width / 2, Image1.Width / 2

    Image controls support all the usual mouse events. For this reason, many Visual

    Basic developers have used Image controls to simulate graphical buttons and

    toolbars.

  • Amity University, UP (PAN African eNetwork Project) 82

    3.8 TextBox

    The text box is the standard control for accepting input from the user as well as to

    display the output. It can handle string (text) and numeric data but not images or

    pictures. TextBox controls offer a natural way for users to enter a value in wer

    program. For this reason, they tend to be the most frequently used controls in the

    majority of Windows applications. TextBox controls, which have a great many

    properties and events, are also among the most complex intrinsic controls. We

    will discuss the most useful properties of TextBox controls.

    When the program Run, only the controls that can be manipulated will be

    activated. For example, if the form contains 3 Labels, 3 TextBoxes and 3 Buttons,

    when it is Run, the cursor will not stop at the labels.

    When the user hits the Tab key, the cursor will go to the first TextBox or Button -

    not necessarily the first one on the form but, the first one that was created. That is

    called the Tab order and we have to specify it.

    On the form there is only one control at any given time that has the cursor on it -

    it is said to have Focus. If we type data, the control with Focus will receive it. We

    change the Focus with Tab or by clicking on a different control.

    Setting properties to a TextBox

    Text can be entered into the text box by assigning the necessary string to

    the text property of the control

    If the user needs to display multiple lines of text in a TextBox, set the

    MultiLine property to True

    To customize the scroll bar combination on a TextBox, set the ScrollBars

    property.

  • Amity University, UP (PAN African eNetwork Project) 83

    Scroll bars will always appear on the TextBox when it's MultiLine

    property is set to True and its ScrollBars property is set to anything except

    None(0)

    We can create multiline TextBox controls by setting the MultiLine

    property to True and the ScrollBars property to 2-Vertical or 3-Both. A

    vertical scroll bar causes the contents of the control to automatically wrap

    when a line is too long for the control's width, so this setting is most useful

    when we're creating memo fields or simple word processor-like

    programs. If we have both a vertical and a horizontal scroll bar, the

    TextBox control behaves more like a programmer's editor, and longer

    lines simply extend beyond the right border. I've never found a decent

    use for the other settings of the ScrollBars property (0-None and 1-

    Horizontal) in a multiline TextBox control. Visual Basic ignores the

    ScrollBars property if MultiLine is False.

    Run-Time Properties of a TextBox control

    The Text property is the one we'll reference most often in code, and conveniently

    it's the default property for the TextBox control. Three other frequently used

    properties are these:

    The SelStart property sets or returns the position of the blinking caret

    (the insertion point where the text we type appears). Note that the

    blinking cursor inside TextBox and other controls is named caret, to

    distinguish it from the cursor (which is implicitly the mouse cursor). When

    the caret is at the beginning of the contents of the TextBox control,

    SelStart returns 0; when it's at the end of the string typed by the user,

    SelStart returns the value Len(Text). We can modify the SelStart property

    to programmatically move the caret.

    The SelLength property returns the number of characters in the portion

    of text that has been highlighted by the user, or it returns 0 if there's no

  • Amity University, UP (PAN African eNetwork Project) 84

    highlighted text. We can assign a nonzero value to this property to

    programmatically select text from code. Interestingly, we can assign to

    this property a value larger than the current text's length without raising a

    run-time error.

    The SelText property sets or returns the portion of the text that's

    currently selected, or it returns an empty string if no text is highlighted.

    Use it to directly retrieve the highlighted text without having to query

    Text, SelStart, and SelLength properties. What's even more interesting is

    that we can assign a new value to this property, thus replacing the current