paper – iii visual basicnews.algacis.com/citm_uploads/visual basic.pdf · paper – iii visual...

33
PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB – Integrated development environment Basic script. The integrated Development Environment: Introduction, Overview, Project Window, Toolbox, Form Layout Window Properties Window, Menu Bar and Tool Bar. Control structure: Part I Introduction, If/Then/Else, While, Do while Do until. UNIT – II Control structure: Part II Introduction, For/Next, select case, Do/Loop While, Do/Loop Until, Exit Do, Exit for Boolean Data type, Constant variables, Logical Operators, visuals Basic Data Type. Sub Procedures and function procedures introduction, Form Modules, Sub procedures, Functions procedures cell By value Vs call by reference, Exit sub and Exit function, Storages classes scope rules recursion optional Arguments, Named Arguments, Visual Basic Math Functions, Code Modules. UNIT – III Arrays: Introduction, Arrays, Declaring Arrays, Passing Arrays to procedures, Sorting Arrays, Searching Arrays, Multidimensional Arrays, Control Arrays, Dynamic Arrays, Paramarray, Functions Array. UNIT – IV Basic Graphical User Interface Concepts: Controls, Text Box, Mash Edit, Combo Box, List Box, Scroll Bars, Slider, Menus, Pop-up Menus, Function Msgbox, Advanced Graphical user Interface Concepts; MDI, Multiple Forms, Template Forms, Rich Textbox, Up Down, Image List, Image Combo. UNIT V – Mouse and keyboard: Changing the shape of the Mouse Pointer, Mouse Events, Mouse Buttons, Shift-Ctrl-Alt Keys, Drag and Drop, Key Events, Key Preview property. Database Management: ADO Data Control, DAO Data Control, RDO Data Control, Accessing the Data Base using ADO, DAO.

Upload: others

Post on 30-Apr-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

PAPER – III VISUAL BASIC

UNIT – I A first glance to VB: Introduction – Features of VB – Integrated development environment – Basic script. The integrated Development Environment: Introduction, Overview, Project Window, Toolbox, Form Layout Window Properties Window, Menu Bar and Tool Bar. Control structure: Part I Introduction, If/Then/Else, While, Do while Do until.

UNIT – II Control structure: Part II Introduction, For/Next, select case, Do/Loop While, Do/Loop Until, Exit Do, Exit for Boolean Data type, Constant variables, Logical Operators, visuals Basic Data Type. Sub Procedures and function procedures introduction, Form Modules, Sub procedures, Functions procedures cell By value Vs call by reference, Exit sub and Exit function, Storages classes scope rules recursion optional Arguments, Named Arguments, Visual Basic Math Functions, Code Modules.

UNIT – III Arrays: Introduction, Arrays, Declaring Arrays, Passing Arrays to procedures, Sorting Arrays, Searching Arrays, Multidimensional Arrays, Control Arrays, Dynamic Arrays, Paramarray, Functions Array.

UNIT – IV Basic Graphical User Interface Concepts: Controls, Text Box, Mash Edit, Combo Box, List Box, Scroll Bars, Slider, Menus, Pop-up Menus, Function Msgbox, Advanced Graphical user Interface Concepts; MDI, Multiple Forms, Template Forms, Rich Textbox, Up Down, Image List, Image Combo.

UNIT V – Mouse and keyboard: Changing the shape of the Mouse Pointer, Mouse Events, Mouse Buttons, Shift-Ctrl-Alt Keys, Drag and Drop, Key Events, Key Preview property. Database Management: ADO Data Control, DAO Data Control, RDO Data Control, Accessing the Data Base using ADO, DAO.

Page 2: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

UNIT I

Introduction to Visual Basic VISUAL BASIC is a high level programming language that evolved from the earlier DOS version called BASIC. BASIC means Beginners' All-purpose Symbolic Instruction Code. The code looks a lot like English Language. Now, there are many versions of Visual Basic available in the market, the latest being Visual Basic 2015 that is bundled with other programming languages such as C#. However, the most popular one and still widely used by many VB programmers is none other than Visual Basic 6. .

VISUAL BASIC is a VISUAL Programming Language because programming is done in a graphical environment. In VB6, you just need to drag and drop any graphical object anywhere on the form and click on the object to enter the code window and start programming.

What programs can you create with Visual Basic 6?

In VB 6, you can create any program depending on your objective. For math teachers, you can create mathematical programs such as Geometric Progression, Quadratic Equation Solver, Simultaneous Equation Solver ,Prime Number, Factors Finder, Quadratic Function Graph Plotter and so on. For science teachers, you can create simulation programs such as Projectile, Simple Harmonic Motion, and Star War etc. If you are in business, you can also create business applications such as inventory management system , Amortization Calculator , investments calculator, point-of-sale system, payroll system, accounting program and more to help manage your business and increase productivity. For those of you who like games, you can create programs such as slot machine, reverse, tic tac toe and more. Besides, you can create multimedia programs such as Smart Audio Player, Multimedia Player and more. Indeed, there is no limit to what program you can create! We offer many sample codes in our tutorial.

1. Introduction to the Visual Basic Language and Environment Preview

Page 3: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

In this first class, we will do a quick overview of how to build an application in Visual Basic. You’ll learn a new vocabulary, a new approach to programming, and ways to move around in the Visual Basic environment. You will leave having written your first Visual Basic program. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool understand the Visual Basic event-driven programming concepts, terminology, and available tools learn the fundamentals of designing, implementing, and distributing a Visual Basic application Learn to use the Visual Basic toolbox Learn to modify object properties Learn object methods Use the menu design window Understand proper debugging and error-handling procedures Gain a basic understanding of database access and management using data bound controls Obtain an introduction to ActiveX controls and the Windows Application Programming Interface (API) What is Visual Basic? Visual Basic is a tool that allows you to develop Windows (Graphic User Interface - GUI) applications. The applications have a familiar appearance to the user. Visual Basic is event-driven, meaning code remains idle until called upon to respond to some event (button pressing, menu selection,). Visual Basic is governed by an event processor. Nothing happens until an event is detected. Once an event is detected, the code corresponding to that event (event procedure) is executed. Program control is then returned to the event processor.

Page 4: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

Some Features of Visual Basic Full set of objects - you 'draw' the application Lots of icons and pictures for your use Response to mouse and keyboard actions Clipboard and printer access Full array of mathematical, string handling and graphics functions Can handle fixed and dynamic variable and control arrays Sequential and random access files support Useful debugger and error-handling facilities Powerful database access tools ActiveX support Package & Deployment Wizard makes distributing your applications simple · The original Visual Basic for DOS and Visual Basic For Windows were introduced in 1991. · Visual Basic 3.0 (a vast improvement over previous versions) was released in 1993. · Visual Basic 4.0 released in late 1995 (added 32 bit application support). · Visual Basic 5.0 released in late 1996. New environment, supported creation of ActiveX controls, deleted 16 bit application support. · And, now Visual Basic 6.0 - some identified new features of Visual Basic 6.0: Faster compiler New ActiveX data control object Allows database integration with wide variety of applications New data report designer New Package & Deployment Wizard Additional internet capabilities

Page 5: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

Structure of a Visual Basic Application

Application (Project) is made up of: Forms - Windows that you create for user interface Controls - Graphical features drawn on forms to allow user interaction (text boxes, labels, scroll bars, command buttons, etc.) (Forms and Controls are objects.) Properties - Every characteristic of a form or control is specified by a property. Example properties include names, captions, size, color, position, and contents. Visual Basic applies default properties. You can change properties at design time or run time. Methods - Built-in procedure that can be invoked to impart some action to a particular object. Event Procedures - Code related to some object. This is the code that is executed when a certain event occurs. General Procedures - Code not related to objects. This code must be invoked by the application. Modules - Collection of general procedures, variable declarations, and constant definitions used by application.

Page 6: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

Steps in Developing Application There are three primary steps involved in building a Visual Basic application: 1. Draw the user interface 2. Assign properties to controls 3. Attach code to controls Drawing the User Interface and Setting Properties · Visual Basic operates in three modes. Design mode - used to build application Run mode - used to run the application Break mode - application halted and debugger is available We focus here on the design mode. · Six windows appear when you start Visual Basic. The Main Window consists of the title bar, menu bar, and toolbar. The title bar indicates the project name, the current Visual Basic operating mode, and the current form. The menu bar has drop-down menus from which you control the operation of the Visual Basic environment. The toolbar has buttons that provide shortcuts to some of the menu options. The main window also shows the location of the current form relative to the upper left corner of the screen (measured in twips) and the width and length of the current form.

Page 7: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

The Form Window is central to developing Visual Basic applications. It is where you draw your application.

The Toolbox is the selection menu for controls used in your application.

The Properties Window is used to establish initial property values for objects. The drop-down box at the top of the window lists all objects in the current form. Two views are available: Alphabetic and Categorized. Under this box are the available properties for the currently selected object.

Page 8: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

The Form Layout Window shows where (upon program execution) Your form will be displayed relative to your monitor’s screen:

The Project Window displays a list of all forms and modules making up your application. You can also obtain a view of the Form or Code windows (window containing the actual basic coding) from the Project window.

Page 9: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

· As mentioned, the user interface is ‘drawn’ in the form window. There are two ways to place controls on a form: 1. Double-click the tool in the toolbox and it is created with a default size on the form. You can then move it or resize it. 2. Click the tool in the toolbox, then move the mouse pointer to the form window. The cursor changes to a crosshair. Place the crosshair at the upper left corner of where you want the control to be, press the left mouse button and hold it down while dragging the cursor toward the lower right corner. When you release the mouse button, the control is drawn. · To move a control you have drawn, click the object in the form window and drag it to the new location. Release the mouse button. · To resize a control, click the object so that it is select and sizing handles appear. Use these handles to resize the object.

Page 10: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

Stopwatch Application - Drawing Controls 1. Start a new project. The idea of this project is to start a timer, then stop the timer and compute the elapsed time (in seconds). 2. Place three command buttons and six labels on the form. Move and size the controls and form so it looks something like this:

Setting Properties of Objects at Design Time · Each form and control has properties assigned to it by default when you start up a new project. There are two ways to display the properties of an object. The first way is to click on the object (form or control) in the form window. Then, click on the Properties Window or the Properties Window button in the tool bar. The second way is to first click on the Properties Window. Then, select the object from the Object box in the Properties Window. Shown is the Properties Window for the stopwatch application:

Page 11: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

The drop-down box at the top of the Properties Window is the Object box. It displays the name of each object in the application as well as its type. This display shows the Form object. The Properties list is directly below this box. In this list, you can scroll through the list of properties for the selected object. You may select a property by clicking on it. Properties can be changed by typing a new value or choosing from a list of predefined settings (available as a drop down list). Properties can be viewed in two ways: Alphabetic and Categorized.

Page 12: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

UNIT II

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 <= 100 number = number + 1 Loop

A variable number is initialized to 1 and then the Do While Loop starts. First, the condition is tested; if condition is True, then the statements are executed. When it gets to the Loop it goes back to the Do and tests condition again. If condition is False on the first pass, the statements are never executed.

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 < 201

The programs executes the statements between Do and Loop While structure in any case. Then it determines whether the counter is less than 501. If so, the program again executes the statements between Do and Loop While else exits the Loop.

Page 13: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

Data Types

There are many types of data that we come across in our daily life. For example, we need to handle data such as names, addresses, money, date, stock quotes, statistics and more every day. Similarly in Visual Basic, we have to deal with all sorts of of data, some can be mathematically calculated while some are in the form of text or other forms. VB divides data into different types so that they are easier to manage when we need to write the code involving those data.

Visual Basic classifies the information mentioned above into two major data types, they are the numeric data types and the non-numeric data types.

Logical Operators

In addition to conditional operators, there are a few logical operators that offer added power to the VB programs. They are shown in Table 7.2.

Operator Meaning

And Both sides must be true

or One side or other must be true

Xor One side or other must be true but not both

Not Negates truth

Using If.....Then.....Else Statements with Operators

To effectively control the VB program flow, we shall use If...Then...Else statement together with the conditional operators and logical operators.

If conditions Then

Page 14: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

VB expressions

Else

VB expressions

End If

Do Loop

The Do Loop statements have three different forms, as shown below:

a) Do While condition

Block of one or more VB statements

Loop

Loop Until condition

Exiting the Loop

Sometime we need exit to exit a loop earlier when a certain condition is fulfilled. The keyword to use is Exit Do.

For....Next Loop

The for....Next Loop event procedure is written as follows:

For counter=start Number to end Number (Step increment)

One or more VB statements

Next

Page 15: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

The While….Wend Loop

The structure of a While….Wend Loop is very similar to the Do Loop. it takes the following form:

While condition

Statements

Wend

The above loop means that while the condition is not met, the loop will go on. The loop will end when the condition is met.

Visual Basic Data Types

There are many types of data that we come across in our daily life. For example, we need to handle data such as names, addresses, money, date, stock quotes, statistics and more every day. Similarly in Visual Basic, we have to deal with all sorts of data, some can be mathematically calculated while some are in the form of text or other forms. VB divides data into different types so that they are easier to manage when we need to write the code involving those data.

Visual Basic classifies the information mentioned above into two major data types, they are the numeric data types and the non-numeric data types.

Numeric Data Types

Numeric data types are types of data that consist of numbers that can be computed mathematically with standard operators. Examples of numeric data types are height, weight, share values, price of goods, monthly bills, fees and others. In Visual Basic, numeric data are divided into 7 types, depending on the range of values they can store. Calculations that only involve round figures can use Integer or Long integer in the computation. Programs that require high precision calculation need to use Single and Double decision data types, they are also called floating point numbers. For currency calculation, you can use the currency data

Page 16: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

types. Lastly, if even more precision is required to perform calculations that involve a many decimal points, we can use the decimal data types

Non-numeric Data Types

Nonnumeric data types are data that cannot be manipulated mathematically. Non-numeric data comprises string data types, date data types, Boolean data types that store only two values (true or false), object data type and Variant data type

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 is 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 > 1000 number = number + 1 Print number Loop

Numbers between 1 to 1000 will be displayed on the form as soon as you click on the command button.

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 Procedure name [( arglist)] [ statements] End Sub

Page 17: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

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.

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

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

Page 18: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

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.

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.

Variables

Variables are the memory locations which are used to store values temporarily. A defined naming strategy has to be followed while naming a variable. A variable name must begin with an alphabet letter and should not exceed 255 characters. It must be unique within the same scope. It should not contain any special character like %, &, !, #, @ or $.

There are many ways of declaring variables in Visual Basic. Depending on where the variables are declared and how they are declared, we can determine how they can be used by our application. The different ways of declaring variables in Visual Basic are listed below and elucidated in this section.

Scope of variables

A variable is scoped to a procedure-level (local) or module-level variable depending on how it is declared. The scope of a variable, procedure or object determines which part of the code in our application is aware of the variable's existence. A variable is declared in general declaration section of e Form, and hence is available to all the procedures. Local variables are recognized only in the procedure in which they are declared. They can be declared with Dim and Static keywords. If we want a variable to be available to all of the procedures within the same module, or to all the procedures in an application, a variable is declared with broader scope.

Static Variables

Page 19: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

A static variable are not reinitialized each time Visual Invokes a procedure and therefore retains or preserves value even when a procedure ends. In case we need to keep track of the number of times a command button in an application is clicked, a static counter variable has to be declared. These static variables are also ideal for making controls alternately visible or invisible. A static variable is declared as given below.

Module Level Variables

A module level variable is available to all the procedures in the module. They are declared using the Public or the Private keyword. If you declare a variable using a Private or a Dim statement in the declaration section of a module—a standard BAS module, a form module, a class module, and so on—you're creating a private module-level variable. Such variables are visible only from within the module they belong to and can't be accessed from the outside. In general, these variables are useful for sharing data among procedures in the same module:

‘In the declarative section of any module Private Login Time as Date ' A private module-level variable Dim Login Password as String ' Another private module-level variable

You can also use the Public attribute for module-level variables, for all module types except BAS modules. (Public variables in BAS modules are global variables.) In this case, you're creating a strange beast: a Public module-level variable that can be accessed by all procedures in the module to share data and that also can be accessed from outside the module. In this case, however, it's more appropriate to describe such a variable as a property:

Operators in Visual Basic

Arithmetical Operators

Operators Description Example Result

+ Add 5+5 10

- Substract 10-5 5

Page 20: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

/ 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

"George"&" "&"Bush" "George Bush"

Relational Operators

Operators Description Example Result

> Greater than 10>8 True

< Less than 10<8 False

>= Greater than or equal to

20>=10 True

<= Less than or equal to

10<=20 True

<> Not Equal to 5<>4 True

Page 21: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

= Equal to 5=7 False

Logical Operators

Operators Description

OR Operation will be true if either of the operands is true

AND Operation will be true only if both the operands are true

Creating a Code Module ·

If you're going to put code in a module, you'll need to know how to create and save a module. A good way to think about modules is to consider them forms without any objects, just code. ·

To create a module, click on the New Module button on the toolbar, or select the Module option from the Insert menu. The module will appear. Note any modules appear in the Project Window, along with your form(s). You use the Project Window to move among forms and modules.

· Once the module is active, establish all of your procedures as outlined above. To name the module, click on the properties window while the module is active. Note Name is the only property associated with a module. Saving a module is just like saving a form - use the Save File and Save File As options.

Page 22: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

UNIT III

Arrays By definition, an array is a list of variables with the same data type and name. When we work with a single item, we only need to use one variable. However, if we have a list of items which are of similar type to deal with, we need to declare an array of variables instead of using a variable for each item

For example, if we need to enter one hundred names, it is difficulty to declare 100 different names; this is a waste of time and efforts. So, instead of declaring one hundred different variables, we need to declare only one array. We differentiate each item in the array by using subscript, the index value of each item, for example name (1), name (2), name (3) .......etc., make declaring variables more streamline.

Dimension of an Array

An array can be one dimensional or multidimensional. One dimensional array is like a list of items or a table that consists of one row of items or one column of items.

A two dimensional array is a table of items that make up of rows and columns. The format for a one dimensional array is Array Name(x), the format for a two dimensional array is Array Name(x, y) and a three dimensional array is Array Name(x, y,z) . Normally it is sufficient to use one dimensional and two dimensional arrays, you only need to use higher dimensional arrays if you need to deal with more complex problems. Let me illustrate the arrays with tables.

Declaring Arrays

We can use Public or Dim statement to declare an array just as the way we declare a single variable. The Public statement declares an array that can be used throughout an application while the Dim statement declares an array that could be used only in a local procedure.

The general format to declare a one dimensional array is as follow:

Page 23: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

Dim array Name (subs) as data Type

Where subs indicates the last subscript in the array.

Multidimensional Arrays

Arrays can have multiple dimensions. A common use of multidimensional arrays is to represent tables of values consisting of information arranged in rows and columns. To identify a particular table element, we must specify two indexes: The first (by convention) identifies the element's row and the second (by convention) identifies the element's column.

Tables or arrays that require two indexes to identify a particular element are called two dimensional arrays. Note that multidimensional arrays can have more than two dimensions. Visual Basic supports at least 60 array dimensions, but most people will need to use more than two or three dimensional-arrays.

The following statement declares a two-dimensional array 50 by 50 array within a procedure.

Static and dynamic arrays

Basically, you can create either static or dynamic arrays. Static arrays must include a fixed number of items, and this number must be known at compile time so that the compiler can set aside the necessary amount of memory. You create a static array using a Dim statement with a constant argument:

‘This is a static array. Dim Names (100) As String

Visual Basic starts indexing the array with 0. Therefore, the preceding array actually holds 101 items.

Most programs don't use static arrays because programmers rarely know at compile time how many items you need and also because static arrays can't be resized during execution. Both these issues are solved by dynamic arrays. You declare and create dynamic arrays in two distinct steps. In general, you declare the array to account for its visibility (for example, at the beginning of a module if you want to make it visible by all the procedures of the module) using a Dim command with an empty pair of brackets. Then you create the array when you actually need it, using a ReDim statement:

Page 24: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

If you don't specify the lower index of an array, Visual Basic assumes it to be 0, unless an Option Base 1 statement is placed at the beginning of the module. My suggestion is this: Never use an Option Base statement because it makes code reuse more difficult. (You can't cut and paste routines without worrying about the current Option Base.) If you want to explicitly use a lower index different from 0, use this syntax instead:

ReDim Customers (1 To 1000) As String

Dynamic arrays can be re-created at will, each time with a different number of items. When you re-create a dynamic array, its contents are reset to 0 (or to an empty string) and you lose the data it contains. If you want to resize an array without losing its contents, use the ReDim Preserve command:

ReDim Preserve Customers (2000) As String

When you're resizing an array, you can't change the number of its dimensions nor the type of the values it contains. Moreover, when you're using ReDim Preserve on a multidimensional array, you can resize only its last dimension:

ReDim Cells (1 To 100, 10) As Integer ... ReDim Preserve Cells (1 To 100, 20) As Integer ' This works. ReDim Preserve Cells (1 To 200, 20) As Integer ' This doesn't.

Finally, you can destroy an array using the Erase statement. If the array is dynamic, Visual Basic releases the memory allocated for its elements (and you can't read or write them any longer); if the array is static, its elements are set to 0 or to empty strings.

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.

Page 25: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

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.

Page 26: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

UINT IV

GRAPHICAL USER INTERFACE & LANGUAGE REFERENCE

1. Introduction to the Visual Basic Language and Environment Preview In this first class, we will do a quick overview of how to build an application in Visual Basic. You’ll learn a new vocabulary, a new approach to programming, and ways to move around in the Visual Basic environment. You will leave having written your first Visual Basic program. Course Objectives Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool understand the Visual Basic event-driven programming concepts, terminology, and available tools learn the fundamentals of designing, implementing, and distributing a Visual Basic application Learn to use the Visual Basic toolbox Learn to modify object properties Learn object methods Use the menu design window Understand proper debugging and error-handling procedures Gain a basic understanding of database access and management using data bound controls Obtain an introduction to ActiveX controls and the Windows Application Programming Interface (API) Drawing the User Interface and Setting Properties · Visual Basic operates in three modes. Design mode - used to build application Run mode - used to run the application Break mode - application halted and debugger is available We focus here on the design mode.

Page 27: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

Six windows appear when you start Visual Basic. The Main Window consists of the title bar, menu bar, and toolbar. The title bar indicates the project name, the current Visual Basic operating mode, and the current form. The menu bar has drop-down menus from which you control the operation of the Visual Basic environment. The toolbar has buttons that provide shortcuts to some of the menu options. The main window also shows the location of the current form relative to the upper left corner of the screen (measured in twips) and the width and length of the current form.

The Text Box

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. Just like text fields in websites, powered not by Windows, but typically Linux web hosting platforms like page, these fields collect user input. String in a text box can be converted to a numeric data by using the function Val (text). The following example illustrates a simple program that processes the input from the user.

The Label

Page 28: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

The label is a very useful control for Visual Basic, as it is not only used to provide instructions and guides to the users, it can also be used to display outputs. One of its most important properties is Caption. Using the syntax label. Caption, it can display text and numeric data. You can change its caption in the properties window and also at runtime. Please refer to Example 3.1 and Figure 3.1 for the usage of label.

The Picture Box

The Picture Box is one of the controls that is used to handle graphics. You 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. You can also load the picture at runtime using the Load Picture method. For example, the statement will load the picture grape.gif into the picture box.

The Image Box

The Image Box is another control that handles images and pictures. It functions almost identically to the picture box. However, there is one major difference, the image in an Image Box is stretchable, which means it can be resized. This feature is not available in the Picture Box. Similar to the Picture Box, it can also use the Load Picture method to load the picture. For example, the statement loads the picture grape.gif into the image box.

Image1.Picture=Load Picture ("C:\VB program\Images\grape.gif")

The List Box

The function of the List Box is to present a list of items where the user can click and select the items from the list. In order to add items to the list, we can use the Add Item method. For example, if you wish to add a number of items to list box 1, you can key in the following statements

The Combo Box

The function of the Combo Box is also to present a list of items where the user can click and select the items from the list. However, the user needs to click on the small arrowhead on the right of the combo box to see the items which are presented in a drop-down list. In order to add items to the list, you can also use

Page 29: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

the Add Item method. For example, if you wish to add a number of items to Combo box 1, you can key in the following statements

The Check Box

The Check Box control lets the user selects or unselects an option. When the Check Box is checked, its value is set to 1 and when it is unchecked, the value is set to 0. You can include the statements Check1.Value=1 to mark the Check Box and Check1.Value=0 to unmark the Check Box, as well as use them to initiate certain actions. For example, the program will change the background color of the form to red when the check box is unchecked and it will change to blue when the check box is checked. You will learn about the conditional statement if….Then….Elesif in later lesson. VbRed and vbBlue are color constants and Back Color is the background color property of the form.

The Option Box

The Option Box control also lets the user selects one of the choices. However, two or more Option Boxes must work together because as one of the Option Boxes is selected, the other Option Boxes will be unselected. In fact, only one Option Box can be selected at one time. When an option box is selected, its value is set to “True” and when it is unselected; its value is set to “False”. In the following example, the shape control is placed in the form together with six Option Boxes. When the user clicks on different option boxes, different shapes will appear. The values of the shape control are 0, 1, and 2,3,4,5 which will make it appear as a rectangle, a square, an oval shape, a rounded rectangle and a rounded square respectively.

Using Pop-Up Menus

Pop-up menus can show up anywhere on a form, usually being activated by a single or double-click of one of the two mouse buttons. Most Windows applications, and Windows itself, use pop-up menus. For example, using the right hand mouse button on almost any object in Windows 95 will display a pop-up menu. In fact, with the introduction of such pop-up menus with Windows 95, the need for adding such menus to Visual Basic applications has been reduced.

Page 30: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

Adding pop-up menus to your Visual Basic application is a two-step process. First, you need to create the menu using the Menu Editor (or, you can use any existing menu structure with at least one sub-menu). If creating a unique pop-up menu (one that normally does not appear on the menu bar), its Visible property is set to be False at design time. Once created, the menu is displayed on a form using the Popup Menu method.

Assigning Icons to Forms

Notice that whenever you run an application, a small icon appears in the upper left hand corner of the form. This icon is also used to represent the form when it is minimized at run-time. The icon seen is the default Visual Basic icon for forms. Using the Icon property of a form, you can change this displayed icon.

The idea is to assign a unique icon to indicate the form’s function. To assign an icon, click on the Icon property in the Property Window for the form. Click on the ellipsis (...) and a window that allows selection of icon files will appear.

In the previous section, we looked at using multiple forms in a Visual Basic application. Visual Basic actually provides a system for maintaining multiple-form applications, known as the Multiple Document Interface (MDI). MDI allows you to maintain multiple forms within a single container form. Examples of MDI applications are Word, Excel, and the Windows Explorer program.

· An MDI application allows the user to display many forms at the same time. The container window is called the parent form, while the individual forms within the parent are the child forms. Both parent and child forms are modeless, meaning you can leave one window to move to another. An application can have only one parent form. Creating an MDI application is a two-step process. You first create the MDI form (choose Add MDI Form from Project menu) and define its menu structure. Next, you design each of the application’s child forms (set MDI Child property to true).

Design-Time Features of MDI Child Forms:

At design time, child forms are not restricted to the area inside the parent form. You can add controls, set properties, write code, and design the features of child forms anywhere on the desktop.

Page 31: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

You can determine whether a form is a child by examining its MDIChild property, or by examining the project window. The project window uses special icons to distinguish standard forms, MDI child forms, and MDI parent forms:

UNIT V Database Management

The Data Manager is a versatile utility for creating and viewing databases. However, its interface is not that pretty and its use is somewhat cumbersome. We would not want to use it as a database management system (DBMS). Nor, would we expect users of our programs to have the Data Manager available for their use. The next step in our development of our database skills is to use Visual Basic to manage our databases that is developing a DBMS.

We will develop a simple DBMS. It will allow us to view records in an existing database. We will be able to edit records, add records, and delete records. Such advanced tasks as adding tables and fields to a database and creating a new database can be done with Visual Basic, but are far beyond the scope of the discussion here.

To edit an existing record, you simply display the record and make any required changes. The Lock Type property should be set to adLockPessimistic (locks each record as it is edited). Then, when you move off of that record, either with a navigation button or through some other action, Visual Basic will automatically update the record. If desired, or needed, you may invoke the Update method to force an update (use Lock Type = asLockOptimistic).

ADO Data Control

Page 32: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,

The ADO (ActiveX Data Object) data control is the primary interface between a Visual Basic application and a database. It can be used without writing any code at all! Or, it can be a central part of a complex database management system. This icon may not appear in your Visual Basic toolbox. If it doesn’t, select Project from the main menu, then click Components. The Components window will appear. Select Microsoft ADO Data Control, then click OK. The control will be added to your toolbox.

As mentioned in Review and Preview, previous versions of Visual Basic used another data control. That control is still included with Visual Basic 6.0 (for backward compatibility) and has as its icon:

Make sure you are not using this data control for the work in this class. This control is suitable for small databases. You might like to study it on your own.

The data control (or tool) can access databases created by several other programs besides Visual Basic (or Microsoft Access). Some other formats supported include Btrieve, dBase, FoxPro, and Paradox databases. · The data control can be used to perform the following tasks:

1. Connect to a database.

2. Open a specified database table.

3. Create a virtual table based on a database query.

4. Pass database fields to other Visual Basic tools, for display or editing. Such tools are bound tools (controls), or data aware.

5. Add new records or update a database.

6. Trap any errors that may occur while accessing data.

7. Close the database.

Page 33: PAPER – III VISUAL BASICnews.algacis.com/citm_uploads/VISUAL BASIC.pdf · PAPER – III VISUAL BASIC UNIT – I A first glance to VB: Introduction – Features of VB ... In VB6,