kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/visua…  · web viewvisual basic....

88
Visual Basic Visual Basic is an event-driven programming language. The Microsoft Corporation released Visual Basic in 1987. It was indeed the first visual development tool from Microsoft and 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. Visual Basic enables rapid application development of graphical user interface applications, access to databases using DAO, RDO, or ADO, and creation of ActiveX controls and objects. The language not only allows Visual Basic programmers to create simple GUI applications, but also helps them develop quite complex applications. 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 Event driven programming language

Upload: others

Post on 16-Apr-2020

11 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

Visual Basic

Visual Basic is an event-driven programming language. The Microsoft Corporation

released Visual Basic in 1987. It was indeed the first visual development tool from

Microsoft and 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. Visual Basic enables rapid application development of

graphical user interface applications, access to databases using DAO, RDO, or ADO,

and creation of ActiveX controls and objects. The language not only allows Visual

Basic programmers to create simple GUI applications, but also helps them develop

quite complex applications.

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

Event driven programming language

Visual Basic is Event-driven because we need to write code that performs some tasks

in response to certain events. The events usually comprise the user's inputs. Some of

the events are load, click, double click, pressing the keys and more. Besides that, a

Visual Basic Program is made up of many subprograms or modules, each has its own

program code, and each can be executed independently.

Visual Basic is not only a language. It’s an Integrated Development Environment in

which you can develop, run, test and debug your applications. Visual Basic is not only

Page 2: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

a programming language, but it also has a complete graphical development

environment. Visual Basic has the ability to develop programs that can be used as a

front end application to a database system, and serving as the user interface which

collects input from the user and displays formatted output in an attractive format.

 The types of project that you can create in Visual Basic are as follows : 

(i) Standard EXE : These are the typical applications that you develop with previous

versions of Visual Basic.

(ii) ActiveX EXE, ActiveX DLL : These types of projects are available with the

Professional edition. ActiveX components are OLE automation servers.

(iii) ActiveX Control : This type of project is also a feature of the Professional

edition. We use it to develop your own ActiveX controls.

(iv) ActiveX Document EXE, ActiveX Document DLL : ActiveX documents are in

essence Visual Basic applications that can run in the environment of the container that

supports hyper-linking.

(v) VB Application Wizard, VB Wizard Manager : The Application Wizard takes

you through the steps of setting up the skeleton of a new application. The Wizard

Manager lets you build your own wizard.

(vi) Data Project : It’s identical to the Standard EXE project type, but it

automatically adds the controls that are used in accessing databases to the Toolbox.

(vii) DHTML Application : VB6 allows you to build Dynamic HTML pages that can

be displayed in the browser’s window on a client computer.

(viii) IIS Application : VB6 allows you to build applications that run on the Web

server and interact with clients over the Internet with the Internet Information Server.

Page 3: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

(ix) Addin : You can create your own add-ins for the VB IDE. These are special

commands you can add to Visual Basic’s menus.

(x) VB Enterprise Edition Controls : It simply creates a new Standard EXE project

and loads all the tools of the Enterprise Edition of Visual Basic.

How to start Visual Basic

Starting Visual Basic 6.0

Visual Basic is initiated by using the following sequence

Click on Start -> Program option -> Microsoft Visual Studio->

MicrosoftVisual Basic 6.0

Then it opens the screen as:-

Page 4: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

The integrated Development Environment

IDE is the term commonly used in the programming world to describe the interface

and environment that weuse 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 visual basic IDE is made up of the following number of components

Page 5: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

1. Menu Bar 

2. Tool Bar 

3. Tool Box

4. Project Explorer 

5. Properties Window

6. Form Designer 

7. Form layout Window

8. Object Browser 

Menu Bar

Menus contain groups of related capabilities from which the user may select appropriate

choices.The various menus available in the Visual Basic IDE are as follows:-

 

Menu Description

File Contains options for opening projects, closing projects, printing

projects, etc.

Edit Contains options such as cut, paste, find, undo, delete, etc.

View Contains options for displaying IDE windows and tool bars.

Project Contains options for adding features such as forms to the project.

Format Contains options for aligning and locking a form’s controls.

Debug Contains options for debugging.

Run Contains options for executing a program, stopping a program, etc.

Query Contains options for manipulating data retrieved from a database.

Diagram Contains options for editing and viewing the design of databases.

Page 6: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

Tools Contains options for IDE tools and options for customizing the

environment.

Add-Ins Contains options for using, installing and removing add-ins. Add-ins

are typically independent software vendor (ISV) products that extend

Visual Basic’s features.

Windows Contains options for arranging and displaying windows.

Help Contains options for getting help.

Tool Bar 

Rather than having to navigate the menus for certain commonly used

commands, the programmer can select them from the tool bar. The tool bar is

comprised of pictures called icons that represent commands for the commonly used

menu commands.

Toolbox

The toolbox contains a set of  controls that are used to place on form at

design time thereby creating the user  interface. Toolbox contains 21 intrinsic

controls such as .

Page 7: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

  The pointer provides a way to move and resize the control and forms.

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

Frame control serves as a visual and functional container for control.

Checkbox display a True/False or yes/no option.

Textbox is a control used to display message and enter text.

The Listbox display a list of items from which a user can select one.

ComboBox contains a textbox and Listbox. This allows the user to select an

item from DropdownListbox, or to type in a selection in the textbox.

HScrollBar and VScrollBar controls allow the user to select a value within

the specified range of value.

Timer control executes the timer events at specified intervals of time.

Dirlistbox allows the user to select the directories and paths, which are

displayed

Shape control use to draw shape on form.

Page 8: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

Image control is used to display icons, bitmaps, metafiles etc

Project Explorer 

Docked 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. In addition to forms, the Project Explorer

window also lists code modules and classes.

Properties Window- The Properties Window is docked 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

Page 9: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

characteristics of an object are called its properties. Thus, a form has properties and

any controls placed on it will have propeties too. All of these properties are displayed

in the Properties Window.

Form Designer 

The Form window contains a child window named Form1, which is where

the program’s Graphical

User Interface (GUI) will be displayed. A GUI is the visual portion of the

program (i.e., buttons, checkboxes, etc.)–this is where the user enters data (called

inputs) to the program and where the program displays its results (called outputs)

for the user to read.

Page 10: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

Form Layout Window

The Form Layout window specifies a form’s position on the screen at runtime. The

Form Layout window consists of an image representing the screen and the form’s

relative position on the screen. With the mouse pointer positioned over the form

image, drag (i.e., hold down the left mouse button, then move the mouse and

release the button) the form to a new location. Note that the mouse pointer changes

shape when over the image representing the form. Later in the book we discuss the

various shapes that the mouse pointer can assume.

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.

Page 11: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

Features of Visual Basic

Gui Interface: – Vb is a Graphical User Interface language. This means that a VB

program will always show something on the screen that the user can interact with

to get a job done.

Modularization: – It is considered good programming practice to modularize our

programs. Small modules where it is clearly indicated what comes into the module

and what goes out makes a program easy to understand.

Object Oriented: – Object Oriented Programming is a concept where the

programmer thinks of the program in “object” that interact with each other. Visual

Basic forces this good programming practice.

Debugging: – Visual Basic offers two different options for code debugging :-

Debugging Managed Code Runtime Debugger The Debugging Managed Code

Individually debugs C and C++ applications and Visual Basic Windows

applications. The Runtime Debugger helps to find and fix bugs in programss at

runtime.

Data Access Feature: – By using data access features, we can create databases,

scalable sever-side components for most databases, including Microsoft SQL

Server and other enterprise-level database.

Macros IDE: – The Macros integrated development environment is similar in

design and function to the Visual Studio IDE. The Macros IDE includes a code

editor, tool windows, the properties windows and editors.

Page 12: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

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 control.

To see how this is done, use the steps in the following procedures to create a

simple application for the following Visual Basic page

1. Adding a text box to the form. Double-click the toolbox’s textbox to

create a text box with sizing handles in the center of the form.

2. Adding a Command Button1 to the form. Click on button and draw

button1 to form then the button appears on form.

3. Repeat step 2 to add a Command Button2 to the form.

Setting Properties: The next step is to set properties for the objects. The

properties window provides an easy way to set properties for all objects on a

form. For the Example )1( , you’ll need to change three property setting. Use

the default setting for all other properties.

• The Caption property determines what is displayed in the form’s title bar

or what text the controls displays on a form. •

The TextBox’s Text Property determines what text (if any) the TextBox

displays.

• The Name property identifies a form or control. It’s necessary only for

writing code.

Writing Code: The code editor window is where you write Visual Basic

code for your application. Code consists of language statements, constants,

Page 13: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

and declarations. To open the code window, double-click the form or control

for which you choose to write code, or from the Project Explorer window,

select the name of a form and choose the View code button.

In the Object list box, select the name of an object in the active form. Or

double click of an object.

In the procedure list box, select the name of an event for the selected

object. The Click procedure is the default procedure for a command button

and the Load is default procedure for a form.

An event procedure for a control combines the control’s actual name

(specified in the name property), an underscore ( _ ), and the event name.

For example (Command1_click).

Type the code between the Sub and the End Sub statements. Choose the

command1 and type the following code:

Private Sub Command1_click ( )

Text1.text=”Welcome”

End Sub

Choose the command2 and type the following code:

Private Sub Command2_click ( )

End

End Sub

Note: The statement END used to close the program runtime.

Running the Application: To run the application, choose start from the run

menu, or click the start button on the toolbar , or F5 Click the command

button (O.k.) and see the “Welcome” displayed in the text box. Click the

command button (close) the end the program and return to the form window.

Page 14: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

Variable: Variables are the memory locations which are used to store values

temporarily. A defined naming strategy has to be followed while naming a variable.

Naming rules of variable.

1. Must begin with a letter.

2. Cannot have a period (remember that we use the period to set a property; in

other words the period is an operator)

3. Can have up to 255 characters. Please, just because it is allowed, don't use 255

characters.

4. Must be unique inside of the procedure or the module it is used in (we will

learn what a module is)

5. It should not contain any special character like %, &, !, #, @ or $.

Data types

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.

Data Types (Constant and Variable):

Page 15: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

Data types control internal storage of data in Visual Basic. There are a number of

variable data types that allow you to optimize your code for speed and size.

1- Boolean: A variable of type Boolean requires 2 bytes of memory and holds

either the value True or False. If boolVar is a Boolean variable, then the

statement Print boolVar displays(1) when the value is True and displays (0)

when the value is False.

2- Currency: The currency data type is extremely useful for calculations

involving money. A variable of type Currency requires 8 bytes of memory

and can hold any number from -9x1014 to 9x1014.

3- Date: A variable of type Date requires 8 bytes of memory and holds numbers

representing dates from January 1St 100 To December 31St 9999. Values of

dateVar are displayed in the form month/day/year (for example, 5/12/1996).

4- Single: A variable of type Single requires 4 bytes of memory and can hold 0,

the numbers from 1.40129x10-45 to 3.40283x1038 with the most seven

significant digits, and the negatives of these numbers.

5- Double: A variable of type Double requires 8 bytes of memory and can hold

0, the numbers from 4.94065x10-324 to 1.7976x10308 with at most 14

significant digits and the negatives of these numbers.

6- Integer: A variable of type integer requires 2 bytes of memory and can hold

the whole numbers from -32,768 to 32,767.

7- Long: A variable of type Long requires 4 bytes of memory and can hold the

whole numbers from -2x109 to 2x109.

8- String: A variable of type string requires 1 byte of memory per character and

can hold a string of up to 32,767 characters, string values are enclosed in

quotes. A variable of type String holds a string of n characters, where n is a

whole number from 1 to 32,767.

Page 16: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

9- Variant: A variable of type variant can be assigned numbers, Strings and

several other types of data. A variable of type variant requires 16 bytes of

memory and can hold any type of data. When values are assigned to a

variant variable, Visual Basic keeps track of the “type “of data that has been

sorted 9for example, type 2 for integer).By default, Visual Basic uses the

variant data type

Byte Store integer values in the range of 0 - 255

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

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

SingleStore floating point value in the range of (-3.4x10-38) - (+ 3.4x1038)

DoubleStore large floating value which exceeding the single data type value

Currencystore monetary values. It supports 4 digits to the right of decimal point and 15 digits to the left

Operators in Visual Basic

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

Page 17: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

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

= 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

Arrays

· Up to now, we've only worked with regular variables, each having its own unique

name. Visual Basic has powerful facilities for handling multi-dimensional

variables, or arrays. For now, we'll only use single, fixed-dimension arrays.

· Arrays are declared in a manner identical to that used for regular variables. For

example, to declare an integer array named 'Items', with dimension 9, at the

procedure level, we use:

Dim Items(9) as Integer

If we want the array variables to retain their value upon leaving a procedure, we

use the keyword Static:

Page 18: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

Static Items(9) as Integer

At the form or module level, in the general declarations area of the Code window,

use:

Dim Items(9) as Integer

And, at the module level, for a global declaration, use:

Global Items(9) as Integer

· The index on an array variable begins at 0 and ends at the dimensioned value.

For example, the Items array in the above examples has ten elements, ranging

from Items(0) to Items(9). You use array variables just like any other variable –

just remember to include its name and its index.

For example, to set Item(5) equal to

7, you simply write:

Item(5) = 7

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

Page 19: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

If <condition> 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 <condition > Then

statements

Else

statements

End If

e.g.: If average>50 Then

txtGrade.Text = "Pass"

Else

txtGrade.Text = "Fail"

End If

Page 20: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

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 as shown

If < condition 1 > Then

statements

ElseIf < condition 2 > Then

statements

ElseIf < condition 3 > Then

statements

Else

Statements

End If

Loops

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

Page 21: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

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.

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 <=100

number = number + 1

Wend

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

Page 22: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

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.

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

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:

Page 23: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

Dim x As Integer

For x = 1 To 50

Print x

Next

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

used

For x = 1 To 50 Step 2

Print x

Next

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

Page 24: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

The Message Box

· One of the best functions in Visual Basic is the message box. The message box

displays a message, optional icon, and selected set of command buttons. The

user responds by clicking a button.

· The statement form of the message box returns no value (it simply displays the

box):

MsgBox Message, Type, Title

where

Message Text message to be displayed

Type Type of message box (discussed in a bit)

Title Text in title bar of message box

You have no control over where the message box appears on the screen.

· The function form of the message box returns an integer value (corresponding to

the button clicked by the user). Example of use (Response is returned value):

Dim Response as Integer

Response = MsgBox(Message, Type, Title)

· The Type argument is formed by summing four values corresponding to the

buttons to display, any icon to show, which button is the default response, and the

modality of the message box.

The first component of the Type value specifies the buttons to display:

Value Meaning Symbolic Constant

0 OK button only vbOKOnly

1 OK/Cancel buttons vbOKCancel

2 Abort/Retry/Ignore buttons vbAbortRetryIgnore

Page 25: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

3 Yes/No/Cancel buttons vbYesNoCancel

4 Yes/No buttons vbYesNo

5 Retry/Cancel buttons vbRetryCancel

· The second component of Type specifies the icon to display in the message

box:

Value Meaning Symbolic Constant

0 No icon (None)

16 Critical icon vbCritical

32 Question mark vbQuestion

48 Exclamation point vbExclamation

64 Information icon vbInformation

Form

The Form is where the user interface is drawn. It is central to the development of

Visual Basic applications.

Form Properties:

Appearance Selects 3-D or flat appearance.

BackColor Sets the form background color.

BorderStyle Sets the form border to be fixed or sizeable.

Caption Sets the form window title.

Enabled If True, allows the form to respond to mouse and Keyboard events; if

False, disables form.

Page 26: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

Font Sets font type, style, size.

ForeColor Sets color of text or graphics.

Picture Places a bitmap picture in the form.

Visible If False, hides the form.

Form Events:

Activate Form_Activate event is triggered when form becomes the active

window.

Click Form_Click event is triggered when user clicks on form.

DblClick Form_DblClick event is triggered when user doubleclicks on form.

Load Form_Load event occurs when form is loaded.

This is a good place to initialize variables and set any runtime properties. ·

Form Methods:

Cls Clears all graphics and text from form. Does not clear any objects.

Print Prints text string on the form.

Examples frmExample.Cls ' clears the form frm

Example.Print "This will print on the form.

Command Button:

Page 27: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

The command button is probably the most widely used control. It is used to begin,

interrupt, or end a particular process.

Command Button Properti es:

Appearance Selects 3-D or flat appearance.

Cancel Allows selection of button with Esc key (only one button on a

form can have this property True).

Caption String to be displayed on button.

Default Allows selection of button with Enter key (only one button on

a form can have this property True).

Font Sets font type, style, size.

Command Button Events:

Click Event triggered when button is selected either by clicking on it or by pressing

the access key

Label Boxes

· A label box is a control you use to display text that a user can't edit directly. the text

of a label box can be changed at run-time in response to events.

Label Properties:

Page 28: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

Alignment Aligns caption within border.

Appearance Selects 3-D or flat appearance.

AutoSize If True, the label is resized to fit the text specifed by the caption

property. If False, the label will remain the size defined at design time and the text

may be clipped.

BorderStyle Determines type of border.

Caption String to be displayed in box.

Font Sets font type, style, size.

WordWrap Works in conjunction with AutoSize property. If AutoSize = True,

WordWrap = True, then the text will wrap and label will expand vertically to fit the

Caption. If AutoSize = True, WordWrap = False, then the text will not wrap and the

label expands horizontally to fit the Caption. If AutoSize = False, the text will not

wrap regardless of WordWrap value.

Label Events:

Click Event triggered when user clicks on a label.

DblClick Event triggered when user double-clicks on a label.

Text Boxes

· A text box is used to display information entered at design time, by a user at

runtime, or assigned within code. The displayed text may be edited.

Text Box Properties:

Page 29: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

Appearance Selects 3-D or flat appearance.

BorderStyle Determines type of border.

Font Sets font type, style, size.

MaxLength Limits the length of displayed text (0 value indicates unlimited

length).

MultiLine Specifies whether text box displays single line or multiple lines.

PasswordChar Hides text with a single character.

ScrollBars Specifies type of displayed scroll bar(s).

SelLength Length of selected text (run-time only).

SelStart Starting position of selected text (run-time only).

SelText Selected text (run-time only).

Tag Stores a string expression.

Text Displayed text.

Text Box Events:

Change Triggered every time the Text property changes.

LostFocus Triggered when the user leaves the text box. This is a good place to

examine the contents of a text box after editing.

KeyPress Triggered whenever a key is pressed. Used for key trapping, as seen in

last class.

Text Box Methods:

Page 30: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

SetFocus Places the cursor in a specified text box.

Check Boxes

· Check boxes provide a way to make choices from a list of potential candidates.

Some, all, or none of the choices in a group may be selected.

Check Box Properties:

Caption Identifying text next to box.

Font Sets font type, style, size.

Value Indicates if unchecked (0, vbUnchecked), checked (1, vbChecked), or grayed

out (2, vbGrayed).

Check Box Events:

Click Triggered when a box is clicked. Value property is automatically changed by

Visual Basic.

Option Buttons

· Option buttons provide the capability to make a mutually exclusive choice among a

group of potential candidate choices. Hence, option buttons work as a group, only one

of which can have a True (or selected) value.

Option Button Properties:

Caption Identifying text next to button.

Font Sets font type, style, size.

Page 31: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

Value Indicates if selected (True) or not (False). Only one option button in a group

can be True. One button in each group of option buttons should always be initialized

to True at design time.

Option Button Events:

Click Triggered when a button is clicked. Value property is automatically changed by

Visual Basic.

Control Arrays

· With some controls, it is very useful to define control arrays - it depends on the

application. For example, option buttons are almost always grouped in control arrays.

· Control arrays are a convenient way to handle groups of controls that perform a

similar function. All of the events available to the single control are still available

tothe array of controls, the only difference being an argument indicating the index of

the selected array element is passed to the event. Hence, instead of writing individual

procedures for each control (i.e. not using control arrays), you only have to write one

procedure for each array.

· Another advantage to control arrays is that you can add or delete array elements at

run-time. You cannot do that with controls (objects) not in arrays. Refer to the Load

and Unload statements in on-line help for the proper way to add and delete

control array elements at run-time.

· Two ways to create a control array:

Page 32: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

1. Create an individual control and set desired properties. Copy the control using the

editor, then paste it on the form. Visual Basic will pop-up a dialog box that will ask

you if you wish to create a control array. Respond yes and the array is created.

2. Create all the controls you wish to have in the array. Assign the desired control

array name to the first control. Then, try to name the second control with the same

name. Visual Basic will prompt you, asking if you want to create a control array.

Answer yes. Once the array is created, rename all remaining controls with that name.

· Once a control array has been created and named, elements of the array are referred

to by their name and index. For example, to set the Caption property of element 6 of a

label box array named lblExample, we would use:

lblExample(6).Caption = “This is an example”

Frames

· We've seen that both option buttons and check boxes work as a group. Frames

provide a way of grouping related controls on a form. And, in the case of option

buttons, frames affect how such buttons operate.

· To group controls in a frame, you first draw the frame. Then, the associated controls

must be drawn in the frame. This allows you to move the frame and controls together.

And, once a control is drawn within a frame, it can be copied and pasted to create a

control array within that frame. To do this, first click on the object you want to copy.

Copy the object. Then, click on the frame. Paste the object. You will be asked if you

want to create a control array. Answer Yes.

Page 33: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

· Drawing the controls outside the frame and dragging them in, copying them into a

frame, or drawing the frame around existing controls will not result in a proper

grouping. It is perfectly acceptable to draw frames within other frames. · As

mentioned, frames affect how option buttons work. Option buttons within a frame

work as a group, independently of option buttons in other frames. Option buttons on

the form, and not in frames, work as another independent group. That is, the form is

itself a frame by default. We'll see this in the next example.

· It is important to note that an independent group of option buttons is defined by

physical location within frames, not according to naming convention. That is, a

control array of option buttons does not work as an independent group just because it

is a control array. It would only work as a group if it were the only group of option

buttons within a frame or on the form. So, remember physical location, and physical

location only, dictates independent operation of option button groups.

Frame Properties:

Caption Title information at top of frame.

Font Sets font type, style, size.

List Boxes

· A list box displays a list of items from which the user can select one or more items.

If the number of items exceeds the number that can be displayed, a scroll bar is

automatically added.

Page 34: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

List Box Properties:

Appearance Selects 3-D or flat appearance.

List Array of items in list box.

ListCount Number of items in list.

ListIndex The number of the most recently selected item in list.

If no item is selected, ListIndex = -1. MultiSelect Controls how items may be selected

(0-no multiple

selection allowed, 1-multiple selection allowed, 2- group selection allowed). Selected

Array with elements set equal to True or False, depending on whether corresponding

list item is selected.

Sorted True means items are sorted in 'Ascii' order, else items appear in

order added.

Text Text of most recently selected item.

List Box Events:

Click Event triggered when item in list is clicked.

DblClick Event triggered when item in list is double-clicked.

Primary way used to process selection.

List Box Methods:

AddItem Allows you to insert item in list.

Clear Removes all items from list box.

Page 35: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

RemoveItem Removes item from list box, as identified by index of item to remove.

Combo Boxes

· The combo box is similar to the list box. The differences are a combo box

includes a text box on top of a list box and only allows selection of one item. In

some cases, the user can type in an alternate response.

· Combo Box Properties:

Combo box properties are nearly identical to those of the list box, with the deletion of

the MultiSelect property and the addition of a Style property.

Appearance Selects 3-D or flat appearance.

List Array of items in list box portion.

ListCount Number of items in list.

ListIndex The number of the most recently selected item in list.

If no item is selected, ListIndex = -1. Sorted True means items are sorted in 'Ascii'

order, else items appear in order added. Style Selects the combo box form. Style = 0,

Dropdown combo; user can change selection.

Style = 1, Simple combo; user can change selection.

Style = 2, Dropdown combo; user cannot change

selection. Text Text of most recently selected item.

Combo Box Events:

Page 36: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

Click Event triggered when item in list is clicked.

DblClick Event triggered when item in list is double-clicked.

Primary way used to process selection.

Combo Box Methods:

AddItem Allows you to insert item in list.

Clear Removes all items from list box.

RemoveItem Removes item from list box, as identified by index of item to remove.

Line Tool

· The line tool creates simple straight line segments of various width and color.

Together with the shape tool discussed next, you can use this tool to 'dress up' your

application.

Line Tool Properties:

BorderColor Determines the line color.

BorderStyle Determines the line 'shape'. Lines can be transparent, solid,

dashed, dotted, and

combinations.

BorderWidth Determines line width.

· There are no events or methods associated with the line tool.

Page 37: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

Shape Tool

The shape tool can create circles, ovals, squares, rectangles, and rounded squares and

rectangles. Colors can be used and various fill patterns are available.

Shape Tool Properties:

BackColor Determines the background color of the shape (only used when FillStyle

not Solid.

BackStyle Determines whether the background is transparent or opaque.

BorderColor Determines the color of the shape's outline.

BorderStyle Determines the style of the shape's outline. The border can be

transparent, solid, dashed, dotted, and combinations.

BorderWidth Determines the width of the shape border line.

FillColor Defines the interior color of the shape.

FillStyle Determines the interior pattern of a shape. Some choices are: solid,

transparent, cross, etc.

Shape Determines whether the shape is a square, rectangle, circle, or some other

choice.

Like the line tool, events and methods are not used with the shape tool

Horizontal and Vertical Scroll Bars

· Horizontal and vertical scroll bars are widely used in Windows applications. Scroll

bars provide an intuitive way to move through a list of information and make great

input devices.

Page 38: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

· Both type of scroll bars are comprised of three areas that can be clicked, or dragged,

to change the scroll bar value. Those are as are: Clicking end arrow increments the

scroll boxes a small amount, clicking the bar area increments the scroll boxes a large

amount, and dragging the scroll box (thumb) provides continuous motion. Using the

properties of scroll bars, we can completely specify how one works. The scroll box

position is the only output information from a scroll bar.

Scroll Bar Properties:

LargeChange Increment added to or subtracted from the scroll bar Value property

when the bar area is clicked.

Max The value of the horizontal scroll bar at the far right and the value of the

vertical scroll bar at the bottom. Can range from -32,768 to 32,767.

Min The other extreme value - the horizontal scroll bar at the left and the vertical

scroll bar at the top. Can range from -32,768 to 32,767.

SmallChange The increment added to or subtracted from the scroll bar Value

property when either of the scroll arrows is clicked.

Value The current position of the scroll box (thumb) within the scroll bar. If you set

this in code, Visual Basic moves the scroll box to the proper position.

Scroll Bar Events:

Change Event is triggered after the scroll box's position has been modified. Use this

event to retrieve the Value property after any changes in the scroll bar. Scroll Event

triggered continuously whenever the scroll box is being moved.

MDI

Page 39: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

The Multiple Document Interface (MDI) was designed to simplify the exchange of

information among documents; you can maintain multiple open windows. The main

Form, or MDI Form, isn't duplicated, but it acts as a container for all the windows,

and it is called the parent window. The windows in which the individual documents

are displayed are called Child windows. At run time, an MDI form and all of its child

forms take on special characteristics:

All child forms are displayed within the MDI form's workspace. The user can move

and size child forms like any other form; however, they are restricted to this

workspace.

By setting the AutoShowChildren property, you can display child forms

automatically when forms are loaded (True), or load child forms as hidden (False).

Advantages of MDI

MDI applications can often handle multiple documents more readily than SDI

programs. For example, many MDI text editors allow the user to open multiple text

files side by side in the same window.

It easy to compare and look up information from a second document while working

on the first.

MDI applications tend to perform more quickly than SDI programs.

SDI

(i) It stands for single Document Interface.

(ii) There is no concept of parent window rather every window is independent of

each other.

(iii) It acts as an container for other windows or forms.

Page 40: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

(iv) All the windows can be moved freely

Visual Basic Functions

· Visual Basic offers a rich assortment of built-in functions. The on-line help

utility will give you information on any or all of these functions and their use.

Some examples are:

Function Value Returned

Abs Absolute value of a number

Asc ASCII or ANSI code of a character

Chr Character corresponding to a given ASCII or ANSI code

Cos Cosine of an angle

Date Current date as a text string

Format Date or number converted to a text string

Left Selected left side of a text string

Len Number of characters in a text string

Mid Selected portion of a text string

Now Current time and date

Right Selected right end of a text string

Rnd Random number

Sin Sine of an angle

Sqr Square root of a number

Str Number converted to a text string

Time Current time as a text string

Timer Number of seconds elapsed since midnight

Val Numeric value of a given text string

Page 41: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

Menu Editor

The Menu Editor allows us to define the menu structure, adding access keys

and shortcut keys, if desired. We then add code to the Click events we need to

respond to. The Menu Editor is selected from the Tools menu bar or by

clicking the Menu Editor on the toolbar. This selection can only be made when

the form needing the menu is active. Upon selecting the editor, and entering

the example menu structure

The Caption box is where you type the text that appears in the menu bar.

Access keys are defined in the standard way using the ampersand (&).

Separator bars (a horizontal line used to separate menu items) are defined by

using a Caption of a single hyphen (-). When assigning captions and access

keys, try to use conform to any established Windows standards.

· The Name box is where you enter a control name for each menu item. This is

analogous to the Name property of command buttons and is the name used to

set properties and establish the Click event procedure for each menu item.

Each menu item must have a name, even separator bars! The prefix mnu is

used to name menu items. Sub-menu item names usually refer back to main

menu headings. For example, if the menu item New is under the main heading

File

menu, use the name mnuFileNew.

· The Index box is used for indexing any menu items defined as control arrays.

· The Shortcut dropdown box is used to assign shortcut keystrokes to any item

in a menu structure. The shortcut keystroke will appear to the right of the

Page 42: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

caption for the menu item. An exa mple of such a keystroke is using Ctrl+X to

cut text.

· The HelpContextID and NegotiatePosition boxes relate to using on-line help

and object linking embedding, and are beyond the scope of this discussion.

· Each menu item has four properties associated with it. These properties can

be set at design time using the Menu Editor or at run-time using the standard

dot notation. These properties are:

Checked Used to indicate whether a toggle option is turned on or off. If True, a

check mark appears next to the menu item.

Enabled If True, menu item can be selected. If False, menu item is grayed and

cannot be selected.

Visible Controls whether the menu item appears in the structure.

WindowList Used with Multiple Document Interface (MDI)

At the bottom of the Menu Editor form is a list box displaying the hierarchical

list of menu items. Sub-menu items are indented to their level in the hierarchy.

The right and left arrows adjust the levels of menu items, while the up and

down arrows move ite ms within the same level. The Next, Insert, and Delete

buttons are used to move the selection down one line, insert a line above the

current selection, or delete the current selection, 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

Page 43: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

Windows 95, the need for adding such menus to Visual Basic applications has

been reduced.

· 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), it’s Visible

property is set to be False at design time. Once created, the menu is displayed

on a form using the PopupMenu method.

· The PopupMenu method syntax is:

ObjectName.PopupMenu MenuName, Flags, X, Y

The ObjectName can be omitted if working with the current form. The

arguments are:

MenuName Full-name of the pop-up menu to display.

Flags Specifies location and behavior of menu (optional).

X, Y (X, Y) coordinate of menu in twips (optional; if either value is omitted,

the current mouse coordinate is used).

· The Flags setting is the sum of two constants. The first constant specifies

location:

Value Meaning Symbolic Constant

0 Left side of menu is at X coordinate vbPopupMenuLeftAlign

4 Menu is centered at X coordinate vbPopupMenuCenterAlign

8 Right side of menu is at X coordinate vbPopupMenuRightAlign

Common Dialog Boxes

· The primary use for the drive, directory, and file name list boxes is to develop

custom file access routines. Two common file access routines in Windows-

Page 44: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

based applications are the Open File and Save File operations. Fortunately, you

don’t have to build these routines.

· To give the user a standard interface for common operations in Windows-

based applications, Visual Basic provides a set of common dialog boxes, two

of which are the Open and Save As dialog boxes. Such boxes are familiar to

any Windows user and give your application a professional look. And, with

Window s 95, some context-sensitive help is available while the box is

displayed.

· The Common Dialog control is a ‘custom control’ which means we have to

make sure some other files are present to use it. In normal setup configurations,

Visual Basic does this automatically. If the common dialog box does not

appear in the Visual Basic toolbox, you need to add it.

This is done by selecting Components under the Project menu. When the

selection box appears, click on

Microsoft Common Dialog Control, then click OK.

· The common dialog tool, although it appears on your form, is invisible at run-

time. You cannot control where the common dialog box appears on your

screen. The tool is invoked at run-time using one of five ‘Show’ methods.

These methods are:

Method Common Dialog Box

ShowOpen Open dialog box

ShowSave Save As dialog box

ShowColor Color dialog box

ShowFont Font dialog box

ShowPrinter Printer dialog box

Page 45: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

Open Common Dialog Box

· The Open common dialog box provides the user a mechanism for specifying

the name of a file to open. We’ll worry about how to open a file in Class 6. The

box is displayed by using the ShowOpen method.

Open Dialog Box Properties:

CancelError If True, generates an error if the Cancel button is clicked.

Allows you to use error-handling procedures to recognize that Cancel was

clicked.

DialogTitle The string appearing in the title bar of the dialog box.

Default is Open

FileName Sets the initial file name that appears in the File name box. After the

dialog box is closed, this property can be read to determine the name of the

selected file.

Save As Common Dialog Box

· The Save As common dialog box provides the user a mechanism for

specifying the name of a file to save. The box is displayed by using the

ShowSave method..

Save As Dialog Box Properties (mostly the same as those for the Open box):

CancelError If True, generates an error if the Cancel button is clicked. Allows

you to use error-handling procedures

to recognize that Cancel was clicked. DefaultExt Sets the default extension of a

file name if a file is listed without an extension. DialogTitle The string

appearing in the title bar of the dialog box.

Default is Save As

Page 46: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

FileName Sets the initial file name that appears in the File name box.

After the dialog box is closed, this property can be read to determine the name

of the selected file.

Filter Used to restrict the filenames that appear in the file list box.

FilterIndex Indicates which filter component is default.

Flags Values that control special features of the dialog box

String functions

Here is a list of the basic functions that work with strings:

Len(string): returns the length of string, the number of characters it contains.

Left(string, number): returns the number of characters specified by number

from the left end of string.

Right(string, number): returns the number of characters specified by number

from the right end of string.

Mid(string, position, number): returns the number of characters specified by

number starting at character number position from the left end of string.

Page 47: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

InStr(string1, string2): returns the position of string2 in string1 - returns 0 if

string2 is not found in string1.

LTrim(string), RTrim(string) and Trim(string): returns string with non-

significant spaces removed from the left, the right or both, respectively.

LCase(string), UCase(string): returns string converted to lower-case or upper-

case, respectively.

Date Functions

S.No. Function & Description

1 Date A Function, which returns the current system date.

2 CDate A Function, which converts a given input to date.

3 DateAdd A Function, which returns a date to which a

specified time interval has been added.

4 DateDiff A Function, which returns the difference between

two time period.

5 DatePart A Function, which returns a specified part of the

given input date value.

6 DateSerial A Function, which returns a valid date for the given

year, month, and date.

Page 48: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

7 FormatDateTime A Function, which formats the date based on the

supplied parameters.

8 IsDate A Function, which returns a Boolean Value whether

or not the supplied parameter is a date.

9 Day A Function, which returns an integer between 1 and

31 that represents the day of the specified date.

10 Month A Function, which returns an integer between 1 and

12 that represents the month of the specified date.

11 Year A Function, which returns an integer that represents the

year of the specified date.

12 MonthName A Function, which returns the name of the particular

month for the specified date.

13 WeekDay A Function, which returns an integer(1 to 7) that

represents the day of the week for the specified day.

14 WeekDayName A Function, which returns the weekday name for

the specified day.

Page 49: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

The Print Method

Print is a fundamental BASIC statement that dates back to the first days of the

language in the mid-1960s. Print is used to display lines of data on a form,

picture box, printer, and the immediate (Debug) window; it can also be used to

write records of data to a file. In VB, Print is implemented as a method of the

following objects:

Form You can print lines of data directly to the background of a

form. This is done in the examples in the section, although it is not typically

done in regular VB applications. Statements that print to a form begin in any of

the following ways:

Form1.Print . . .

Me.Print . . .

Print . . .

Picture Box You can print lines of data or graphics to a PictureBox

control, with syntax beginning like the following:

PictureBox1.Print . . .

· Debug object You can print lines of data to the VB Immediate

Window, using syntax beginning like the following:

Page 50: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

Debug.Print . . .

Printer You can print lines of data to the Windows default printer,

using syntax beginning like the following:

Printer.Print . . .

To write data to a file, the Print # statement is used, using syntax beginning

like the following:

Print #1, . . .

Printing to files is a common way to write data to a sequential file; this will be

covered in detail in a later section.

The general format for the Print method is:

[object.]Print [expressionlist]

where object refers to one of the objects mentioned above (Form, PictureBox,

Debug window, Printer) and expressionlist refers to a list of one or more

numeric or string expressions to print.

Items in the expression list may be separated with semicolons (;) or commas

(,). A semicolon or comma in the expression list determines where the next

output begins:

Page 51: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

; (semicolon) means print immediately after the last value.

, (comma) means print at the start of the next "print zone".

Printing with the semicolon (;) separator

As noted above, items in the expression list of a Print statement that are

separated by semicolons print immediately after one another. In the statement

Print "Hello,"; strName; "How are you today?"

If strName contained "HARRY", the Print statement would generate the

following output:

Hello,HARRYHow are you today?

Database

Database is a collection of data or information that can be stored, sorted,

organized and retrieved. Your local telephone book and the card catalog at

Page 52: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

your local library are examples of a database. Traditionally databases are

organized by fields, records, and files tables.

Field is A is single piece of information; a record is a one complete set of

fields; a file is a collection of records. For example, a telephone book is

analogous to a file. It contains a list of records, each of which consists of three

fields: name, address, and telephone number .

To access information form a database, you need a database management

system (DBMS). This is a collection of programs that enables you to enter,

organize, and select data in a database.

There is different type of technique used to make connection between the

visual basic and database (Access), like:

Data Access Objects (DAO)

ActiveX Data Objects (ADO)

Remote Data Objects (RDO)

DAO

Data Access objects (DAO) communicate with Microsoft Access and other

ODBC complaint data sources through the JET engine. They provide

properties and methods that allow to perform all the operation necessary to

manage such a system, including the ability to do the following.

Create databases

Define tables, fields, and indexes

Establish relations between tables.

Navigate and query the database, and so on.

Page 53: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

The important properties of the Data Control:

Name: the name to use in code - Data1 is default - eventually we'll have

several data controls on the form - we'll call this one dta_proj.

Connect: the kind of database - in this case it's Access - could be Foxpro,

dBaseIV, etc.

DatabaseName: the name and path of the database the control is connected to.

RecordSource: the name of the database table being used.

BOFAction and EOFAction: action to take when trying to read before the

beginning of file or past the end of file - we'll look at those later.

Recordset: this is a run time property, it represents the result of the query

executed to the database - it contains all the records required by the Data

Control - when you navigate through the database, you are actually navigating

through the recordset, which is then mapped back to the database - that is why

the methods of the Data Control refer to the Recordset property.

Next we add the controls needed to look at the fields in the records. In many

instances we will need to make changes to the data. Therefore, we'll use a

TextBox for each of the fields so that we can both diaplay and enter data as

needed. Each TextBox will be a bound control, meaning that it is bound or tied

to a specific field from the database. When we navigate through the database

using the arrow buttons the content of each TextBox will always reflect the

content of the current field. To bind the control to the database field we use its

Data properties:

Page 54: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

DataSource is the name of the Data Control - remember that the DC specifies

the name of the database to use and the name of the table to access - tip: enter

this one before the DataField.

DataField is the name of the field to bind - that field is selected from the

content of the table.

How to connect with database using DAO

After placing a DAO data control on a form, set the DatabaseName property

first. Simply click on the ellipsis in the property box and choose the database.

Then, set the RecordSource property. Click on that property’s drop-down

arrow and a list of valid tables will be presented. Choose the desired table.

This establishes the Recordset object. By following these steps carefully, we

avoid run-time errors associated with inability to find referenced data.

Recordset Object

The Recordset object is an important concept. When we set the

RecordSource property (either select a table from the database or form a virtual

table via a query), the data control (using the Jet engine) retrieves the needed

records and places them in the Recordset object for our use. We will see that

this object has its own properties and methods for our use.

Page 55: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

There are three types of recordsets, established via the RecordsetType

property:

Table Representation of a native database table (not formed via

a query). You can add, change, or delete records.

Dynaset The default type, a Dynaset is formed as the result of a

database query. You can add, change, or delete records from the underlying

table(s). This is the most flexible Recordset type.

Snapshot A static copy of records that cannot be updated. Used if

you are just viewing or searching a database table.

Data Bound Controls

· The DAO data control allows us to easily connect to a database and form

a Recordset. Yet, that control alone does not provide us with anyway to view

the information in the database. To view the information, we use data bound

controls that are special controls with properties established by database fields.

A data bound control is needed for each field (column) in the Recordset

(database table) you need to view. Most of the standard Visual Basic tools can

be used as data bound controls.

Page 56: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

Standard data bound data controls are:

Label Can be used to provide display-only access to a specified

text data field. Caption property is data bound.

Text Box Can be used to provide read/write access to a specified

text data field. Probably, the most widely used data bound tool. Text property

is data bound.

Check Box Used to provide read/write access to a Boolean field.

Value property is data bound.

Picture Box Used to display a graphical image from a bitmap, icon, gif,

jpeg, or metafile file. Provides read/write access to a image/binary data field.

Picture property is data bound.

Image Box Used to display a graphical image from a bitmap, icon,

gif, jpeg, or metafile file (uses fewer resources than a picture box). Provides

read/write access to a image/binary data field. Picture property is data bound.

There are also three ‘custom’ data bound controls, the bound combo box, the

bound list box, and the bound data grid tool.

Data Bound Control Properties

Page 57: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

To establish the connection of the data bound control to a database, we use a

few properties:

DataChanged Indicates whether a value displayed in a bound control has

changed.

DataField Specifies the name of a field in the table pointed to by the

respective data control.

DataSource Specifies which data control the control is bound to

(indirectly specifying the database table).

· If the data in any data bound control is changed and the user moves to

another record in the database, the database will automatically be updated with

the new data (assuming it is not ReadOnly). Be aware of this - it is an

extremely powerful feature of the data control, but also a potential source of

problems.

· To make using bound controls easy, follow these steps (in order listed)

in placing the controls on a form:

Page 58: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

Draw the bound control on the same form as the data control to which it will be

bound.

Set the DataSource property. Click on the drop-down arrow to list the data

controls on your form. Choose one.

Set the DataField property. Click on the drop-down arrow to list the fields

associated with the selected data control records. Make your choice.

Set all other properties, as needed.

DAO Data Control Events

Like other controls, the DAO data control has events that are triggered at

various times during database access.

Using the ADO Data Control

Add the Microsoft ADO Data Control 6.0 (OLEDB) component to your

project.

Create an instance of the ADO Data Control on your form.

Connect to a database with the ADO Data Control by building a connection

string.

Set the RecordSource property of the ADO Data Control

Create bound controls on your form.

Building a Connection String

In the properties window of the ADO Data control’s choose the

ConnectionString property.

From the property pages, choose Use Connection String and choose Build

From the Provider tab in the Data Link Properties dialog box, specify which

data provider to use.

Page 59: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

use Microsoft Jet 4.0 OLE DB Provider for Access databases

choose Next >> to bring up the Connection tab of the Data Link Properties

dialog box.

– Use a data Data Link File

– Use an ODBC Data Source Name

– Use a Connection String

From the Connection tab, enter your database name and path (or browse for it)

Leave the default log on information

Test Connection

Set the RecordSource property of the ADO Data Control

choose the RecordSource property. Choose a Command Type

adCmdUnknown

adCmdTable

adCmdText

adCmdStoredProc

Select a table or enter an SQL statement

Creating Bound Controls

Many different controls that can hold text and graphics can be bound to a field

in an ADO Data control.

Set the DataSource property of the bound control to the ADO Data Control.

Set the DataField property of the bound control to the field you want to

display.

You will need a separate ADO Data Controls on your form for each table or

query you need to access.

Page 60: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

RDO

The following are the steps in using RDO

Create a new blank project.

Add a new form using the VB Data Form Wizard. To create a new form select Project from the menu bar, then click Add Form. The Add Form dialog box will then appear.Select Remote(ODBC) as the Database type. Then click Next.Under Form Layout select Single record, then click Next.Select the Dataset or File you wish to view as the Record Source. Add Available Fields to your form. Then click NextChange the MSRDC properties to optimze the use of the selection. For speedier browsing, choose a smaller value for RowsetSize. To limit the result set, enter a WHERE clause in the SQL statement.

Page 61: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

The material has been retrieved from the various websites as shown below:-

Retrieved from https://www.streetdirectory.com/travel_guide/114415/programming/visual_basic_programming_language_and_its_significant_features.htmlRetrieved from http://ecomputernotes.com/visual-basic/basic-of-visual-basic/what-is-an-ide

Retrieved from  http://www.tutorialized.com/tutorial/Introduction-to-VB-IDE/3869

Retrieved from  https://www.freetutes.com/learn-vb6/lesson1.html

Retrieved from  https://www.freetutes.com/learn-vb6/lesson2.html

Retrieved from  https://www.freetutes.com/learn-vb6/lesson4.html

Retrieved from http://marjan.fesb.hr/~tihana/Programiranje1/2.pdf

Retrieved from http://www.indiantechrain.com/visual-basic/

Retrieved from  https://www.uop.edu.jo/download/research/members/vb6_1__1_.0%20-%20visual%20basic%20-%20learn%20visual%20basic%206.0%20%28nice%20manual%29.pdf

Retrieved from  http://www.profsr.com/vb/vbless09.htm

Page 62: kcgpwamb002.edu.inkcgpwamb002.edu.in/wp-content/uploads/2018/10/VISUA…  · Web viewVisual Basic. Visual Basic is an event-driven programming language. The Microsoft Corporation

Retrieved from   https://sites.google.com/site/technicalcontents/databaseconnectionwiththedaodatacontrol

http://www.profsr.com/vb/vbless07.htm

https://www.tutorialspoint.com/vba/vba_date_time.htmhttps://www.thevbprogrammer.com/Ch03/03-04-Print1-Semi.htm