0% found this document useful (0 votes)
94 views

Visual Basic Programming

Visual Basic (VB) is an event-driven programming language that allows developers to easily create graphical user interfaces. It has a visual integrated development environment (IDE) that incorporates design, editing, compiling, and debugging tools. The IDE contains elements like menu bars, toolbars, a toolbox, and windows for debugging. VB uses event-driven programming where the program flow is determined by user interactions or messages. It has many built-in functions, operators, and features for developing applications.

Uploaded by

ashfaque1968
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views

Visual Basic Programming

Visual Basic (VB) is an event-driven programming language that allows developers to easily create graphical user interfaces. It has a visual integrated development environment (IDE) that incorporates design, editing, compiling, and debugging tools. The IDE contains elements like menu bars, toolbars, a toolbox, and windows for debugging. VB uses event-driven programming where the program flow is determined by user interactions or messages. It has many built-in functions, operators, and features for developing applications.

Uploaded by

ashfaque1968
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

VISUAL BASIC PROGRAMMING

UNIT - I
Introduction
(BASIC – Beginners all-purpose Symbolic Instruction Code)
It is developed in 1991. It is even driven, non-procedural, object based high level language. VB is the
fastest and easiest way to create applications for Microsoft Windows. VB has the ability to develop
programs that can be used as front end application to a database system. It is effectively used for
developing the prototypes of large software.

The Visual refers to the method used to create the graphical user interface (GUI) instead of writing
numerous lines of code. We can simply add pre build objects on screen. For example a drawing program
Paint.
The Basic refers to the basic (Beginners all-purpose Symbolic Instruction Code) language

Features
 User friendly interface
 ActiveX support
 Faster complier
 Userful debugger and error handling facilities
 Large library of user controls – helps in designing an interface

IDE Integrated Development Environment


The working environment in VB is often referred to as Integrated Development Environment (IDE)
because it integrates many different functions such as design, editing, compiling and debugging within a
common environment. IDE comprises of multiple windows that come up on the screen. It makes all the
tools available at one place which are required for designing an application.

Components of IDE

Menu Bar – It contain File, Edit, View, Project, Format, Debug, Run, Query, Tools, Add-Ins, Window, Help

Context Menus - it contain shortscuts to frequently performed actions. The specific list of shortcuts
available from context menu.

Tool Bars – it provide quick access to commonly used command in the programming envoirnment.
Tool Box – It contains the icons of the control that can be placed on a form to create the application.
Project Explorer Window – it contains list of forms and modules in our current project. A project is a
collection of files we used to build an application.
Properties window – it contain settings for the selected object like caption, color
Object Bxrowser – it gives us a quick way to navigate through our code
Form Layout Window – it allow us to position the forms in our application
Immediate, Locals and Watch windows – it is used for debugging an application.
Immediate Window – it is used to get current values of variables and to run other code
Even Driven Programming – it is a computer programming paradigm. Unlike traditional programs, which
follow their own flow pattern, the even driven programs are largely driven by external events. It is Style
of programming where the flow of the program is determined by user Actions (mouse clicks, key
presses) or messages from other programs.

System Defined Functions / Library Functions

String Functions
Math Functions
Date Functions
Conversion Functions
User Interaction Functions / Dialog Box

String Functions – it is used for strings processing. This function return a string, although some return a
number
Lean Function – used for find out length of the string
Ucase – converts all lowercase letters in a string to uppercase
Lcase – converts all uppercase letters in a string to lowercase

Math Functions – it is used to perform basic mathematical task.


ABS – return absolute value which is neither negative nor positive
Sqr – used to calculate Square root of the specified number
Int – it return the first negative number that might be less or equal to the number that was
passed to it.
Sgn – it return integer value
Sing – it return the sine of an angle
Cos – It return cosine of an angle
Tan – It return tangent of an angle

Date Function - it supports different date functions which return date and time
Date – this function returns the current date
Now – this function returns the current date and time
Time – this function return the current system time
Day – this function returns the integer which represents the day of the month
Weekday – returns a number from 1 to 7 indicating the day of the week for given date
Hour – returns an integer specifying a whole number between 8 and 23

User Interaction Function / Dialog Boxes – In windows based applications, dialog boxes are used to
prompt the user for data needed by the application to continue or to display information to the user.
Predefined dialog boxes –
Customized dialog boxes –
Standard Dialog Bosex -

SHORT NOTES -

OPERATORS
Arithmetic Operator - Carat, * Multiplication, / Division, \ Integar Division, + Addition, - Sub
Assignment Operator - = = *= /= += -=
Comparison / Relational Operator - < <= > >= = <>
Concatenation Operator - & +
Logical Operator – and, o,r not, xor
Operator Precedence in VB

EVENT DRIVEN PROGRAMMING

Visual Basic (VB) is an event-driven programming language. This is called because programming is done
in a graphical environment unlike the previous version BASIC where programming is done in a text only
environment and executed sequentially in order to control the user interface. Visual Basic enables the
user to design the user interface quickly by drawing and arranging the user elements. Due to this spent
time is saved for the repetitive task.

Event driven programming is a style of programming where the flow of the program is determined by
user actions (mouse click, key presses) or messages from other programs. Graphical user interface
programs are typically programmed in an event driven style. Event driven programs typically consist of a
number of small programs called event handlers, which are to be called in response to external events,
which calls the event handlers. Event driven programming is a flexible way to allow our programs to
respond to many different inputs or events.

Important Features of Visual Basic (VB)

 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 file support
 Useful debugger and error-handling facilities
 Powerful database access tools
 ActiveX support
 Package & Deployment Wizard makes distributing your applications simple

DATA TYPES :
When we declare a variable, we can supply a data type for it. All variables have a data type that
determines what kind of data they can store. The VB classified data into the following types

 Numeric Data Type


 Non Numeric Data Type
 Variant Data Type

Numeric Data Type contains numbers. Ex.: Integer, Long, Single, Double, Currency, Byte

Non Numeric Data Type contains characters and phrases. Ex.: String, Boolean, Date, Object
Variant Data Type is capable of storing all system defined types of data. We don’t have to convert
between these type of data If we assign them to a variant variable. The variant variable can also contain
three special values : Empty, Null, and Error.

VARIABLES / IDENTIFIERS

VARIABLE
Variables uses for storing data value. Variable are used to store temporarily during the
execution of an application. Using variable we can store, retrieve, and manipulate values.
Variable have a name and a data type. Variable can represent many types of values like text
values, dates, various numeric types even object.

Variable is an entity whose values may change during the execution of programme. Variable
can be declared as integer, real, character etc. variable can be used to store the result of query
for later processing or temporarily holding the calculation.

Local variable
- when we declare a variable within a function, the variable can only be accessed within that
function. When we exit the function, the variable is destroyed. Each variable is recognized only
by the function in which it is declared.

Globle variable
- a variable declared outside a function. And all the function on your web page can access it.
These variable is known as Globle variable. These variable starts when they are declared and
ends when the page is closed.

CONSTANT
A constant is a data whose value does not change during execution. The declaration of constant
is same as that of declaring variable except the keyword constant. The VB has a number of built
in constants, such as data access constants, keycode constants, color definition constants that
are used for various programming purposes. We can define our own constants as per our
requirements.

ARRAY
Array is a collection of similar data items that has a common name. An array can hold any type
of data and these are stored in adjacent locations into memory. For ex suppose we want to
arrange the marks obtained by 100 students in ascending order. In this case there are two
options first we have to assign 100 variables for each student to store the marks. Or second
construct one variable capable of storing or holding all the 100 values. Ex = (11,4,21,10,2)
Properties of an array

 An array is a collection of similar type of elements.


 These elements can be all integers of all characters or all floats
 The type of an array is type of its elements.
 The location of an array is the location of its 1st element
 An array is known as subscripted variable

User-Defined data type

Variables of different data types when combined as a single variable to hold several related
informations is called a User-Defined data type.

A Type statement is used to define a user-defined type in the General declaration section of a
form or module. User-defined data types can only be private in form while in standard modules
can be public or private. An example for a user defined data type to hold the product details is
as given below.

Private Type ProductDetails


ProdID as String
ProdName as String
Price as Currency
End Type

The user defined data type can be declared with a variable using the Dim statement as in any
other variable declaration statement. An array of these user-defined data types can also be
declared. An example to consolidate these two features is given below.

Dim ElectronicGoods as ProductDetails ' One Record


Dim ElectronicGoods(10) as ProductDetails ' An array of 11 records

A User-Defined data type can be referenced in an application by using the variable name in the
procedure along with the item name in the Type block. Say, for example if the text property of a
TextBox namely text1 is to be assigned the name of the electronic good, the statement can be
written as given below.

Text1.Text = ElectronicGoods.ProdName

If the same is implemented as an array, then the statement becomes

Text1.Text = ElectronicGoods(i).ProdName

User-defined data types can also be passed to procedures to allow many related items as one argument.

Sub ProdData( ElectronicGoods as ProductDetails)


Text1.Text = ElectronicGoods.ProdName
Text1.Text = ElectronicGoods.Price
Unit – II

Control flow statement: if-then, select-case, for-next, while wend, do-loop statement.
Visual Basic Controls: Frame, Checkbox, Option Button, ListBOx, ComboBox,
ScrollBar, DriveListBox, FileListBox, Timer, Status Bar, Image List, Tree View.

Taking different actions when a condition is true and when it is false

Decision Structures 
If...Then...Else Construction
If...Then...Else constructions allow you to test for one or more conditions and run one or more statements
depending on each condition. You can test conditions and take actions in the following ways:

 Run one or more statements if a condition is True


 Run one or more statements if a condition is False
 Run some statements if a condition is True and others if it is False
 Test an additional condition if a prior condition is False

The control structure that offers all these possibilities is the If...Then...Else Statement (Visual Basic). You can use a
single-line version if you have just one test and one statement to run. If you have a more complex set of
conditions and actions, you can use the multiple-line version.

Select...Case Construction
The Select...Case construction allows you to evaluate an expression once and run different sets of statements
based on different possible values. For more information, see Select...Case Statement (Visual Basic).

Try...Catch...Finally Construction
Try...Catch...Finally constructions allow you to run a set of statements under an environment that retains
control if any of your statements causes an exception. You can take different actions for different exceptions.
You can optionally specify a block of code that is to run before you exit the entire Try...Catch...Finally
construction, no matter what happens. For more information, see Try...Catch...Finally Statement (Visual Basic).
Loop Structures 
Visual Basic loop structures allow you to run one or more lines of code repetitively. You can repeat the
statements in a loop structure until a condition is True, until a condition is False, a specified number of times,
or once for each element in a collection.

The following illustration shows a loop structure that runs a set of statements until a condition becomes true.

Running a set of statements until a condition becomes true

While Loops
The While...End While construction runs a set of statements as long as the condition specified in the While
statement is True. For more information, see While...End While Statement (Visual Basic).

Do Loops
The Do...Loop construction allows you to test a condition at either the beginning or the end of a loop structure.
You can also specify whether to repeat the loop while the condition remains True or until it becomes True. For
more information, see Do...Loop Statement (Visual Basic).

For Loops
The For...Next construction performs the loop a set number of times. It uses a loop control variable, also called
a counter, to keep track of the repetitions. You specify the starting and ending values for this counter, and you
can optionally specify the amount by which it increases from one repetition to the next. For more information,
see For...Next Statement (Visual Basic).

For Each Loops


The For Each...Next construction runs a set of statements once for each element in a collection. You specify the
loop control variable, but you do not have to determine starting or ending values for it. For more information,
Control Structures

If...Then...Else
If condition1 Then
     statements1
Else
     statements2
End If

If condition1 is True, then statements1 block is executed; Else, condition1 is not


True, therefore statements2 block gets executed. The structure must be terminated
with the End If statement.

The Else clause is optional. In a simple comparison, statements1 get executed or


not.

If condition1 Then
     statements1
End If

Select Case
Can be used as an alternative to the If...Then...Else structure, especially when
many comparisons are involved.

Select Case ShirtSize


     Case 1
          SizeName.Caption = "Small"
     Case 2
          SizeName.Caption = "Medium"
     Case 3
          SizeName.Caption = "Large"
     Case 4
          SizeName.Caption = "Extra Large"
     Case Else
          SizeName.Caption = "Unknown size"
End Select
Do...Loop
Used to execute a block of statements an unspecified number of times.

Do While condition
     statements
Loop

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.

For...Next
When the number of iterations of the loop is known, it is better to use the
For...Next rather than the Do...Loop.

For counter = start To end


     statements
Next

1) The counter is set to the value of start.


2) Counter is checked to see if it is greater than end; if yes, control passes to the
statement after the Next; if not the statements are executed.
3)At Next, counter is incremented and goes back to step 2).

More will be covered on Control strucures as it becomes necessary in upcoming


lessons. Meanwhile,if you want to know more, consult the VB Language Reference.

VB CONTROLS

 Intrinsic controls
 Active X
 Insertable Objects

Intrinsic controls, such as command button and frame controls. These controls are contained inside the
VB .exe file. It is always included in the toolbox which can be removed from or added to the toolbox. Ex.:
Text box, Label, Command button, Frame, Check box, Option button, List Box, Combo box etc
Active X these separate files with extension .OCX. These can be added to the toolbox

Insertable Objects such as Microsoft Excel Worksheet object containing a list of employee. These can be
added to the tool box and used as a controls.

CHECK BOX – It is commonly used to present a Yes/No or True/False selection to the user. We can use
check box controls in groups to display multiple choices from which the user can select one or more. As
check boxes work independently of each other, we can select any number of check boxes at the same
time.

FRAME – It is used to provide an indetifiable grouping for other controls. For example we can use fram
controls to subdivide a form functionally to separate groups of option button controls.

OPTION BUTTON – It is mainly used to select an option from a group of option. It is also known as ratio
button.

LIST BOX – Present a list of choices to the user. If no of items exceeds than the size, scroll bars
automatically appeared on the control. The user can scroll up and down, left to right through the list.

COMBO BOX – Allow the user to select an item either by typing text into the combo box, or by selecting
it from the list. Combo box contains edit field, so choices not on the list can be typed in this field. It
present the list of choices to the user. If no If no of items exceeds than the size, scroll bars automatically
appeared on the control. The user can scroll up and down, left to right through the list.

SCROLL BARS are two types one Horizontal and another is vertical scroll bars. The scroll bars provide
easy navigation through a long list of items or a large amount of information by scrolling either
horizontally or vertically within an application or control. We can use scroll bar to magnify an image,
increase the voulme

DRIVE LIST BOX is a drop down list box. By default, the current drive is displayed on the user’s system.
We can select a drive from the list at run time to perform operations like directory browsing. The
important properties of this control are Drive, List, ListCount, Listindex, Change Event.

FILE LIST BOX displayed files contained in the directory specified by the path property at run time. The
important properties of the control are File Name, Normal, Hidden, Archive, System, ReadOnly,
Listcount, List, Listindex, Pattern, Selected, Path

TIMER – Timer controls respond to the passage of time. They are independent of the user, and we can
program them to take actions at regular intervals. A typical response is checking the system clock to see
if it is time to perform some task. Timers are useful for background processing.

STATUS BAR is a horizontal window at the bottom of a parent window in which an application can
display various kind of status information.

IMAGE LIST is a collection of images of the same size, each of which can be referred by its index. Image
lists are used to efficiently manage large set of incons or bitmaps, which represents the data to be
displayed by the control.
TREE VIEW control is a window that displays a hierarchical list of items, such as the headings in a
document, the entries in an index or the files and directories on a disk.

LABEL – It is used to display text such as status messages to the user and cannot be edited by the user.
The property of the label contains Captions, Alignment, AutoSize, WordWrap

COMMAND BUTTON – it is used to begain, interrupt or end a process. When we click it invokes a
command that has been written into its click event procedure. The property of the command button
contains Caption, Name, Value, BackColor and ForeColor, Cancel, Default, Style, Picture etc.

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

The Command Button 


The command button is one of the most important controls as it is used to execute commands.
It displays an illusion that the button is pressed when the user click on it. The most common
event associated with the command button is the Click event, and the syntax for the procedure
is
Private Sub Command1_Click ()
Statements
End Sub

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 LoadPicture
method. For example, the statement will load the picture grape.gif into the picture box.
Picture1.Picture=LoadPicture ("C:\VB program\Images\grape.gif")

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 LoadPicture method to load the picture. For
example, the statement loads the picture grape.gif into the image box.

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 AddItem 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 the AddItem method.
 
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 BackColor 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.

The Drive List Box


The Drive ListBox is for displaying a list of drives available in your computer. When you place
this control into the form and run the program, you will be able to select different drives from
your computer as shown in Figure 3.3
 
The Directory List Box
The Directory List Box is for displaying the list of directories or folders in a selected drive. When
you place this control into the form and run the program, you will be able to select different
directories from a selected drive in your computer.
 
The File List Box
The File List Box is for displaying the list of files in a selected directory or folder. When you place
this control into the form and run the program, you will be able to shown the list of files in a
selected directory. You can coordinate the Drive List Box, the Directory List Box and the File List
Box to search for the files you want. The procedure will be discussed in later lessons.
http://www.scribd.com/doc/24339321/Visual-Basic-6-0-Notes-short

Unit – III
Creating MDI (Multiple Document Interface) from – parent and child form. Menu editor, menu
properties, creating the pop-up menu, dynamic menus. Creating a toolbar.

Multiple-Document Interface (MDI) Applications


The multiple-document interface (MDI) allows you to create an application that maintains multiple forms within
a single container form. Applications such as Microsoft Excel and Microsoft Word for Windows have multiple-
document interfaces.

An MDI application allows the user to display multiple documents at the same time, with each document
displayed in its own window. Documents or child windows are contained in a parent window, which provides a
workspace for all the child windows in the application. For example, Microsoft Excel allows you to create and
display multiple-document windows of different types. Each individual window is confined to the area of the
Excel parent window. When you minimize Excel, all of the document windows are minimized as well; only the
parent window's icon appears in the task bar.

A child form is an ordinary form that has its MDIChild property set to True. Your application can include many
MDI child forms of similar or different types.

At run time, child forms are displayed within the workspace of the MDI parent form (the area inside the form's
borders and below the title and menu bars). When a child form is minimized, its icon appears within the
workspace of the MDI form instead of on the taskbar, as shown in Figure 6.4.

Figure 6.4   Child forms displayed within the workspace of the MDI form
Note   Your application can also include standard, non-MDI forms that are not contained in the MDI form. A
typical use of a standard form in an MDI application is to display a modal dialog box.

An MDI form is similar to an ordinary form with one restriction. You can't place a control directly on a MDI form
unless that control has an Align property (such as a picture box control) or has no visible interface (such as a
timer control).

Creating an MDI Application


Use the following procedure to create an MDI form and its child forms.
To create an MDI application

1. Create an MDI form.


From the Project menu, choose Add MDI Form.
Note   An application can have only one MDI form. If a project already has an MDI form, the Add
DI Form command on the Project menu is unavailable.

2. Create the application's child forms.


To create an MDI child form, create a new form (or open an existing one) and set its MDIChild
property to True.

MENU
Menus are used to provide information under relevant headings. A menu makes the interface
of an application more appealing and easy to use. It enables user to view options under the
relevant.
Advantages of MENU
 It provides complete set of command
 Menu increases the accessibility of an application
 The use of menu reduces the number of action required to perform a specific task
 Menus do not require users to memorize large commands.
 Menu enhance the navigation of an application.

MENU EDITOR
Menu editor is used to create new menus and menu bars, add new commands to existing menus,
replace existing menu commands with our own commands, and change and delete existing menus and
menu bars. From the tools menu, choose the Editor or click the menu Editor button on the toolbar.
Menu Properties : Caption and Name
Optional Properties : Index, Shortcut, HelpcontextID, Negotiation position, Checked, Enabled,
Visible, Window List etc.

POP-UP MENUS
A pop-up menu is a floating menu that is displayed over a form, independent of menu bar. The items
displayed on pop-up menu depend on where the pointer was located when the right mouse button was
pressed. Any menu has at least one menu item can be displayed at run time as pop-up menu. Only one
pop-up menu can be displayed at a time.

DYNAMIC MENU
We can add menu item at run time. Similar to the adding any control at runtime. First we have to create
a control array at design time, then at run time we just load the new controls into the array.

CREATING TOOL BOX

UNIT IV
Active X Data Objects (ADO)
The bridge between the data providers and data consumers is through data sources created using
Microsoft ActiveX Data Objects, which is the primary method in VB to access data in any data source,
both relational and non relational

DATA CONTROL
The data control is a link between information in our databases and the bound controls that we use to
display the information. As we set the properties of the Data Control, we tell it which database is to
connect and what part of that database is to access

PROPERTIES OF DATA CONTROL


RecordsetType, DafaultType, DefaultCursorType, exclusive, Options,BOFAction, EOFAAction

DATA BOUND CONTROLS

 Data Bound List Control (DBList)


 Data Bound Combobox Control (DBCombo)
 The Data Bound Grid Control (DBGrid)
Data Bound List Control (DBList) : can be bound to a specific column of the Recordset. It has the
standard dataSource/Data Field properties, which are used just like any other data bound control and
the RowSource/List field properties that determine how the control populated

You might also like