Visual Basic PDF
Visual Basic PDF
Contents
CHAPTER 1: INTRODUCTION TO VISUAL BASIC ................................................................................ 3
1.1 Concepts ............................................................................................................................................. 3
1.2 The Importance of Visual Basic Program ............................................................................................ 3
1. 3 Visual BASIC environment ................................................................................................................ 4
1.4 Steps in Developing Application ......................................................................................................... 5
1.6 Project ................................................................................................................................................ 6
CHAPTER 2: INTEGRATED DEVELOPMENT ENVIRONMENT (IDE) ................................................ 10
2.1 Menu Bar.......................................................................................................................................... 10
Menu bar ................................................................................................................................................ 10
2.3 ToolBox ........................................................................................................................................... 11
ToolBox ................................................................................................................................................. 11
2.4 Form Designer .................................................................................................................................. 12
Form designer......................................................................................................................................... 12
2.5 Properties Window ........................................................................................................................... 13
Properties window .................................................................................................................................. 13
2.6 Project Explorer Window .................................................................................................................. 14
2.7 Form Layout Window ....................................................................................................................... 14
2.8 Code Editor Window: ....................................................................................................................... 14
2.9 Environment options (SDI, MDI) ...................................................................................................... 15
CHAPTER 3: VISUAL BASIC CONTROLS ............................................................................................ 17
3.1.1 Form properties .......................................................................................................................... 17
3.1.2 Code form .................................................................................................................................. 18
3.1.3 Form and event .......................................................................................................................... 18
3.3 Text Box ........................................................................................................................................... 21
3.5 Option button.................................................................................................................................... 26
3.7 Timer ................................................................................................................................................ 28
CHAPTER 4: CODE ELEMENT ............................................................................................................... 33
4.1 Declaration of variables and constants and data types .................................................................. 33
4.1.1 Data types used in visual basic ................................................................................................... 33
4.1.2 Declaration of variable and constant ........................................................................................... 34
1
VISUAL BASIC PROGRAMMING
2
VISUAL BASIC PROGRAMMING
a. Visual: The "Visual" part refers to the method used to create the graphical user interface (GUI).
b. BASIC: (Beginners All-Purpose Symbolic Instruction Code) language, a language used by more
programmers than any other language in the history of computing.
c. Visual Basic: Visual Basic is a Microsoft Windows Programming language. Visual basic allows
user to create GUI. Visual Basic programs are created in an Integrated Development Environmental
(IDE). The IDE allows the programmer to create, run and debug Visual Basic programs
conveniently. : It is Language developed in early 1960's at Dartmouth College
c. Objects: is the collection of controls (labels, command button, textbox, checkbox etc) and form
that allow user to create a project.
d. Events: An event is a specific action that occurs on or with a certain object.
Examples of event used in VISUAL BASIC are: click, Dblclick, change, load, keypress, mouse
down etc
e. Procedure: a procedure is the block of visual basic statement enclosed by declaration statement
(sub, function, operator, get, and set) and a matching end declaration.
1. It uses integrated development environment (IDE) which is easier for the user to minimize code
writing.
3
VISUAL BASIC PROGRAMMING
2. All visual programs follow the same concepts; therefore the user will become more familiar with
visual approach for other visual languages.
3. It provides Input box and Output box as an interactive window with user.
4. It is able to connect to Internet, and to call Explorer.
Visual Basic implements graphical user interface that allows the use of graphics for different
applications. It provides visual interactive windows with user, like Dialogue box for (color, font)
Input box, and Output box .Also it is able to create menu to simplify user application.
To run this program on user computer:
To exit from Visual Basic and return to Windows is like exit from most Windows applications.
There are three ways to close the Visual Basic as stated below.
1- Click on close button icon that appears in the upper-left corner of the screen.
2- Press Alt+F4
4
VISUAL BASIC PROGRAMMING
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
Example: step1 and 2:
5
VISUAL BASIC PROGRAMMING
Output
1.6 Project
Project is a program designed to user application that may be simple (like calculator program) or
complex (like word program). Visual basic program can create many types of projects. The most
important or usual project is the standard project (for window applications) and the DHTML project
(for internet).
Working with Standard Projects:
The following working steps (create, save, add, open and delete) could be done:
a) To create project:
6
VISUAL BASIC PROGRAMMING
e) To save project: The visual basic can save the project on disc in two ways, as an executable type
or a non- executable type.
7
VISUAL BASIC PROGRAMMING
For project in non execution stage: There are many types of files summarized as follows:
1. Project file: it consists of all files which are related to specific project,also some other
information with it. This could be saved with extension(.VBP)
2. The form Files: this contains form description and any Object or program related to it .This is
saved with extension (.frm).
Example1 of application:
Private Sub Form_Load ( )
Form1.show
Print “Welcome to Visual Basic tutorial”
End Sub
8
VISUAL BASIC PROGRAMMING
Example2:
Private Sub Form_Activate ( )
Print 20 + 10
Print 20 - 10
Print 20 * 10
Print 20 / 10
End Sub
9
VISUAL BASIC PROGRAMMING
10
VISUAL BASIC PROGRAMMING
2.2 Toolbar
Tool bar contains several icons that provide quick access to commonly used features.
2.3 ToolBox
ToolBox contains a collection of tools (controls) that are needed for project design. To show the
toolbox press View> toolbox icon. The user can place the tool on form, and then work with the tool.
To place the tool on form: click on tool > draw tool to form > the tool appears on form or double
click on tool then the tool appears on form.
11
VISUAL BASIC PROGRAMMING
12
VISUAL BASIC PROGRAMMING
13
VISUAL BASIC PROGRAMMING
Code Editor Window is used to write a VB code for an application. For each form there is a
separate code editor window. It is displayed when user clicks on form or object in form.
14
VISUAL BASIC PROGRAMMING
SDI: single document interface is one where all windows appear independently of one other
without unification of a single parent window .
MDI: multiple document interfaces is one that allows you to view multiple windows within a larger
window.
15
VISUAL BASIC PROGRAMMING
Project > Add MDI form. Click Project from the menu bar and click Add MDI form.
These restrictions are there because MDI forms are special type of forms, only used to handle
multiple child forms.
In your project, there will be only one MDI parent form with one or more MDI child forms (or
simply child forms).
MDI child form: To add a child form, you have to add a regular form, and set the MDIchild
property to True. You can have many child forms. You can show an MDI child form using
the Show method as same as the regular forms.
AutoShowChildren property of an MDI form: The default value is True. When its True,
the MDI child forms are displayed when they are loaded. When the value is False, only then
you can keep it hidden after loading, otherwise not.
16
VISUAL BASIC PROGRAMMING
The most important properties of the form are listed in the following table:
17
VISUAL BASIC PROGRAMMING
Examples:
1- Design a form such that: in event load, when project runs, the form backcolor property changed
(chose any color).
Eg: code:
18
VISUAL BASIC PROGRAMMING
Result
3.2 Labels:
Label is used to display fixed text on form
19
VISUAL BASIC PROGRAMMING
20
VISUAL BASIC PROGRAMMING
The textbox is a box for entering and displaying text (characters or values) in user project. This tool
is used frequently in most of the application. The textbox has property window, with no caption, but
with space for text. The most important property of this tool is the text content which is described in
the following:
21
VISUAL BASIC PROGRAMMING
Example: Design a form to enter username and password such that the title of the form is VB.
Example: Design a form with one textbox, set the text properties so that this massage appears when
project runs (welcome to visual basic world).
22
VISUAL BASIC PROGRAMMING
Running stage
It acts as a switch. To deal with tool property> click on command button> property window
appear> change setting of any desired property. Usually change set its caption property to a suitable
string. To make the button functional; the user should add some code. To do this: click on command
tool> code form appears with click event procedure. Write code in this event or other events like
keypress event.
23
VISUAL BASIC PROGRAMMING
Example: Design a form with label, such that when click on the command button "name" your
name appears on label (at running stage).
Example: Design a form to appear your name and department in textbox, when click on command
button "name" and "department" respectively so that you can clear these informations when click on
command "clear" and stop project when click on command "exit".
24
VISUAL BASIC PROGRAMMING
25
VISUAL BASIC PROGRAMMING
Option button is used only as a group of buttons. When the user selects one of them the others are
deselected automatically. All other properties of this control are similar to those in form and
command button where they are fully discussed which are caption, font, enabled, backcolor and
visible beside an important property which is value that takes true or false and it used with if
statement. The option button usually takes click event.
Example: Design a form with three option buttons " red ", " green " and " blue " such that when we
click on options the color of the form colored by red, green and blue respectively.
26
VISUAL BASIC PROGRAMMING
Example: Design a form with one text box and three check boxes such that when click on boxes the
following is done: change typing to bold, italic, underline.
27
VISUAL BASIC PROGRAMMING
3.7 Timer
Timer returns the time in millisecond. It may be used to measure execution time of code (program
efficiency).
28
VISUAL BASIC PROGRAMMING
A list control in Visual Basics 6.0 is a control which helps to display data vertically to the user on
the form of a list.
A list box has many entries and is selected by the user. These entries are not generated
automatically, there are entered by methods AddItem, the method RemoveItem help to delete
these entries from a list. To clear the whole content of a list we use Listname.clear , To refresh list
content we use Listname.Refresh
Example:
29
VISUAL BASIC PROGRAMMING
List the following department names in a Visual Basics 6.0 list control:
Computer Electronics
Computer science
Accounting
Secretary
ListA.AddItem “secretary”
ListA.AddItem “Accounting”
ListA.AddItem “Construction”
30
VISUAL BASIC PROGRAMMING
3.9 ComboBox
A comboBox control is a combination of TextBox control and ListBox control on only one entity. It
allows to add entries or to select from a list predefined values.
List the following department names in a Visual Basics 6.0 ComboBox control:
Computer Electronics
Computer science
Accounting
Secretary
Construction
Combo1.AddItem “secretary”
Combo1.AddItem “Accounting”
Combo1.AddItem “Construction”
31
VISUAL BASIC PROGRAMMING
Note: the procedure for add a list box and combo box must be placed in form not in control itself,
and they are two way to add it.
Combo1.AddItem “programming”
Combo1.AddItem “networking”
End sub
32
VISUAL BASIC PROGRAMMING
33
VISUAL BASIC PROGRAMMING
4.1.2.1 Variables
Variable is used to store value. The value of the variable may vary during the program execution.
Declaration of a variable
The declaration means defining the variable type. When you declare a variable, memory space for
the variable is reserved. This is called memory allocation. Different amount of memory space is
reserved for different data types.
Syntax:
34
VISUAL BASIC PROGRAMMING
Example:
Private Sub cmdSum_Click()
Dim m As Integer
Dim n As Integer
Dim sum As Integer
End Sub
You can declare many variables in one line as follows and assign multiple variables in one line
using ':' operator.
Private Sub cmdSum_Click()
Dim m As Integer, n as Integer, sum as Integer
m = 10 : n = 30
sum = m + n
End Sub
35
VISUAL BASIC PROGRAMMING
Example:
Implicit declaration: The variable is declared “on the fly” its data type is deduced from other
variable:
Dim X As Integer
Dim Balance As Currency
Dim Y As Long
Dim A AS Double,
B As Double
Dim Month As Date
Dim Max As Single
Dim Name As String
Dim Z,V,C
36
VISUAL BASIC PROGRAMMING
Example2:
You can create your own constant to use it in your program. The value of the constant remains
unchanged throughout the program.
37
VISUAL BASIC PROGRAMMING
Example3:
Private Sub cmdCalculate_Click()
Const pi = 3.1415926 'or Const pi As Double = 3.1415926
Dim area As Double, r As Double
r=2
area = pi * r * r
Print area
End Sub
Output: 12.5663704
38
VISUAL BASIC PROGRAMMING
Code stage:
Dim a,b, c as single
Private sub command1_click ()
a = val(text1.text)
b = val(text2.text)
c=a+b
text3.text = c
End sub
39
VISUAL BASIC PROGRAMMING
40
VISUAL BASIC PROGRAMMING
5.1. If statement
The comparison operations are used with conditional statements. The comparison operations are:
(<, <=, >, >=, =, <>, and, or)
There are four structures for if statement.
a) Simple structure If.. then:
Used for running one programming statement only if the required condition satisfied.
The general form is:
If condition then statement
Example 1: write a program to enter a mark of a student then print (pass) if he successful.
Sol:
Dim x as integer
Private sub command1_click()
X= val (text1.text)
If x>= 50 then text2.text= "pass"
End sub
b) If block structure: Used for running many programming statements if the required condition
satisfied.
41
VISUAL BASIC PROGRAMMING
Sol:
Dim x as integer
Private sub command1_click()
X= val(text1.text)
If x>= 50 then
text2.text= "pass"
text2.fontsize=18
end if
End sub
c) If.. Then.. Else structure: Used for running many programming statements if the required
condition satisfied. And running another programming statements (after else) if the required
condition not satisfied.
42
VISUAL BASIC PROGRAMMING
If condition then
Statements
Else
Statements
End if
End Sub
43
VISUAL BASIC PROGRAMMING
44
VISUAL BASIC PROGRAMMING
Example 5: Write a program to classify any entered number according to its sign and display the
phrase (negative number) when the number is negative and the phrase (positive number) when the
number is positive, otherwise display the phrase (neither positive nor negative).
Sol:
Dim x As Single
Private Sub command1_click ()
x = Val (Text1.Text)
If x > 0 Then
MsgBox "positive number"
ElseIf x < 0 Then
MsgBox "negative number"
Else
MsgBox "neither positive nor negative"
End If
End Sub
45
VISUAL BASIC PROGRAMMING
Nested If statement:
It can be takes the following structure:
46
VISUAL BASIC PROGRAMMING
The format is :
Select Case expression
Case value1
Block of one or more VB statements
Case value2
Block of one or more VB Statements
Case value3
Block of one or more VB statements
Case value4
Case Else
Block of one or more VB Statements
End Select
Example 7: write a program to print the days of the week when we enter
its number
Sol:
Dim x As Integer
Private Sub Command1_Click()
x = val(Text1.Text)
Select Case x
Case 1
MsgBox ("Sunday")
Case 2
MsgBox ("Monday")
47
VISUAL BASIC PROGRAMMING
Case 3
MsgBox ("Tuesday")
Case 4
MsgBox ("Thursday")
Case 5
MsgBox ("Wednesday")
Case 6
MsgBox ("Friday")
Case 7
MsgBox ("Saturday")
End Select
End Sub
48
VISUAL BASIC PROGRAMMING
Running
49
VISUAL BASIC PROGRAMMING
Example3
Dim mark As Single
Private Sub Compute_Click()
'Examination Marks
mark = mrk.Text
Select Case mark
Case Is >= 85
comment.Caption = "Excellence"
Case Is >= 70
comment.Caption = "Good"
Case Is >= 60
comment.Caption = "Above Average"
Case Is >= 50
comment.Caption = "Average"
Case Else
comment.Caption = "Need to work harder"
End Select
NB: * Note we use the keyword Is here to impose the conditions. This is generally used for
numeric data.
ii) Do - while
While – wend
While – wend first checks whether the condition is true. The statements will be executed as long
as the condition remains true.
50
VISUAL BASIC PROGRAMMING
WHILE <condition>
Statements
WEND
Example
Properties
Code
i=i+1
51
VISUAL BASIC PROGRAMMING
End Sub
DO – WHILE
Do –loop executes a block of statements as long as the condition is true. If the expression is false
the program continues to the statement following the loop statement and that will be executed
DO WHILE <condition>
Statements
LOOP
Properties
d = Text1.Text
position = 1
words = words + 1
52
VISUAL BASIC PROGRAMMING
Loop
Instr() function finds space in the text and returns positive number. When no more spaces, it
returns 0 and instr(start point, line of text to be counted, the parameter to count i.e. space)
Example .1
Example:
(a) For counter=1 to 10
display.Text=counter
Next
(b) For counter=1 to 1000 step 10
counter=counter+1
Next
Example6: Write a program to find the summation of undetermined number of positive numbers
such that the program will be stopped when we enter negative number.
Sol:
Dim x, sum As Single
Private Sub command1_click()
sum = 0
x = Val(InputBox("enter x", "summation"))
Do While x >= 0
sum = sum + x
x = Val(InputBox("enter x", "summation "))
Loop
MsgBox (CStr(sum))
End Sub
54
VISUAL BASIC PROGRAMMING
Example7: Write a program to find the summation of the numbers from 5 to 15.
Sol:
Dim I, sum as integer
Private Sub command1_click ()
sum = 0
For i = 5 to 15
Sum = sum + i
Next i
Label1.caption = "sum ="&cstr(sum)
End Sub
Example8: Write a program to find the summation of 10 numbers.
Sol:
Dim i as integer
Dim x, sum as double
Private Sub command1_click ()
sum = 0
For i = 1 to 10
x = val(inputbox ("enter number"))
Sum = sum + x
Next i
Label1.caption = "sum="& cstr(sum)
End Sub
55
VISUAL BASIC PROGRAMMING
Running stage:
For example if we entered the numbers: 1, 5, -1, 3, 2, 0, -1, 3, 0, -4 then sum=8
56
VISUAL BASIC PROGRAMMING
i=i+5
Loop
End Sub
Example11: write a program to find the average of numbers that dividable by 3 (without
remainder) from 3 to 99.
Sol:
Dim I, n, sum as integer
Dim av as Double
Private Sub command1_click ()
i=3:n=0
sum = 0
Do while i <= 99
Sum = sum + i
i=i+3
n=n+1
Loop
Av = sum/n
Print "av ="; av
End Sub
Example12: write a program to print (welcome) ten times, the first one with the ordinary size and
color. Then make the color changed and the size bigger at each
time.
Sol:
Dim i As Integer
Private Sub Command1_Click()
Print "welcome"
For i = 1 To 9
FontSize = 10 + i
ForeColor = QBColor(i)
Print "welcome"
57
VISUAL BASIC PROGRAMMING
Next i
End Sub
Series:
To compute the value of series, we use suitable loop statements according to the boundaries (limits)
of each series.
Example13: Find
Sum=1+x+x2+x3+…+xn , where x is an integer.
Sol:
Dim I, n, x, sum as integer
Private Sub command1_click ()
sum = 1
n=val(text1.text)
x=val(text2.text)
For i = 1 To n
Sum = sum +x^i
Next i
Text3.text=sum
End Sub
58
VISUAL BASIC PROGRAMMING
The nested loops are the loops that are placed inside each other. The most inner loop will be
executed first, then the outer ones. These loops should neither intersect, nor have the same index.
As follows:
For i = 1 To n
For j = 1 To m
Statements
Next j
Next i
59
VISUAL BASIC PROGRAMMING
60
VISUAL BASIC PROGRAMMING
The general format of a function is functionName(arguments) where arguments are values that are
passed on to the functions.
We are going to learn two very basic but useful internal functions, i.e. the MsgBox( ) and InputBox
( ) functions.
The objective of MsgBox is to produce a pop-up message box and prompt the user to click on a
command button before he /she can continues. This message box format is as follows:
yourMsg=MsgBox(Prompt, Style Value, T itle)
The first argument, Prompt, will display the message in the message box. The Style Value will
determine what type of command buttons appear on the message box, please refer Table 7.1 for
types of command button displayed. The Tit le argument will display the title of the message board.
We can use named constant in place of integers for the second argument to make the programs more
readable. In fact, VB6 will automatically shows up a list of names constant where you can select
one of them.
example: yourMsg=MsgBox( "Click OK to Proceed", 1, "Startup Menu")
61
VISUAL BASIC PROGRAMMING
i. The Interface:
You draw three command buttons and a label as shown in Figure 7.1
62
VISUAL BASIC PROGRAMMING
To make the message box looks more sophisticated, you can add an icon besides the message.
There are four types of icons available in VB as shown in Table 7.3
63
VISUAL BASIC PROGRAMMING
You could draw the same Interface as in example 10.1 but modify the codes as follows:
Private Sub test2_Click()
Dim testMsg2 As Integer
testMsg2 = MsgBox("Click to Test", vbYesNoCancel + vbExclamation, "Test Message")
If testMsg2 = 6 Then
display2.Caption = "Testing successful"
ElseIf testMsg2 = 7 Then
display2.Caption = "Are you sure?"
Else
display2.Caption = "Testing fail"
End If
End Sub
64
VISUAL BASIC PROGRAMMING
An InputBox( ) function will display a message box where the user can enter a value or a message
in the form of text. The format is
myMessage=InputBox(Prompt, Tit le, default_text, x-posit ion, y-posit ion)
myMessage is a variant data type but typically it is declared as string, which accept the message
input by the users. The arguments are explained as follows:
Prompt: The message displayed normally as a question asked.
Title: The title of the Input Box.
default-text: The default text that appears in the input field where users can use it as his
intended input or he may change to the message he wish to key in.
x-position and y-posit ion - the posit ion or the coordinate of the input box.
Example
i. The Interface
End Sub
When a user click the OK button, the input box as shown in Figure 10.5 will appear. After user
entering the message and click OK, the message will be displayed on the caption, if he click Cancel,
"No message" will be displayed.
Visual Basic provides number of built in functions. The Val function is one of it. Val function
converts the text data into a numeric value.
Val(Expression to Convert)
The Str is the function that converts a number to a string while the Val function converts a string to
a number. The two functions are important when we need to perform mathematical operations.
Example2: Write a program to add and subtract two integer numbers after putting a suitable design.
Use message box for outputting.
66
VISUAL BASIC PROGRAMMING
Code:
Dim x, y, z As Integer
x = Val(Text1.Text)
y = Val(Text2.Text)
z=x+y
End Sub
x = Val(Text1.Text)
y = Val(Text2.Text)
z=x-y
End Sub
67
VISUAL BASIC PROGRAMMING
Running stage
Enter two values in text1 and text2. When click on command (+) or (-) the addition or subtraction
result appears in message box.
The Sqr function returns the square root of a number. This function takes a Double type argument
and returns a double implying that you can work with large numbers using the Sqr function.
Example:
Print Sqr(9)
Output: 3
The Ucase function converts all the characters of a string to capital letters.
Syntax: UCase(string)
68
VISUAL BASIC PROGRAMMING
The Lcase function converts all the characters of a string to small letters.
Syntax: LCase(string)
Synthax: Len(string)
69
VISUAL BASIC PROGRAMMING
Definition
Menu bar
A row of menu titles typically located at the top of the application's window on screen. The File
menu is often the first menu title on the menu bar. See menu bar:
Menu panel
The formal name for the list of options that is displayed when you select a menu from the menu
bar. See meu pane.
Pull-down menu
Also called a "drop-down menu" or "pop-down menu," the common type of menu used with a
graphical user interface (GUI). Clicking a menu title causes the menu items to appear to drop down
70
VISUAL BASIC PROGRAMMING
from that position and be displayed. Options are selected either by clicking the menu item or by
continuing to hold the mouse button down and letting go when the item is highlighted.
VB programmers can create menus by first selecting the form that will host the menu and then
using the VB Menu Editor.
The Menu Editor is available only when a form is being designed. It is located on the Tools
menu in VB6.
The first step in creating a menu is to enter the menu item's caption. The caption can incorporate
the ampersand (&) for an access key designation, also known as an accelerator key. This enables
the user to see an underlined letter in the menu and use the Alt key along with the accelerator
key.
After the caption of the menu item has been set, the menu requires an object name for
programmatic reference. The menu names can be any valid object name. Naming conventions are
71
VISUAL BASIC PROGRAMMING
preferred to allow for easier reading of source code and quick identification of objects Menus use
the three-letter prefix "mnu" before the selected name.
You can implement a separator bar in a menu (separator bar is: a horizontal line that visually
defines the boundary between two groups of menu items) by putting a single dash (-) as the
entire caption for a menu item. This item then becomes the separator bar on the runtime menu. You
must remember that even separator items in a menu must each have their own unique Name
property.
Menu items can also have their appearance properties set at design time through the Menu
Editor. Properties such as Checked, Enabled, Visible, WindowList, and a shortcut key
can all be specified.
In addition a drop-down list of possible shortcut key combinations allows the programmer to assign
a shortcut key to this particular menu item. Unlike the accelerator or access key mentioned above,
the shortcut key can be pressed by the user without its corresponding menu item being visible.
Windows automatically displays the shortcut key assignment when the menu item is displayed. All
of these properties are also available at runtime except for the shortcut key.
To change the desired property of the menu object, just use the object name followed by the
property name and the value. Examples of such runtime changes are given in the following
section.
A menu control has a single event procedure: the Click event procedure. The Click event
procedure is the place where you write or call the code that you want to execute when the user
chooses the menu item.
E.g.
End
End sub
You can access a menu control's Click event procedure by single clicking the menu item from the
design time copy of the menu.
The submenu refers to the level in the menu structure the items will appear. An object may be a top-
level menu item, sub-menu item, or a sub–sub-menu item.
Sub-level menu items have four small dots (….) preceding the menu caption; sub– sub-menu items
have eight dots (………). The menu items and sub menu can also be reorganized according to
position in the menu.
73
VISUAL BASIC PROGRAMMING
To control the level and position of the menu item being entered, just use the four direction arrows
in the Menu Editor. The up and down arrows reposition menu items for order. The left and right
arrows allow menu items to be top-level, sub-level or sub–sub-level.
Aim: to create a menu of Edit and do the operations of Cut, Copy, Paste.
Properties
Clipboard.SetText Screen.ActiveControl.SelText
End Sub
Clipboard.SetText Screen.ActiveControl.SelText
Screen.ActiveControl.SelText = Clipboard.GetText()
74
VISUAL BASIC PROGRAMMING
End Sub
Seltext means selected text in the active control will be set as text for copying or cutting and it
is sent to the clip board. The text in the clipboard will be put on the active control of the
screen. The active control here is the text box control.
75
VISUAL BASIC PROGRAMMING
This is the most important part of visual basic whereby we are going to produce a back
Database
A database is a collection of records that can be manipulated with ease. The manipulation
of data is done by structured query language (SQL).the SQL is a simple English like language that
user’s can use to request a database for details, Often abbreviated as DB. A collection of
information organized in such a way that a computer program can quickly select desired pieces
of data. You can think of a database as an electronic filing system.
Traditional databases are organized by fields, records, and files. A field is a single piece of
information; a record is one complete set of fields; and 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.
Increasingly, the term database is used as shorthand for database management system. In
Visual Basic it is incorporated in the form of Visual Data Manger.
76
VISUAL BASIC PROGRAMMING
For designing database from visual basic u choose Add-Ins menu Visual Data Manger.
It will ask for the name of the database .give name (user defined).for example I m going to give
as electricity bill
77
VISUAL BASIC PROGRAMMING
Next
In this right click on the properties you will be getting a menu, in that select a new table.
78
VISUAL BASIC PROGRAMMING
Include all the fields that is necessary (for ex here customer’s name, bill no, price/unit, unit,
total amount) and then click build the table. When you want to include values to the records
then double click on the table name and it will open for input of data and give values and then
click update. When once giving values is finished then click close.
Note down the path of the database where you have stored. Now designing the database has
been finished.
79
79
VISUAL BASIC PROGRAMMING
Data control
Data control provides access to databases through controls on your form. It makes the job
Example
Properties
Connecting database and displaying corresponding fields to the form do the following
80
80
VISUAL BASIC PROGRAMMING
Text3 Data source Data1
Data field Unit
Text4 Data source Data1
Data field Price per unit
Text5 Data source Data1
Data field Total amount
Now run your application it will show the records in the database. You can navigate
between the records.
Output
Example
81
81
VISUAL BASIC PROGRAMMING
Aim: To have the information of employees
Properties:
Code:
82
82
VISUAL BASIC PROGRAMMING
Private Sub Command1_Click()
Data1.Recordset.MoveFirst
End Sub
End Sub
End Sub
End Sub
End Sub
83
83
VISUAL BASIC PROGRAMMING
End Sub
End Sub
End Sub
84
84
VISUAL BASIC PROGRAMMING
85
85
VISUAL BASIC PROGRAMMING
ADODC
In the early days of computing, dumb terminals were wired to powerful mainframe computers.
The centralized Information Services (IS) department of a company ran the computing show.
The mainframe gurus told us what we could and could not do. Then in
August of 1981, the first IBM personal computer was released and the world changed. Control
was eventually wrested from the centralized IS department at companies and flowed to the
every individual with a personal computer.
Each personal computer had its own CPU and hard drive to run programs and store data.
Centralized computing for many day to day activities disintegrated and each person with a
personal computer took individual control if their data destiny. But there were problems too. For
example, lots of individual computers sitting on people’s desks, and all wanted to share
information and common data. Out of the many desktop solutions to this need to access data by
distributed computing stations was Data Access Objects (DAO).
Now, with VB6.0, a brand new Jet database engine 3.51 just made this solution stronger. In fact,
Jet 3.51 is faster and more robust than Jet 3.5 that shipped with VB 5.0. Microsoft wanted to
enhance a proven, strong database access solution and, when developing desktop database
solutions using .mdb or ISAM files, Microsoft says the combination of Jet and DAO is definitely
the way to go. Microsoft has upgraded DAO and will continue to support this approach for the
foreseeable future. And don’t forget, DAO is the most popular desktop database access method
around applications using DAO is tremendous.
86
86
VISUAL BASIC PROGRAMMING
As seen two needs of modern business rapidly emerge that require a new and more
sophisticated approach to gathering data.
The first need is that of accessing legacy data - that is, information that is stored around
the business enterprise in disparate forms in various types of computers.
The second need is that of accessing non-relational data.
While .mdb databases (native to the Access database system) are easy, there are times when
programmers need to get data from other desktop sources. For example, we might need to read
or write data from dBASE, Paradox, FoxPro, or other databases. We might also need to retrieve
information from Excel or Lotus spreadsheets, or even text files. If you take a look at the intrinsic
(built-in) data control in VB 6.0, you will notice that there are several additional data sources
that the control can talk to in addition to its native Access.
87
87
VISUAL BASIC PROGRAMMING
The real benefit of connecting to one of the external ISAM (Indexed Sequential Access Method)
file types listed in the connect property of the data control is that we can work on the data - as
is - without changing its structure. We can leave the data where it is and use VB6.0 to connect
with the various data source types. So any applications that created these files can continue to
operate unchanged. We just go in and read or write data to and from these sources.
Microsoft’s standard for providing data access to various data sources is Open Database
Connectivity (ODBC). Essentially, this is a SQL approach to retrieving data. ODBC is supported by
all sorts of software applications from spreadsheets to word processors to databases. ODBC
provides database interoperability, which really means that it gives us methods by which
data can be exchanged among different databases.
88
88
VISUAL BASIC PROGRAMMING
Using ODBC Direct allows you to deploy client/server applications using Microsoft Access
without using Microsoft Jet as the middle layer. ODBC Direct is an interface directly to ODBC. So
in most cases, it is faster.
If your application is hitting a Microsoft Jet .mdb or any other file-share databases it supports,
you should use the Microsoft Jet path. This is because ODBC Direct was created
specifically to access remote data. You should also use Jet if you want to join data in tables
stored in different back-ends such as Oracle and SQL Server. You would need Jet in this case
because it provides heterogeneous joins. You can create tables using ODBC Direct by executing
SQL statements, but it’s more convenient to use the Jet TableDef object.
89
89
VISUAL BASIC PROGRAMMING
With the ADO data control, we can be connected to more databases of different types. Depend
upon the code it can be accessed from the same interface.
1. Start a new project. Now go into the Project | References dialog and add the Microsoft
ActiveX Data Objects 2.0 Library and ActiveX Data Objects Record set 2.0 Library references to
your project. Now VB 6.0 knows about the ADO components we want to use.
90
90
VISUAL BASIC PROGRAMMING
Then right click on your tool palette and select Components. Select the Microsoft ADO Data
Control 6.0 (OLEDB):
91
91
VISUAL BASIC PROGRAMMING
Click OK. This will add an ADO data control to your palette.
2. Name the default form in the project frmADO. Draw an ADO Data Control (ADODC) on the
form. Next, draw a textbox and label as shown on the form as well. We are going to create a
simple bound text box program like our first data control program. And we will use the label
to show where we are in the record set.
92
92
VISUAL BASIC PROGRAMMING
In order to hook up the ADODC to ourBiblio.mdb database, we must first set some properties.
Right click on the ADODC and select ADODC Properties. This will bring up a Property Page dialog
box for the control. The first thing we must do is tell the control some important information.
Unlike the singular Database Name property we need to set on the standard data control, the
ADO data control requires a connection string. The connection string consists of the specific OLE
DB provider to use, as well as the data source we want to access. The connection string is the
critical piece of information the ADODC control needs to find the data source.
Since setting up the Connection String must contain just about every piece of information
required connecting to our data source, this comes in very handy indeed! Recall that the
connection string needs to know things like the location and name of the database, any
passwords that might be required, and the OLE DB data provider.
93
93
VISUAL BASIC PROGRAMMING
Click the Build button and let’s step through the process.
We are presented with another set of property pages for the Data Link. Notice the list of OLE DB
Providers that are shipped with VB6.0. If we wanted to connect to a generic ODBC source, we
have a provider for ODBC Drivers. Notice that we have providers for Oracle and SQL Server. And
as time goes on, all of the major database providers will ship their own OLE DB providers.
94
94
VISUAL BASIC PROGRAMMING
Click the Next >> button. This brings up the Connection tab. Here is where we must tell VB the
location and name of the database we will be using. Click the button with the ellipsis and locate
the usual\BegDB\Biblio.mdb database. Since the database does not require a password, don’t
change the entries for logging on to the database.
95
95
VISUAL BASIC PROGRAMMING
It is always a good idea to use the Test Connection option. This way, if there was something
wrong with the location or name of the database, we would get an error advising us of this.
Let’s say that you entered the name of the database but forgot to add the .mdb extension. By
testing the Data Link, we would know immediately:
96
96
VISUAL BASIC PROGRAMMING
We can then correct the error in the name and location of the database and press Test
There, that’s better. Now click the Advanced tab just to see what options are available to us.
Leave the default Share Deny None (if you needed to open the database in a read- only,
exclusive mode you would check the Read box)
97
97
VISUAL BASIC PROGRAMMING
Now click the All tab. Here you can see all of the information the Data Link property box
garnered for us:
This is all of the information that will be used to create the connection string. If you need to
modify any of the properties, simply click the Edit Value…button. Highlight any value you wish to
edit and press the Edit Value button. This will give you a chance to modify any value in the
connect string prior to clicking the OK button.
98
VISUAL BASIC PROGRAMMING
After the connection string is built, click OK to dismiss the property pages for the Data Link.
Now the control has the information it needs to connect to the data source. However, we
still need to inform the data control which table(s) we wish to access. Right click on the ADODC
data control again and select ADODC Properties. Notice that the connection string text box is
now filled in:
99
VISUAL BASIC PROGRAMMING
Click on the Record Source tab and click the drop down list box for the Command Type:
Select 2 – adCmdTable. Now the control knows we want to access records from a table directly.
If the DataSource is not known in advance, then adCmdUnknown is selected. If we were going to
issue a SQL command, the adCmdText would be selected, and the bottom text box, Command
Text (SQL), would become enabled. Finally, if we have stored, pre-compiled procedures, we
would choose adCmdStoredProc. This time, be sure to select choice2 - adCmdTable.
Now the control knows that we want to access records from a table, and it knows the name
of database from when we set up the Data Link. Now, the Table or Stored
Procedure Name list box becomes enabled. Click the list box and all of the tables in the database
are shown:
100
VISUAL BASIC PROGRAMMING
The data control now has the connection string built, and will be able to retrieve a recordset for
us from the data source. Double-click on the data control to bring up the code window. You
might notice that the Adodc1 data control has a few new event procedures.
3. Now that the ADODC data control has been set up, let’s bind the Text1 textbox. Bring up the
property dialog box forText1. Set the DataSource property to Adodc1.
101
VISUAL BASIC PROGRAMMING
Now click the drop down box for the DataField. Notice that just like the DAO data control; all of
the valid fields are displayed:
Go ahead and run the program. You can see that it works as follows
102
VISUAL BASIC PROGRAMMING
To the user, there is absolutely no difference between the intrinsic data control and our new
ADO data control.
Data report
103
VISUAL BASIC PROGRAMMING
Select data project.
Double click on the data environment1 object in the project explorer to open the
data environment window.
Right click on the data environment1 and from the shortcut menu, select
add command.
104
VISUAL BASIC PROGRAMMING
Right click on the connection1 object, and from the short cut menu, select
properties to open the data link properties window. Specify the driver in the provider.
Specify the database to which you want to connect, in the connections tab.
Click the test connection button to make sure the connection works.
105
VISUAL BASIC PROGRAMMING
To retrieve all the records from the database, follow these steps
In the database object, select table and in the object name box, select name of the
table you want.
106
VISUAL BASIC PROGRAMMING
107
VISUAL BASIC PROGRAMMING
108
VISUAL BASIC PROGRAMMING
The template which is shown below contains a report, which is subdivided into
header, section, footer.
Header – what are the headings of the report you want put it there.
Section - contains information’s which are retrieved from the database.
Footer – contains the information for the end of the report.
In the page header right click, from the short cut menu select insert control and in
that click label control. Write the name of the report.
In the detail right click, from the short cut menu select insert control and in that
click label control. Write the field name
Go to the data environment window resize it and bring the fields from data
environment window to report’s detail section. Likewise you continue until all
fields are finished.
109
VISUAL BASIC PROGRAMMING
In the page footer right click insert control and from the sub menu select label
control. Write its caption as end of report.
Run the data project, the output will be in format as follows
110
VISUAL BASIC PROGRAMMING
111