Software Development With Visual Basic B.com Ca
Software Development With Visual Basic B.com Ca
III B.COM CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
1
SEMESTER – V
PAPER - SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
UNIT – I:
Introduction to Visual Basic: Getting Started - Working with Visual Basic – The Initial
Visual Basic Screen –The SDI Environment – Toolbars - The Toolbox and Custom Controls and
Components – Starting a New Project – The Properties Window – Common Form Properties – Scale
Properties – Colour Properties.
UNIT – II:
Building the User Interface: Toolbox – Creating Controls – Name Property - Properties of
Command Buttons - Image Controls - Text Boxes – Labels – Message Boxes - Grid. Anatomy of a
VB Application – The Code Window – Statement in Visual Basic – Variables – Data types – Working
with Variables – Constants – Input-Boxes.
UNIT- III:
Display Information on a Form - The Format Function - Picture Boxes – Rich Text Boxes –
The Printer Object - Determinate Loops - Indeterminate Loops – Making Decisions – Select Cases –
Nested If-Then – The GOTO – String Functions – Numeric Functions – Date and Time functions –
Financial Functions
UNIT - IV:
Function Procedures – Sub Procedures – Advanced Uses of Procedures and Functions – Lists:
One–Dimensional Arrays – Arrays with more than One–Dimension - Using Lists and Arrays with
Functions and Procedures – The with Statement - Enums – Control Arrays – List and Combo Boxes –
Menus – Menu Editor – MDI Forms.
UNIT – V:
Introduction to Database - Working with Data Control: The Data Control - The Bound
Control – Coding – Data Access Object: Functions of the Jet Database Engine – The DAO Object
Model - Crystal and Data Reports: Crystal Report - Data Report – Creating Multiple Reports
TEXT BOOKS:
1. ―Visual Basic 7 From the Group UP‖, Gray Cornell, Tata McGraw Hill Edition (Unit-1 to Unit –
IV)
2. ―Programming With Visual Basic 6.0‖, Mohammed Azam, 2nd Edition. (Unit – V
2
DEPARTMENT OF COMPUTER SCIENCE
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
CLASS: III B.COM[CA] UNIT I
• Microsoft intended Visual Basic to be relatively easy to learn and use. Visual Basic was derived
from BASIC and enables the rapid application development (RAD) of graphical user interface
(GUI) applications, access to databases using Data Access Objects, Remote Data Objects,
or ActiveX Data Objects, and creation of ActiveX controls and objects.
• A programmer can create an application using the components provided by the Visual Basic
program itself. Over time the community of programmers developed third-party
components. Programs written in Visual Basic can also use the Windows API, which requires
external function declarations.
• Since VB defines default attributes and actions for the components, a programmer can develop a
simple program without writing much code.
• Programs built with earlier versions suffered performance problems, but faster computers and
native code compilation has made this less of an issue.
3
▪ After a while, new project window is opened
▪ There are 3 tabs in new project window
• New – to create a new project window
• Recent- it will display the existing project that are used recently
• Existing- it will display the existing projects
▪
▪
▪
▪
▪ In it choose standard.exe from the new tab. Now a window is opened. It contains form
▪ Place the controls on the form by double clicking the control
▪ Change the properties of the window using properties window. It will open by pressing f4
(or) click view->properties
4
2) Write code to respond to user input/events
▪ We must write code in response to user input or event in the code window
▪ To go to the code window press F7 (or) choose view code->view menu
▪ A code window will open which contains two drop-down list that contains (i) controls
(ii)events for that controls
▪ A framework will appear while we click the control & within it we enter our own code
Private Sub Form_Load()
End Sub
▪ Private->means that the variable & code can be used only by that function
▪ Sub->means subroutine (or)function
▪ End Sub-> is the end of sub routine
eg: Private Sub Form_Load()
Text1.Text=”Hai”
End Sub
Saving the Project
▪ After designing the interface we must save the project. For that goto File->SaveProject
▪ when we save the project it asked (i)a name for the form file(.frm) (ii)and a name for the
project(.vbp)
5
save your form and project
Design window
6
Code window
SDI Environment:
SDI stands for Single Document Interface. It is an interface design for handling documents
within a single application. SDI exists independently from others and thus is a stand-alone
window. SDI supports one interface means you can handle only one application at a time.
1. Choose tools / options.
2. Click on the advanced tab
3. Select the SDI development environment check box.
7
8
9
10
11
12
13
The toolbox and custom controls and components
• The toolbox is located at the left of the screen.
• It contains the controls you use to build the interface for your application.
• To add new components to your toolbox that are already registered with windows follow
the steps.
1. Choose project/components
2. From the dialog box that pops up
3. Choose which controls you want to add by clicking in the box that marks the
appropriate component
4. Then click ok
5. Now the component available in tool box and you make use of it.
14
COMMON FORM PROPERTIES:
1) Name:
This property is used only in code. It gives the name that we want to use to refer to
the form. The default value is “Form1”and so its value starts out the same as the default
value of the caption property.
2) Appearance:
Determines the form in three-dimensional. The default value is 1, the form will be in
three dimensional. If Change it to 0 then the form will appear flat.
3) Border style:
The default value, 2-sizable, allows the user to change size and shape of the form the
hot spots located on the boundary of the form.
Set the border style value to 0-None, and the application will show no border and
therefore no minimize and maximize, or control box buttons.
4) Control Box:
Changes to this property go into effect only when a user runs the application. As in
Microsoft Windows application, control boxes are located in the far left corner of the title
bar.
5) Enabled:
We don’t want change the Enabled property casually. If we set the enabled form
false, the form cannot respond to any events such as the user clicking on the form.
15
6) Font:
If we move the focus to this item and then double click on the three dots(ellipsis), we
will see a dialog box that looks something like this:
7) Left, Top:
These properties determine the distance between the left or top of the form and the
screen. Set the value of the top property to 0, and the form were designing is flush with the
top. Set the value of the life property to 0 ,and it will be flush with the left side of the
screen
8) Mouse Pointer, Mouse icon:
Mouse pointer is a useful property that lets we set the shape of the mouse pointer.
The default value is 0, but the pull-down list indicates there are 17 other values.
1. Set the Mouse pointer property
2. Pick the icon we want to be the custom mouse icon as the value of the Mouse
Icon property.
9) Start Up Position:
The neat property gives another way to decide on the initial position of our form at
run time. It is generally more precise than using the Form Layout Window.
10) Visible:
This is another property that is dangerous to change by mistake. Set the value of this
property to false, and the form will no longer be visible.
11) Window State:
This property determines how the form will look at run time. There are three
possible settings. A setting of 1 reduces the form to an icon, and a setting of 2 maximizes
16
the form. A setting of 0 is the normal default setting. The property is most often changed
in code.
SCALE PROPERTIES:
Visual Basic provides five properties that affect the scale used on a form.
1) Scale mode:
Scale mode allows changes the units in the form’s internal coordinate system.
There are seven other possibilities.
• own units value 0
• default tips
• graphics
• picture element
• inches
• millimeters
• centimeters
2) Scale height, Scale width:
Set up our own scale for the height and width of the form. Resetting the properties
has the side effect of setting value of the Scale mode property back to 0.
3) Scale left, Scale top:
This property describes what value Visual Basic uses for the left or top corner of
the form. The original value for each of these properties is 0.
COLOR PROPERTIES:
We can specify background color and foreground color for text and graphics in
the form.
1) The Backcolor and Forecolor Properties via the Color Palette:
• Open the Properties window and select Back Color:&H8000000F&.
• Click the down arrow in the setting box.
• This opens up a tabbed dialog box with two tabs.
17
• The system tab on the dialog box gives a list of the colors currently used by
Windows for its various elements.
• Click on the Palette tab, the color grid shown here pops up.
2) Working with the color palette:
• We can create our own colors by working with the color palette directly.
• Open the color palette by going to the View→color palette(Alt+V, L).
• The left of the palette, a dark box enclosed in a lighter box.
• The inner box displays the current foreground color an. The text box in the lower
left corner of the color palette displays the foreground
• The outer box displays the current background color and to change the
background color, click the outer box and select any of the colored boxes
displayed.
• To get back to the default colors specified in the windows control panel, click the
default command button at the right.
• We can create our own colors for the color palette. Each of the Blank boxes on
the bottom of the color palette represents a possible custom color.
• To make one, follow these steps:
✓ Click one of these blank boxes, and then click the Define color Command
button. This opens the define Color dialog box.
✓ Change the amount of red, green, or blue.
18
✓ Press the add color button to create the custom color or the close button to
cancel.
Making A Form Responsive:
Visual Basic objects can recognize many different events. If a user clicks an area on the
screen, we want to display a message. The user clicks a command button, we want to perform a
specific action, such as displaying an image.
1) The code window and writing a simple event procedure:
• Double clicking the form opens the code window (View→code window, F7).
• The two drop down list boxes in the top part of the screen.
• Click drop down in the right hand box, a list of all events of a form will be
display.
• Click drop down in left hand box in the code window, a list of the controls will be
display
19
• Gives a new event procedure template for the form_Click event procedure.
• Adds a dotted line between the form_load event and the click event.
• Moves the cursor to the blank line before End sub line in the click event
procedure template.
• Now press F5 to run the application. Move the mouse until the pointer is inside
the form and click once.
20
UNIT -II
BUILDING THE USER INTERFACE
THE TOOL BOX
The toolbox supplied with the default installation of Visual Basic. The toolbox is usually
located on the left of the Visual Basic screen, but it needs not be visible at all times.
View→Toolbox.
Tool box provides a set of tools that the user use at design time to place controls on a
form. By default 21 controls are available in the toolbox. They are
1. Text Box 9.HScroll Bar
2. Picture Box 10.VSroll Bar
3. Label Box 11.Timer
4. Option Button 12.Command Button
5. Frame 13.Check Box
6. List Box 14.Drive, Dir & File List Control
7. Combo Box 15.Image Control
8.Data Control 16. Line & Shape Controls
17. OLE
(1)TextBox:
• It is used to accept the user input in text format (or) to display the results. It is also called
as an Edit Field (or) Edit control. Users can edit the information at runtime (or) at design
time
(2)PictureBox
• It is used to display the picture. The picture may be jpeg (or) gif files. It clips the picture
if the control isn’t large enough to display the entire image
(3)Label Box
• It displays text which is not edit by the user
21
(4)Option Button
• This control is used to select only one option from multiple choices
(5)Frame
• This control allows the user to create a graphical (or) functional grouping of controls. To
group controls, first draw the frame after that draw controls inside the frame
(6)ListBox:
• It is used to display list of item for which user can choose anyone item. Limitation of this
control is that we cannot enter new item at run time
(7)Combo Box
• User can choose an item or enter new item in the textbox. New values can be added to the
existing data
(8)Data Control
• It is used to access the information from the data base
(9)HScrollBar
• It is a graphical tool for quickly navigating through a long list of items or a large amount of
information
(10)VScrollBar
22
• It is a graphical tool for quickly navigating through a long list of items or a large amount of
information
(11)Timer
• It is used to keep track of the number of minutes or hours
(12)Command Button
• The user can choose to carry out a command. When the user click on the button the
computer will perform the task associated with the button
(13)CheckBox
• it is used when the user can choose more than one choices
(16)Image Control
• It is used to display the pictures. We can stretch the picture to the size of the image control
23
• It is used to link our program to another object or program
Customizing Toolbar
It means that we can add some more controls. The steps to customize the toolbox is
• place the mouse on the tool box and click right mouse button
• choose components from the pop-up menu
• a window pops up which have controls
• click on the controls & push ok button, to add control on the toolbox
CREATING CONTROL:
• We can always get a control on a form by double clicking on its icon in the toolbox. The
control in its default size and shape in the middle of the form. This is certainly one way to
proceed.
• Many of the more sophisticated methods for using the tool box are similar to those used
in a paint program, such as Microsoft Paint, which comes with Windows. We can use a
combination of pointing, clicking, and dragging to manipulate the toolbox.
1. Move the mouse pointer to the tool we want to use and click. The Background of
the tool changes color when we have successfully selected it.
2. Move the mouse pointer to the form. Think of this as the paint area in which we
will draw the control. The mouse pointer has changed an arrow to a shape like a
crosshair.
3. Hold the mouse button down and drag the mouse to create the object. Drag the
mouse pointer, an outline of the control appears on the form.
• When we release the mouse button, the control has eight little boxes, called sizing
handles. We can use this handles to move and resize a control after we have create it.
The pointer control is automatically highlighted when we release the left mouse button.
1) Working with a Control Already on a Form:
Resizing an Existing control:
To changing the size of an existing command button at design time,
• Use the properties window to adjust the width and height properties
• Working with the sizing handles
24
The figure shows a command button with its eight sizing handles on an otherwise blank
form. Click inside the control by moving the mouse pointer to the control and clicking once.
When the sizing handles visible, we know the control is selected.
To resizing a control with the sizing handles by following these steps:
1. Move the mouse pointer to a sizing handle and click and hold down the left mouse
button.
2. Drag the mouse until the control is the size we want.
25
The steps for the dragging method to select multiple controls:
• Imagine a rectangle that surrounds only those controls we want to select. Move to one
corner of this imagined rectangle and click the left mouse button.
• Hold the left mouse button down and drag the dotted rectangle until it covers all the
controls we want to select. Then release the mouse button.
The dragging method of selecting multiple controls only works when the controls to be
moved can be placed in a rectangular “lasso” that excludes any other controls.
• Select each control by moving the mouse pointer to it and holding down the left
mouse button while pressing CTRL.
• Move the mouse pointer to any place outside the selected controls and click.
4) Locking controls:
By choosing Format→Lock Controls or the lock control tool from the toolbar. We can
prevent from inadvertently moving a properly positioned control. This item is toggle, choosing it
again frees up controls so that we can move them again.
5) Deleting controls:
1. Move the mouse pointer until it is inside the control, and click the left mouse button
to select it.
2. Press Del or open the Edit menu and choose the Delete option by pressing ALT+E, D.
THE NAME(Control Name) PROPERTY:
The property determines the name Visual Basic uses for the event procedure we write to
make the control respond to the user. An important as the Name property for a control is even
more important. While we can avoid using the Name of a form in our code because VB knows
the form that the code is attached to, ‘
Height=5000
Or
Me. Height=5000
Then visual basic will always assume mean to change the height of the current form. If
we want to change the height of a command button whose Name property is
MyCommandButton: MyCommandButton.Height=500
Picking meaningful names for our controls goes a long way toward making the inevitable
debugging of our application easier. For example:
26
Private Sub Command2_Click()
-
-
End Sub
Private Sub left_Click()
-
-
End Sub
Using a prefix to start the name of any control. For command buttons the prefix is cmd.
Private Sub cmdleft_Click()
-
-
End Sub
The setting use for a control’s name should be meaningful but not ridiculous; we have to
type the name of the controls in our code. The limits on a control name are the same as for
names:
• The name must begin with a letter
• After that, we can use any combination of letters, digits, and underscores
• No spaces are allowed in a control’s name
• The name cannot be longer than 40 characters.
PROPERTIES OF COMMAND BUTTON:
The properties window to customize the size and shape of blank forms, we can use it to
customize the controls. For example, if we don’t like the default value for a controls property,
simply open the properties window and change it.
1) The Caption Property:
The caption property of a form determines the name that shows in the title bar. Simply,
the caption property on a command button determines what the user sees on the face of the
button. Unlike the name property, the caption property can use just about any symbols available
in a single font.
27
Command button always start out with caption like Command1, Command2 reflecting
the default value of the Name Property. The number indicates the order in which the buttons
were created.
The name shown in the button will not fit inside the default size of a command button.
We want to change the caption property of the command button. Double click on the command
button icon to create the button in the center of the screen.
1. Move to the properties window
2. Go to the caption property by using the mouse or UP ARROW or DOWN ARROW keys.
2) Other useful properties for Command buttons:
• Visible: This property determines whether the command button is visible or not. Like
the visual property for forms, this property can only be set to true or false.
• Enabled: This property determines whether the button can respond to any event. If
we set the property to false, Visual Basic will not respond to any event concerning
that button.
• Font: This property controls which font is for the caption of the button. We can only
use one font at a time.
• Height, width: These properties define the height and width of the command button.
The units used are the ones set by the scale properties for the surrounding container.
• Left, Top: These properties determine the distance between the command button and
the left edge and top of the container respectively.
• Mouse pointer: Setting the mouse pointer to something different than the usual
arrow is a good way to give a user feedback that the user has moved the focus to the
command button.
28
• Disable picture, Down picture, Picture, Style: Visual Basic gives command buttons
the ability to display graphics. In addition to giving a command button a picture in its
normal state, we can set a special picture when the control is disabled or when it is
clicked.
End Sub
Private sub cmdbutton_GotFocus
29
End Sub
Access keys:
• Many Windows application allow pressing ALT and one other key, the access key, to
quickly activate a control or a menu item. For example, These access keys are underlined
in the caption of the control or name of the menu item.
• Visual Basic makes it easy to set up an access key for any object that has a caption
property. When we set the caption, place an (&)ampersand in front of the letter we want
to be the access key.
• Look at the following diagram
• Notice that the C in the caption underlined. When the application is running, we can
activate this button either by pressing the Alt+C combination or by clicking on the
button.
IMAGE CONTROLS:
o Image controls hold pictures. The toolbox icon for an image control is the sun
over a mountain.
o Image controls can be used to display icons or pictures created with a program
such a s Microsoft Paintbrush.
o They can also hold Windows Metafiles or Jpegs or Gifs. Jpeg format is also the
common format used by most Digital Cameras.
30
o Since image controls respond to the click event. Load picture into an image
control by resetting the value of the picture property.
o If we choose the picture property for the image control, this opens up a dialog box
that lets we choose what image file to load.
o We can also reset the picture property directly by copying an image from a
graphics program to the windows clipboard and then using the Copy command on
the Edit menu to paste the image into the image control.
o Visual basic will attach the graphics to the project when we save it.
Properties of Image controls:
• Many of the properties of image controls are similar to those for command buttons. We
can set the Left and Top properties to control where the image control is located relative
to its container.
• The border style property for an image control has only two possible settings: No border
(Setting=0) and Fixed single border (Setting=1).
• The most important property of an image control is seen Stretch property.
• This determines the image control adjusts to fit the picture or the picture adjusts to fit thre
control.
• If the stretch property is left at the default value of false, the control resies itself to fit the
picture. If we change it to true, the picture resizes to fit the control.
• Start a new project and place two large image controls on the form. Set the stretch
property to true for one of them and leave the default for the other.
TEXT BOXES:
Tex boxes are the primary method for accepting input and displaying output in Visual
Basic. In fact, too many lines of text to a form will often lead to a run-time error.
1) Standard properties of Text boxes:
There are around 50 properties for text boxes. The name property is used only for the
code we write.
31
2) Some Special Properties for Text boxes:
• Multi line: This property determines a text box can accept more than one line of text
when the user runs the application, and it is usually combined with resetting the value
of the Scrollbars property. The limit for a multi-line text boxes is approximately
32000 characters.
• Scroll Bars: This property determines whether a text box has horizontal or vertical
scrollbars. These are useful, because Visual basic allows to accept long or multiple
lines of data from a single text box, roughly 32000 characters is the limit for a multi-
line text box.
Value Meaning
0 This is the default value. The text box lacks both vertical and horizontal
scroll bars
1 The text box has horizontal scroll bars only(255 characters)
2 The text box has vertical scroll bars only.
3 The text box has both horizontal and vertical scroll bars.
• Border style: As with the image control, there are only two possible settings for the
Border style property for a text box. The default value is 1, which gives a single-width
border, called a fixed single. Change the value of this property to 0, the border
disappears.
• Maxlength: This property determines the maximum number of characters the text box
will accept. The default value is 0, which means there is no maximum other than the
32000 characters limit for multi-line text boxes.
• Password char The passwords char property lets we limit what the text box displays.
The convention is to use an asterisks (*) for the password character. Once we set this
property, all the user sees is a row of asterisks
• Event procedure for Text box:Text boxes can recognize 23 events. Events such as
GotFocus and LostFocus work exactly. Three others—Key down, Key up and Key press
are for monitoring exactly what the user types.
LABELS:
32
• Another common use is to display help information. The icon for a label is the bold,
capital letter A, and Microsoft’s suggested prefix for the name property of labels is lbl.
• Labels have 34 possible properties.
• Labels have a caption property that determines what they display.
• The caption property is originally set to be the same as default Name property: Label1 for
the first label on our form.
1) Useful properties for Labels:
• Alignment: The alignment property for a label has three possible settings. The usual
(default) value is 0, which means the text in the label is left justified. Set the value of
this property to 1, and the text inside the label will be right justified; set the value to
2; and the text is centered.
• Border style, Back style: The border style property has the same two possible
values as text boxes do. The difference is that the default value is 0, so labels do not
start out with a border. Sort the value to 1, and the label resembles a text box. This is
occasionally useful when our program displays results.
• Autosize, Word wrap: The default value for this property, set to false, and we need
to change it to true to take advantage of this neat feature. The word wrap property to
True, the label will grow in the vertical direction to encompass its contents, but the
horizontal size will stay the same. The words will be wrapped so that they are never
broken.
• Event Procedure for Labels :Labels respond to 18 events. They can respond to
clicking, double-clicking or the change event. The most common event procedures
for a label are mouse events. One problem is that labels do not respond to key events
or direct whether the user has shifted the focus.
NAVIGATING BETWEEN CONTROLS:
❖ Using the mouse is the most common way to move from control to control in a windows
application, but our application have to allow for using the TAB key as well. Tab order is
the term used in a windows application for the sequence of controls that pressing TAB
moves through.
33
❖ The first control create at design time is the one that receives the focus when the
application starts. If we press TAB once when the application is running, move to second
control. Disabled controls are skipped.
❖ It is possible to change the setting for the tab order via the properties window or by
writing code. The property need to set is the TabIndex property. If we set the value to 0
for a control, this control automatically becomes the first control in tab order, and all the
other controls move upward in tab order.
❖ If we change a control with a higher tab index, then only controls with larger tab index
are affected. If we create a control and set the Tab Index property at design time, the
settings for the TabIndex property are moved higher to make way for the new control.
We can also change the TabIndex property via code.
Assigning Access Keys for Text boxes:
• If the user presses the access key for a control, such a as label, that does not respond to
focus events, the focus moves to the next control that will accept it in tab order.
• This makes it easy to give an access key for a text box.
1. Crate a label for the text box
2. Set up the access key for the label
3. Then create the text box.
MESSAGE BOXES
Message boxes display information in a dialog box superimposed on the form. They wait
for the user to choose a button before returning to the application. Users cannot switch to another
form in our application as long as Visual Basic displaying a message box. Message boxes should
be used for short messages or give transient feedback. The simplest form of the message box
command:
Msgbox “The message goes in quotes “
Message box can hold a maximum of 1024 characters, and visual basic automatically
breaks the line at the right side of the dialog box.
34
The complete syntax for the Msgbox command:
Msgbox Message Inbox, TypeOfBox, TitilOfBox
Three different groups of built-in integer constants to specify the kind of message box.
Symbolic constants Value Meaning
VbOkonly 0 Display ok button only
VbOkCancel 1 Display ok nad cancel buttons
VbAbortRetryIgnore 2 Display Abort, retry, and ignore buttons
VbYesNoCancel 3 Display yes, no, cancel buttons
VbYesNo 4 Display yes and no button
VbRetryCancel 5 Display Retry and cancel buttons
VbCritical 16 Display Critical Message icon
VbQuestion 32 Display warning query icon
VbExclamation 48 Display Warning message icon
VbInformation 64 Display information message icon
35
We can combine this option by adding the constants are values together.
Msgbox “Example of buttons”, bOkCancel + vbExclamation + vbDefaultButton2, “Test Msg
box”
This box contains an exclamation mark icon with Ok and Cancel buttons, and the second
button, cancel would be the default button for this form. The title bar of the message box would
show Test Message box.
THE GRID
The grid is so important for accurately positioning controls, mastering it will help our
applications a finished, professional look. Tools→option(Alt + T,O), and then go to the general
page on the options dialog box .
• Show grid We can turn the grid on or off by changing the Show Grid Setting. The
defauolt setting is on. There is usually little reason to turn the grid off.
• Grid width, Grid Height boxes The width and Height text boxes let we set the distance
between grid marks. The default’s 120 twips. Change these both to 60 and the grid
becomes twice as fine.
• Align control to Grid The align controls to grid check box determines whether controls
automatically move to the next grid mark or whether they can be placed between grid
marks.
36
ANATOMY OF A VB APPLICATION:
CODE WINDOW:
Code window is used to make the control to perform the necessary operation. For performing
that operation we need to write the code. For each and every move we need to write the code.
The code statement in vb like
Private sub form1_load()
End sub
STATEMENTS IN VISUAL BASIC
• Statements in visual basic rarely use line numbers, and each statement generally occurs on its
own line.
• Lines are limited to 1023 characters but a statement can be extended to the next line by using the
underscore character (_) preceded by a space at the end of the line.
• However unless ends with underscore, pressing enter indicates to VB that the line is done. If we
use a line more character than can fit in the window, Visual basic scrolls the window towards the
right as needed.
• Finally, we combine statements on one line by placing a colon (: ) between the statements.
Eg:-
MsgBox “Welcome to VB”_
Vbokonly,”Test button”
COMMENTS:
Comment statements are statements that help to explain the code to later we identify. They are
not processed by visual basic and so thay won’tr make the cmpiled version of our code.
Ther are two ways to indicate the comment:-
i) Single quotation mark- not the backward apostrophe found below the tidle (~)but usually
found below the double quotation mark(“).
Private Sub Command1_Click()
‘Calculator
End sub
ii) If we want to add comments to the ends of the lines, it is easier to use the single quotation
mark because the Rem form requires a colon before it.
PrintForm :Rem written by shen
THE END STATEMENT
37
Visual Basic processes an End statement, the programs stops.If we developing a program, we are
dumped back into the development environment.The effect is exactly the same as chossing the end
option on the run menu.In a stand alone program, after the end statement, all windows opened by the
program are closed and the program is cleared from the memory.
Many professional programmer prefer to use only one end statement in their code.They place this
end statement in the Query Unload Event for the main form
Advantage:
• If we use the Query Unload Event to execute any code needed for cleaning up.
• To replace any End Statement in other places with an Unload Me Statement.This calls the
Query Unload Event for that form.
VARIABLES
✓ A variable is a placeholder in memory for storing a value. The value of the variable changed
during its run time.
DECLARING VARIABLES:
✓ The variables in VB are declared using the DIM statement. Before the variable is used the user
must be inform to the program that this particular word is a variable.
Syntax:
Dim Variable name [As type]
Example:
Dim x As Integer
Rules:
✓ The name of the variable must be the following:
o Must begin with an alphabet.
o Must not have an embedded period or a special character.
o Must not exceed 255 characters.
o Must be unique with in the same scope.
o Must not used reserved words in visual basic
Use capitals only at the beginning of the words that’s makes up the parts of it.(Eg InterestRate not
Interestrate).This convention is called mixed case variable names.
VARIABLE ASSIGNMENT STATEMENTS
Variable assignment statements means is copying information from a source to destination.
InterestRate=.05
The variable name always appears on the left of the equality sign, and the value appears on the
right. Visual Basic must be able to obtain a value from the right side of an assignment statement.
38
Area= .05* .5
SETTING PROPERTIES WITH CODE
1) Setting Properties of Objects at Design Time
• Each form and control has properties assigned to it by default when you start up a new project.
There are two ways to display the properties of an object. The first way is to click on the object
(form or control) in the form window.
• Then, click on the Properties Window or the Properties Window button in the tool bar. The
second way is to first click on the Properties Window. Then, select the object from the Object
box in the Properties Window. The drop-down box at the top of the Properties Window is the
Object box.
• It displays the name of each object in the application as well as its type. This display shows the
Form object. The Properties list is directly below this box. In this list, you can scroll through the
list of properties for the selected object.
• You may select a property by clicking on it. Properties can be changed by typing a new value or
choosing from a list of predefined settings (available as a drop down list). Properties can be
viewed in two ways: Alphabetic and Categorized. A very important property for each object is
its name. The name is used by Visual Basic to refer to a particular object in code.
39
• A convention has been established for naming Visual Basic objects. This convention is to use a
three letter prefix (depending on the object) followed by a name you assign.
Object Prefix Example
Form frm frmWatch
Command Button cmd, btn cmdExit, btnStart
Label lbl lblStart, lblEnd
Text Box txt txtTime, txtName
Menu mnu mnuExit, mnuSave
Check box chk chkChoice
• Object names can be up to 40 characters long, must start with a letter, must contain only letters,
numbers, and the underscore (_) character. Names are used in setting properties at run time and
also in establishing procedure names for object events.
2) Setting Properties at Run Time
You can also set or modify properties while your application is running. To do this, you
must write some code.
The code format is:
ObjectName.Property = NewValue
Such a format is referred to as dot notation. For example, to change the BackColor
property of a form name frmStart, we'd type:
frmStart.BackColor = BLUE
3) Names are Used in Object Events
• The names you assign to objects are used by Visual Basic to set up a framework of event-
driven procedures for you to add code to.
• The format for each of these subroutines (all object procedures in Visual Basic are
subroutines) is:
40
DEFAULT PROPERTIES :
Every visual basic object has a default property .When referring to the default property, to use the
property name.
Text1 = “This is new text:
To change the text property of a text box. Most Visual basic programmers avoid using the
default property because they feel it makes their code less readable.
BOOLEAN PROPERTIES
Properties that take only the value true or false are called Boolean properties. Thus Boolean
properties specify whether a command button is visible, is enabled, or is the default cancel or command
button. Boolean properties are commonly used, whenever we have an “on/off” situation.
A statement such as is an event procedure hides the command button by resetting the visible
property to be false.
Command1.Visible =False
The control stays hidden until visual basic process the statement
Command1.Visible =True
Eg:
The TAB key to skip a control while a program is running , change the Tabstop property to false.
Control.TabStop = False
DATATYPES:
❖ Each variable consists of name and a data type. It determines how the bits/bytes representing
values are stored in the computer’s memory. The VB consists of various data types. They are:
▪ String
▪ Integer
▪ Long (Long Integer)
▪ Single
▪ Double
▪ Currency
▪ Byte
▪ Boolean
▪ Date
▪ Object
▪ Variant
41
Data Type Suffix
Boolean None
Integer %
Long (Integer) &
Single (Floating) !
Double (Floating) #
Currency @
Date None
Object None
String $
Variant None
String:-
The string data type holds characters.A single character is a string or many.A variable holding a
string is called , naturally enough a string variable .One method of identifying variables of this type is to
place a dollar sign ($) at the end of the variable name :
Astringvariable$
String variable hold about 2 billion characters.
❖ This data type used for holding text or string values, declared by ‘variable-length string’ or ‘fixed
length string’. The default string variable is variable length.
Example:
Dim x As String *20 → Fixed-length string
Dim x As String → Variable-length string
❖ If you assign a string of fewer than 20 characters, the x will be padded with enough trailing
spaces to total 20 characters. If you assign a string that is too long, VB simply truncates the
characters. (Trim function used to remove spaces).
Integer:
❖ It is used to store whole numbers, and cannot be used for decimals or fractional part. It occupies
only two bytes of memory.
Long (Long Integer):
❖ It occupies twice as much space as the integer.
Single:
❖ This is equivalent to floating-point number. It occupies 4 bytes of memory space.
Double:
42
❖ It occupies Eight (8) bytes of memory space and should be used in applications where the
requirement of precision is very high.
Currency:
❖ It is used for holding monetary values. (The values related to item rates, payroll details and other
financial functions).
Byte:
❖ This data type occupies only one byte of memory. It holds the values from 0 to 255. It cannot
hold negative values or numbers larger than 255.
Boolean:
❖ This data type accepts only True or False values.
Date:
❖ This variable holds date and time data. It occupies eight bytes of memory.
Object Data Type:
❖ It is used to holding references to objects in VB. (forms, controls, procedures, record set). An
object variable refers to an object within the application or in some other application.
❖ The object may be textbox or a form or a database. A variable declared as an object is that can
subsequently be assigned (Using set statement) to refer to any actual object recognized by the
application. This data type occupies 4 bytes of storage.
Example:
Dim db As database
Set db= OpenDatabase(“C:\xyz\sample.mdb”)
Variant Data type:
❖ A variant data type is a variable that can change its type freely. It can accept text, numeric data or
byte etc. It always takes up 16 bytes, regardless of the type of data stored in it.
Example:
Dim x // Variant by default
x=”200” // String value (“100”)
x=x-70 // Numeric value (130)
❖ The variant data type contains the following three values:
▪ The Null Value
▪ The Empty Value
▪ The Error Value
The Null Value:
43
❖ It is used in database applications to indicate unknown or missing data. Assign null value with
“Null” keyword.
Example:
x=null
If IsNull(x) then
Debug.print…
End If
If variables are not implicitly or explicitly typed, they are assigned the variant type by default.
The variant data type is a special type used by Visual Basic that can contain numeric, string, or date data.
To implicitly type a variable, use the corresponding suffix shown above in the data type table.
For example,
TextValue$ = "This is a string"
creates a string variable,
while, Amount% = 300
creates an integer variable.
There are many advantages to explicitly typing variables. Primarily, we insure all computations
are properly done, mistyped variable names are easily spotted, and Visual Basic will take care of insuring
44
consistency in upper and lower case letters used in variable names. Because of these advantages, and
because it is good programming practice, we will explicitly type all variables.
To explicitly type a variable, you must first determine its scope. There are four
levels of scope:
Procedure level
Procedure level, static
Form and module level
Global level
Within a procedure, variables are declared using the Dim statement:
Dim MyInt as Integer
Dim MyDouble as Double
Dim MyString, YourString as String
Procedure level variables declared in this manner do not retain their value once a procedure
terminates. To make a procedure level variable retain its value upon exiting the procedure, replace the
Dim keyword with Static:
Static MyInt as Integer
Static MyDouble as Double
Form (module) level variables retain their value and are available to all procedures within that
form (module). Form (module) level variables are declared in the declarations part of the general object
in the form's (module's) code window. The Dim keyword is used:
Dim MyInt as Integer
Dim MyDate as Date
Global level variables retain their value and are available to all procedures within an application.
Module level variables are declared in the declarations part of the general object of a module's code
window. (It is advisable to keep all global variables in one module.) Use the Global keyword:
Global MyInt as Integer
Global MyDate as Date
-
End Sub
Hungarian Notation :-
Some programmers like to use the convention of adding a lower case prefix to variables to
indicate what type they are. This is usually called Hungarian Notation
Data Type Preffix
Boolean bin
45
Integer int
Long (Integer) ing
Single (Floating) sng
Double (Floating) dbl
Currency cur
String str
Variant vnt
DefInt A-Z Changes the default-all variable default to being integer variable
46
❖ It can be referenced in a procedure, a form and so on. The value of the variable in one procedure
cannot be accessed from another procedure. The value of a variable is local to that procedure.
❖ The procedure-level variables also known as local variables, declared using the Dim keyword.
The variable declared using the Dim keyword exists only as long as the procedure is executing.
❖ The values in local variables declared with static exist the entire time your application is running.
The variables are declared as static using the ‘static’ keyword.
Static x as Integer
❖ By declaring a variable using the public keyword, it will be available throughout the application.
The users use a variable without declaring it. The VB automatically creates a variable with that
name. This is called “Implicit Declaration”
❖ To enforce variable declarations before they are used, this can be done using the “Option
Explicit” statement. This statement used in the declaration section of a form, module etc.
Form-level variables
(Declared in general)
section of form with private key
Procedure 1
Local variables
Procedure 1
Local variables
47
Public y as Integer
Example:
Module 1:
Application
Public x As Integer
Form1:
Public y As Integer Module
Private Sub Command1_Click()
Form1 Form2
Dim x As Integer
x = 30
Module1.x = 10
Form1.y = 20
x = 30
MsgBox "module.x=" & Str(Module1.x)
MsgBox "form1.y=" & Str(Form1.y)
MsgBox "x=" & Str(x)
Form2.Show
End Sub
Form2:
Private Sub Form_Load()
MsgBox "module1.x=" & Str(Module1.x)
MsgBox "form1.y=" & Str(Form1.y)
MsgBox "x=" & Str(x)
End Sub
MORE ON STRINGS:
A String is simply a bunch of character surrounded by double quotes .To enter information into
text box ,Visual basic stores that information a s a string .Thus, even if have a text box meant to hold an
amount, it starts out as a string.
To concatenate two string ,use the ampersand symbol.
Ex:
Titles$=”Queen”
Name$=”Elizabeth”
First=Tiles$ & Name$
48
1) ASCII/ANSI codes
• The ASCII code associates with each number from 0 through 255 a displayable or control
character, although windows cannot display all 255 ASCII characters and uses a more limited set
of characters called the ANSI (American National Standard Institute) character set. The control
characters, and such special keys as TAB and a line feed, have a number less than 32.
• The value of the function Chr(n) is the string consisting of the character of ASCII value n.The
statement as :Print Chr(n)
• Visual basic also have a function that takes a string expression and returns the ASCII\ANSI value
of the first character : it is asc.If the string is empty, using this function generates a run time error.
2) Built in String Constants:-
Visual basic , one of the most important uses of the Chr function was to set up a newline code
for use in our programs..
A new lines are made up of two parts :-
i)a carriage return to bring the cursor tom the first column and the line feed to move it
tro the next line
ii) the Chr function , the new line code is
vbcrLf=Chr(13) & Chr(10)
3) Buil In Constants For Various Characters:-
CHARACTER SYMBOLIC CONSTANTS
49
The simplest operators carry out arithmetic operations. These operators in their order of
precedence are:
1) Operator Operation
^ Exponentiation
*/ Multiplication and division
\ Integer division (truncates)
Mod Modulus
+- Addition and subutraction
Parentheses around expressions can change precedence.
To concatentate two strings, use the & symbol or the + symbol:
lblTime.Caption = "The current time is" & Format(Now, “hh:mm”)
txtSample.Text = "Hook this “ + “to this”
2) Operator Comparison
There are six comparison operators in Visual Basic:
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
= Equal to
<> Not equal to
The result of a comparison operation is a Boolean value (True or False).
Logical Operator :
Logical operators follow arithmetic operators in precedence.We will use three logical operators.
• The Not operator simply negates an operand.
• The And operator returns a True if both operands are True. Else, it returns a False.
• The Or operator returns a True if either of its operands is True, else it returns a False.
CONSTANT:
Constants store values like variables, those values not changed throughout the execution of an
application.
Syntax:
[Public|Private] Const constantname [As type] =expression
50
1. Constantname should be a valid name.
2. As Type is the data type.
3. expression is the numeric or string value that has to be assigned to the constant.
Example:
Const pi=3.14
Scope of the Constant:
By declaring a constant in the declarations section of the form standard or class module.
❖ By declaring a constant using the public keyword, it is available throughout the application.
❖ Declaring a constant in a procedure will be available to that procedure only.
Circular reference:
Constant can be defined with reference to other constant.
Example:
Public Const A=B*1.414
Public Const B=A*2
The variables are constant available throughout the application. Visual Basic generate an
error. This methods of defining constants where each is defined in terms of the other is called circular
reference. To resolve this problem a word of caution on variables before we move to array.
1. A variable in the module cannot have the same name as any procedures or type defined in the module.
2. A local variable can have the same name as public procedures, types or variables defined in
other modules. If this variable is accessed form another module, it must be qualified with the module
name.
INPUT BOXES:-
Input boxes which are alternative way of getting information from the user.Now it is true that the
text boxes are the most common way for a visual basic application to accept data,but the inputbox
function display a modal dialog box on the screen-just like msgbox function.
• Advantage:-
Sometimes need to insist that a user supply some necessary data before letting them move
on in the application.
• Disadvantages:-
The dimension of the input box is fixed beforehand, and loses the flexibility that
textboxes provided.
51
this forms uses the name of the project in the title bar of the input box.
The Full Syntax For Inputbox Function Is
VaraibleName= InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile][,context])
• The prompt parameter is a string or string variable whose value vbisual basic displays in the
dialog box.It is limited to roughly 1,024 characters.
• The title parameter is optional and gives the caption used in the title bar.There is no default
value;if leave this out, the application name is used in the title bar.
• The default parameter is also optional .Its lets to display default text in the edit box where the
user will be entering information.If we omits this,the box starts out empty.
• Both xpos and ypos are integral numeric expression. Xpos is the distance in twips between the
left edge of the inputbox and the left edge of the screen. ypos is the distance in twips between the
top of the box and the top of the screen.
• The two parameters help file and context are used together when they help message attached to
the box.
52
UNIT -III
DISPLAY INFORMATION ON A FORM
THE FORMAT FUNCTION:
The Format function is a very powerful formatting function which can display the numeric
values in various forms.
There are two types of Format function, one of them is the built-in or predefined format while
another one can be defined by the users.
Example 3
Now, run the program and you will get an output like the figure below:
53
PICTURE BOXES
The picture box allows you to place graphics information on a form. It is best suited for
dynamic environments - for example, when doing animation.
Picture boxes lie in the top layer of the form display. They behave very much like small forms
within a form, possessing most of the same properties as a form.
1) Picture Box Properties:
• AutoSize If True, box adjusts its size to fit the displayed graphic.
• Font Sets the font size, style, and size of any printing done in the picture box.
• Picture Establishes the graphics file to display in the picture box.
2) Picture Box Events:
• Click Triggered when a picture box is clicked.
• DblClick Triggered when a picture box is double-clicked.
3) Picture Box Methods:
• Cls Clears the picture box.
• Print Prints information to the picture box.
Examples
picExample.Cls ' clears the box picExample
picExample.Print "a picture box" ' prints text string to picture box
4) Picture Box LoadPicture Procedure:
• An important function when using picture boxes is the LoadPicture procedure. It is used to
set the Picture property of a picture box at run-time.
Example
picExample.Picture = LoadPicture("c:\pix\sample.bmp")
5) Five types of graphics files can be loaded into a picture box:
• Bitmap An image represented by pixels and stored as a collection of bits in which each bit
corresponds to one pixel. Usually has a .bmp extension. Appears in original size.
• Icon A special type of bitmap file of maximum 32 x 32 size. Has a .ico extension. We’ll
create icon files in Class 5. Appears in original size.
54
• Metafile A file that stores an image as a collection of graphical objects (lines, circles,
polygons) rather than pixels. Metafiles preserve an image more accurately than bitmaps
when resized. Has a .wmf extension. Resizes itself to fit the picture box area.
• JPEG JPEG (Joint Photographic Experts Group) is a compressed bitmap format which
supports 8 and 24 bit color. It is popular on the Internet. Has a .jpg extension and scales
nicely.
• GIF GIF (Graphic Interchange Format) is a compressed bitmap format originally
developed by CompuServe. It supports up to 256 colors and is popular on the
• Internet. Has a .gif extension and scales nicely.
RICHTEXT BOXES
• The rich textbox control allows the user to enter and edit text, providing more advanced
formatting features than the conventional textbox control. You can use different fonts for
different text sections.
• You can even control indents, hanging indents, and bulleted paragraphs.This control is loaded by
selecting the Microsoft Rich Textbox Control from the Components dialog box.
• Possible uses for this control include:
Read and view large text files.
Implement a full-featured text editor into any applications.
1) Rich Textbox Properties, Events, and Methods:
Some unique properties of the rich textbox are:
• FileName Can be used to load the contents of a .txt or .rtf file into the control.
• SelFontName Set the font name for the selected text.
• SelFontSize Set the font size for the selected text.
• SelFontColor Set the font color for the selected text. Some unique methods of the rich
textbox are:
• LoadFile Open a file and load the contents into the control.
• SaveFile Save the control contents into a file.
Rich Textbox Example:
Put a rich textbox control on a form. Put a combo box on the form (we will use this to display the
fonts available for use). Use the following code in the Form_Load event:
Private Sub Form_Load()
55
Dim I As Integer
For I = 0 To Screen.FontCount - 1
Combo1.AddItem Screen.Fonts(I)
Next I
Other Visual Basic Topics 10-9
End Sub
PRINTER OBJECT
Any serious Visual Basic application will need to use the printer to provide the user with a hard
copy of any work done or results (text or graphics) obtained. Printing is one of the more complex
programming tasks within Visual Basic.
Visual Basic uses two primary approaches to printing text and graphics:
You can produce the output you want on a form and then print the entire form using the
PrintForm method.
You can send text and graphics to the Printer object and then print them using the NewPage and
EndDoc methods.
We’ll look at how to use each approach, examining advantages and disadvantages of both. All of these
techniques use the system default printer. You can also select a printer in Visual Basic, but we won’t look
at that here.
The PrintForm method sends a pixel-by-pixel image of the specified form to the printer. To
print, you first display the form as desired and via code invoke the command: PrintForm. This command
will print the entire form, using its selected dimensions, even if part of the form is not visible on the
screen. If a form contains graphics, they will be printed only if the form’s AutoRedraw property is True.
The PrintForm method is by far the easiest way to print from an application. But, graphics results
may be disappointing because they are reproduced in the resolution of the screen, not the printer. And
small forms are still small when printed.
PrintForm Example:
Start a new application. Put an image box on the form. Size it and set the Stretch property to
True. Set the Picture property to some picture (metafiles are best, you choose). Add a label box. Put
some formatted text in the box. My form looks like this:
56
Add this code to the Form_Click event:
Private Sub Form_Click()
PrintForm
End Sub
Printer Object Example:
In this example, we’ll first define a standard sheet of paper. Then, we’ll use the Line method to
draw a box, the Circle method to draw a circle, and the Print method to ‘draw’ some text. Start a new
application. We don’t need any controls on the form - all the printing is done in the Form_Click
procedure.
Private Sub Form_Click()
Printer.Scale (0, 0)-(850, 1100)
Printer.Line (100, 100)-(400, 300), , B
Printer.Circle (425, 550), 300
Printer.CurrentX = 100
Printer.CurrentY= 800
Printer.Print "This is some text."
Printer.EndDoc
End Sub
57
❖ In many situations we have to change the order of execution of statements based on certain
conditions.
❖ VB supports the following statement known as Control Statement or Decision Making Statements.
1. Simple-If
2. If-Else
3. Else-If Ladder
4. Nesting of If…Else
5. Select Case
Decision maker … If:
❖ The IF conditions… statement is used when the program has to perform an instruction or a block of
instructions depending upon the value of an expression.
❖ If the expression returns true then a set of statement(s) is executed.
Syntax:
If <condition> Then
<Statement>
End If
if
<condition
> True
Example:
Private Sub Command1_Click() false
If Val(Text1.Text) >=45 Then
Text2.Text = “PASS”
End If
End Sub
If-Else Statement:
❖ The If-Else statement is an extension of simple If statement.
❖ The condition is true, the statement followed by if are executed otherwise the else part statement is
executed.
Syntax:
If <condition> Then
<Statement-1>
Else
<Statement-2>
End I
58
Teste
xpress
ion?
Statement-x
Example:
Private Sub Command1_Click ()
If Val (Text1.Text) >=45 Then
Text2.Text = “PASS”
Else
Text2.Text = “FAIL”
End If
End Sub
Else-If Ladder:
❖ There is another way of putting ifs together when multi path decision are involved.
❖ A multi path decision is a chain of ifs in which the statement associated with each else if.
Syntax:
If <condition> Then
<Statement-1>
ElseIf <condition> Then
<Statement-2>
ElseIf<condition> Then
<Statement-3>
Else
<Statement-4>
End If
❖ The condition is evaluated from top to bottom.
❖ A true condition is found; the statement associated with it is executed.
❖ When all the conditions become false, then the final else statement will be executed.
59
Example:
Private Sub Command1_Click()
Dim marks As Integer
Dim Grade As String
marks = val(Text1.Text) / 2
If marks > 79 Then
Grade = "Honours"
MsgBox Grade
ElseIf marks > 59 And marks <= 79 Then
Grade = "First"
MsgBox Grade
ElseIf marks > 49 And marks <= 59 Then
Grade = "Second"
MsgBox Grade
Else
Grade = "Fail"
MsgBox Grade
End If
End Sub
Nesting of If-Else:
❖ When a series of decisions are involved, we have used more than one if…else statement in nested
form.
Syntax:
If <condition-1> Then
If <condition-2> Then
Statement-2
Else
Statement-3
End If
Else
Statement-4
End if
Statement-5
❖ If the condition-1 is false, the Statement-4 will be executed; otherwise it continues to perform the
second test.
❖ If the condition-2 is true, the Statement-2 will be executed; otherwise the Statement-3 will be
evaluated and then control transferred to the Statement-5.
Example:
If op = 1 Then
Text1.Text = a + Text1.Text
Else If op = 2 Then
Text1.Text = a - Text1.Text
Else If op = 3 Then
Text1.Text = a * Text1.Text
60
Else If op = 4 Then
If Text1.Text = 0 Then
Text1.Text = "error"
Else
Text1.Text = a / Text1.Text
End If
End If
End Sub
Select Case:
❖ This method is used when the program has to execute one of several groups of statement, depending
on the value of an expression.
Syntax:
Select Case test expression
[case expression list-1
statement-1]
[case expression list-2
statement-2]…..
[case Else
[else statements]
End Select
select
expression
e
Block 1
Block 2
Default Block
Statement -x
61
❖ The case else is executed when if no match is found between the test expression and the case
expression.
Example1:
Private Sub Command1_Click()
Dim a As Integer
a = val(Text1.Text) / 6
Select Case a
Case 1
MsgBox "good"
Case 2
MsgBox "not good"
Case Else
MsgBox "bad"
End Select
End Sub
LOOPING statement:
Do… Loop:
❖ A Do Loop construct is used to repeat the execution of a block of statements based on the condition.
❖ This loop construct evaluates a condition to determine whether or not to continue the execution.
Body of the
loop
Test
conditi
on
62
Dim i As Integer
Do While (i <= 10)
Print i
i=i+1
Loop
End Sub
Syntax-2:
Do
<Statements>
Loop While <Condition>
❖ Executes the statements first and then tests the condition.
❖ Loops at least once, then test the condition.
Example:
Private Sub Command2_Click()
Dim i As Integer
Do
Print i
i=i+1
Loop While (i <= 10)
End Sub
Syntax-3:
Do Until < Condition>
<Statements>
Loop
❖ Tests the condition first and if false, executes the statements.
❖ Loop till the condition is False.
Example:
Private Sub Command3_Click()
Dim i As Integer
Do Until (i > 10)
Print i
i=i+1
Loop
End Sub
While…end Loop:
❖ This Loop structure allows performing a series of steps based on a condition.
❖ The condition following the While clause is evaluated first. If it is true, the statements in the block are
executed.
❖ When the end clause is encountered, the control goes to the beginning of the loop, and the condition
is tested again.
❖ The block of code is executed as long as the condition following the While Clause evaluates to True.
Syntax:
While < condition>
< Statements>
end
63
Test
condition
?
Body of the
loop
Example:
Private Sub Command5_Click()
Dim i As Integer
While (i <= 10)
Print i
i=i+1
end
End Sub
For…Next Statement:
❖ This loop structure uses a counter that increases or decreases the value of a variable each time the
loop is
executed.
Syntax:
For <Counter> = <Start> to <End> [step value]
[Statements]
Next <Counter>
❖ Counter is the integer variable that is incremented.
❖ Start is the initial value of the counter.
❖ End is the stop value of the counter.
❖ Step Value is the increment or decrement value of counter.
Example1:
64
The GoTo Statement
• Another branching statement, and perhaps the most hated statement in programming, is the GoTo
statement. However, we will need this to do Run-Time error trapping. The format is GoTo Label,
where Label is a labeled line.
• Labeled lines are formed by typing the Label followed by a colon.
• When the code reaches the GoTo statement, program control transfers to the line
labeled Line10
STRING FUNCTIONS
Function: Len
Description: Returns a Long containing the length of the specified string
Len(string)
Syntax:
Where string is the string whose length (number of characters) is to be returned.
Example: 1. lngLen = Len("Visual Basic") ' lngLen = 12
Function: Mid$ (or Mid)
Description: Returns a substring containing a specified number of characters from a string.
Syntax: Mid$(string, start[, length])
start Required; Long. Character position in string at which the part to be taken
begins. If start is greater than the number of characters in string, Mid returns
a zero-length string ("").
65
Note: Mid$ can also be used on the left side of an assignment statement, where you
can replace a substring within a string.
In VB6, the Replace$ function was introduced, which can also be used to replace
characters within a string.
string Required. String expression from which the leftmost characters are returned.
length Required; Long. Numeric expression indicating how many characters to return.
If 0, a zero-length string ("") is returned. If greater than or equal to the number of
characters in string, the entire string is returned.
string Required. String expression from which the rightmost characters are returned.
length Required; Long. Numeric expression indicating how many characters to return.
If 0, a zero-length string ("") is returned. If greater than or equal to the number of
66
characters in string, the entire string is returned.
Description: Converts all lowercase letters in a string to uppercase. Any existing uppercase letters
and non-alpha characters remain unchanged.
Syntax: UCase$(string)
Description: Converts all uppercase letters in a string to lowercase. Any existing lowercase letters
and non-alpha characters remain unchanged.
Syntax: LCase$(string)
Function: Instr
Description: Returns a Long specifying the position of one string within another. The search starts
either at the first character position or at the position specified by the start argument,
and proceeds forward toward the end of the string (stopping when either string2 is
found or when the end of the string1 is reached).
Syntax: InStr([start,] string1, string2 [, compare])
start Optional. Numeric expression that sets the starting position for each search. If
omitted, search begins at the first character position. The start argument is required
if compare is specified.
67
search.
Examples: 1. lngPos = Instr("Visual Basic", "a")
2. ' lngPos = 5
3.
4. lngPos = Instr(6, "Visual Basic", "a")
5. ' lngPos = 9 (starting at position 6)
6.
7. lngPos = Instr("Visual Basic", "A")
8. ' lngPos = 0 (case-sensitive search)
9.
10. lngPos = Instr(1, "Visual Basic", "A", 1)
11. ' lngPos = 5 (case-insensitive search)
Function: InstrRev
Description: Returns a Long specifying the position of one string within another. The search starts
either at the last character position or at the position specified by the start argument,
and proceeds backward toward the beginning of the string (stopping when either
string2 is found or when the beginning of the string1 is reached).
Introduced in VB 6.
Syntax: InStrRev(string1, string2[, start, [, compare]])
start Optional. Numeric expression that sets the starting position for each search. If
omitted, search begins at the last character position.
68
8. ' lngPos = 0 (case-sensitive search)
9.
10. lngPos = InstrRev("Visual Basic", "A", , 1)
11. ' lngPos = 9 (case-insensitive search)
12. ' Note that this last example leaves a placeholder for the start argument
Description: Returns a string containing a repeating character string of the length specified.
character Required; Variant. This argument can either be a number from 0 to 255
(representing the ASCII character code* of the character to be repeated) or a
string expression whose first character is used to build the return string.
NUMERIC FUNCTIONS:
The common mathematical functions in Visual Basic are Rnd, Sqr, Int, Abs, Exp, Log, Sin,
Cos, Tan , Atn, Fix and Round.
(i) Rnd is very useful when we deal with the concept of chance and probability.
The Rnd function returns a random value between 0 and 1. In Example 1:
Randomize Timer
For x=1 to 10
Print Rnd
Next x
End Sub
69
a) Int is the function that converts a number into an integer by truncating its decimal part and the
resulting integer is the largest integer that is smaller than the number. For example, Int(2.4)=2, Int(4.8)=4,
Int(-4.6)= -5, Int(0.032)=0 and so on.
b) Sqr is the function that computes the square root of a number. For example, Sqr(4)=2, Sqr(9)=2 and
etc.
c) Abs is the function that returns the absolute value of a number. So Abs(-8) = 8 and Abs(8)= 8.
e) Fix and Int are the same if the number is a positive number as both truncate the decimal part of the
number and return an integer. However, when the number is negative, it will return the smallest integer
that is larger than the number. For example, Fix(-6.34)= -6 while Int(-6.34)=-7.
f) Round is the function that rounds up a number to a certain number of decimal places. The Format is
Round (n, m) which means to round a number n to m decimal places. For example, Round (7.2567, 2)
=7.26
g) Log is the function that returns the natural Logarithm of a number. For example,
Example 3
70
Randomize Timer
x = Round (Rnd * 7, 7)
Print n, x, Int(x), Fix(x), Round(x, 4)
n=n+1
Loop
End Sub
Function Description
DateValue Returns the date portion of a Date/Time value, with the time portion "zeroed out".
(Note: When the time portion of a date/time variable is "zeroed out", the time would
be interpreted as 12:00 AM.)
Example:
Dim dtmTest As Date
dtmTest = DateValue(Now)
At this point, the date portion of dtmTest is 8/31/2001, with a time portion of 0
(12:00 AM midnight).
71
TimeValue Returns the time portion of a Date/Time value, with the date portion "zeroed out".
(Note: When a date/time variable is "zeroed out", the date will actually be interpreted
as December 30, 1899.)
Example:
Dim dtmTest As Date
dtmTest = TimeValue(Now)
At this point, the time portion of dtmTest is 9:15:20 PM, with a date portion of 0
(12/30/1899).
Function Description
Weekday Returns a number from 1 to 7 indicating the day of the week for a given date, where
1 is Sunday and 7 is Saturday.
Example:
intDOW = Weekday(Now) ' intDOW = 6
Note:
When necessary to refer to a day of the week in code, VB has a set of built-in
constants that can be used instead of the hard-coded values 1 thru 7:
Constant Value
vbSunday 1
vbMonday 2
vbTuesday 3
vbWednesday 4
vbThursday 5
vbFriday 6
vbSaturday 7
72
Function Description
WeekdayName Returns a string containing the weekday name ("Sunday" thru "Saturday"), given a
numeric argument with the value 1 through 7.
Example:
strDOW = WeekdayName(6) ' strDOW = "Friday"
The WeekdayName function takes an optional, second argument (Boolean)
indicating whether or not to abbreviate the weekday name. By default, the second
argument is False, meaning do not abbreviate and return the full name. If True, the
first three letters of the weekday name will be returned:
Month Returns a number from 1 to 12 indicating the month portion of a given date.
Example:
intMonth = Month(Now) ' intMonth = 8
MonthName Returns a string containing the month name ("January" thru "December"), given a
numeric argument with the value 1 through 12.
Example:
strMoName = MonthName(8, True) ' strMoName = "Aug"
You can nest the Month function within the MonthName function to get the month
name for a given date:
Day Returns a number from 1 to 31 indicating the day portion of a given date.
Example:
intDay = Day(Now) ' intDay = 31
Year Returns a number from 100 to 9999 indicating the year portion of a given date.
Example:
intYear = Year(Now) ' intYear = 2001
73
Function Description
Hour Returns an integer specifying a whole number between 0 and 23 representing the hour
of the day.
Example:
Minute Returns an integer specifying a whole number between 0 and 59 representing the
minute of the hour.
Example:
Second Returns an integer specifying a whole number between 0 and 59 representing the
second of the minute.
Example:
To demonstrate the date functions shown thus far, set up a "Try It" project, and place the
following code in the cmdTryIt_Click event:
74
Print "Using MonthName (abbrev.):"; Tab(30); MonthName(Month(Now), True)
Print "Using Day:"; Tab(30); Day(Now)
Print "Using Year:"; Tab(30); Year(Now)
Print "Using Hour:"; Tab(30); Hour(Now)
Print "Using Minute:"; Tab(30); Minute(Now)
Print "Using Second:"; Tab(30); Second(Now)
End Sub
Run the project and click the "Try It" button. The output should look similar to the following:
The generic DatePart function returns an Integer containing the specified part of a given
date/time value. Thus, it incorporates the functionality of the Weekday, Month, Day, Year, Hour, Minute,
and Second functions. In addition, it can used to get the quarter of a given date (1 through 4) , the "Julian"
date (the day of the year from 1 to 366), and the week number (1 through 53).
Syntax:
Part Description
interval Required. String expression that is the interval of time you want to return.
The string expression can be any of the following:
75
Expression Description Possible Range of Values
"q" Quarter 1 to 4
"m" Month 1 to 12
"d" Day 1 to 31
"w" Weekday 1 to 7
"ww" Week 1 to 53
"h" Hour 0 to 23
"n" Minute 0 to 59
"s" Second 0 to 59
firstdayofweek Optional. A constant that specifies the first day of the week. If not specified, Sunday
is assumed.
firstweekofyear Optional. A constant that specifies the first week of the year. If not specified, the first
week is assumed to be the week in which January 1 occurs.
To demonstrate DatePart, set up a "Try It" project, and place the following code in the
cmdTryIt_Click event:
Private Sub cmdTryIt_Click()
Print "Current date/time is: "; _
Format$(Now, "Long Date"); _
Spc(1); _
76
Format$(Now, "Long Time")
Print "*** DatePart Function Examples ***"
Print "Using 'yyyy':"; Tab(20); DatePart("yyyy", Now)
Print "Using 'q':"; Tab(20); DatePart("q", Now)
Print "Using 'm':"; Tab(20); DatePart("m", Now)
Print "Using 'y':"; Tab(20); DatePart("y", Now)
Print "Using 'd':"; Tab(20); DatePart("d", Now)
Print "Using 'w':"; Tab(20); DatePart("w", Now)
Print "Using 'ww':"; Tab(20); DatePart("ww", Now)
Print "Using 'h':"; Tab(20); DatePart("h", Now)
Print "Using 'n':"; Tab(20); DatePart("n", Now)
Print "Using 's':"; Tab(20); DatePart("s", Now)
End Sub
Run the project and click the "Try It" button. The output should look similar to the following:
FINANCIAL FUNCTIONS:
These functions are used to perform actions relating to financial accounting. The table below
gives some of the financial functions used in the language.
AP=(Rate(TotPmts,Payment,PrincipalVal,FutureVal,PayDuration,Result)*12)*100
77
Where TotPmts is Total number of payments, Payment is loan amount,
Principalval is principal amount, FutureVal is future value, PayDuration is
payment period and Result is expected interest rate.
DDB To returns the depreciated value of an asset for a specific duration using the
Function double-declining balance method or some other method you specify.
FV To returns the future value based on periodic, constant payments and a constant
Function interest rate. e.g.:
Pmt To returns the payment based on periodic, constant payments and a constant
Function interest rate.
PV To returns the present value based on periodic, constant payments to be paid in the
Function future and a constant interest rate. e.g.:
78
UNIT – IV
PROCEDURES AND FUNCTIONS:
There are two kinds of general procedures in visual basic:
✓ Function procedures
✓ Sub procedures
Function procedures or user-defined function have self-contained piece of
code designed to message data and return a value.
Sub procedures are smaller “helper program” that are used as needed, and
do not return any value.
Then sub program and function procedures will do the following:
➢ Help we break down large tasks in to smaller ones.
➢ Automated repeated operations.
➢ Make it clearer what it we are trying to accomplish by ”naming” a piece of
code.
FUNCTION PROCEDURES:
To insert a function in the code window, open the code window by double
clicking anywhere in the form or pressing F7.choose tool/add procedure from the
tools menu. Then click the function radio button and type a name for your
function. Click on ok and a function template for the form pops up in the window.
The tools/add procedure from the tools menu. Add procedure dialog box will pop.
79
The following lines of the code are supposed to take a string and do the steps.
▪ Remove all spaces at the beginning and end of the string.
▪ Reduce multiple spaces inside the string to single spaces.
80
Function template in code window
SUB PROCEDURES:
These procedures consist of a block of code that does something much as an
event procedure. The general format sub procedures look like
Sub procedure name (parameter1, parameter2…)
Statement (s)
End sub
When visual basic executes statements of the form
procedure name (parameter1, parameter2…)
or the equivalent
call procedure name (parameter1, parameter2…)
Then the values of the parameter are passed to the corresponding
parameters in the procedure and the statement inside the sub procedure is executed.
When the End sub statement is reached execution continues with the line that
followed the call to the sub procedure.
81
ADVANCED USES OF PROCEDURES AND FUNCTIONS:
It is based on the fact that functions or procedures you define can also use
named arguments, if you choose to use this future, the names you choose for the
parameters of your functions or procedures become vital. For ex: The header for
our original char count% function was simply
Functions char count %(x$,y$)
PASSING PARAMETERS:
When we call a functions or procedures, there are actually two ways to pass
the variable as an argument, they are
➢ Passing by references
➢ Passing by value
When we pass an argument variable by references, any changes to the
corresponding parameters inside the procedure will change the value of the original
arguments when the procedure finishes.
82
Passing a variable to a procedure by reference
When we pass an argument by value, then the original variable retains its
original value after the procedures terminates regardless of the corresponding
parameters inside the procedure
85
✓ Right click and choose properties from the context menu that
pops up.
✓ In the procedure attribute dialog box shown here, enter the
descriptions you want in the description text box.
86
The project properties dialogue box
ARRAYS
By definition, an array is a list of variables, all with the same data type and
name, when we work with a single item; we only need to use one variable.
However, if we have a list of items, which are of similar type to deal with, we need
to declare an array of variables instead of using a variable for each item.
A dimension is a direction in which you can vary the specification of an
array’s elements. An array that holds the sales total for each day of the month has
one dimension (the day of the month).
An array that holds the sales total by department for each day of the month
has two dimension (the department for each day of the month).the number of
dimensions an array has is called its rank.
87
MULTI-DIMENSIONAL ARRAYS:
We specify an element an array by supplying an index or subscript for each
of its dimensions. The elements are contiguous along each dimension from index
0through the highest index for the dimension.
The following illustrations show the conceptual structure of arrays with
different ranks. Each element in the illustrations shows the index value that
accesses it.
ONE -DIMENSIONAL ARRAY:
Many arrays have only one dimension, such as the number of the people of
each page. The only requirement to specify an element is the age for which that
element holds the count. Therefore, such an array uses only one index.
The following examples declare a variable to hold a one -dimensional array
of the age counts for ages 0 through120.
Dim age counts (120) As UInteger
Suppose we want to track sales amounts for every day of the present month.
You might declare a one -dimensional array with 31 elements. One for each day of
the month, as the following example shows,
Dim Sales Amounts(30)As Double
ARRAYS WITH MORE THAN ONE- DIMENSIONS:
Some array has two dimensions. The specification of an element requires
both the building number and the floor. Each element holds the count for that
combination of building and floor, therefore, such an array uses two- indexes. The
following examples declare a variable to hold a two-dimensional array of office
counts, for building 0 through 40 and floor 0 through 5.
Dim office counts (40,5)As Byte
A two-dimensional array is also called rectangular array.
88
A few arrays have three –dimensions, such as the values in three –
dimensional space. Such an array uses three indexes, which in this case represents
the x,y and z coordinates of physical space.
The following examples declare a variable to hold a three-dimensional array
of air temperatures at various points in the three-dimensional volume.
Dim air Temperatures (99, 99, 24) As Single
Although an array can have as many as 32 dimensions. It is to have more
than three. Suppose you want to track the information not only for every day of the
month but for every day of the year.
We might declare a two-dimensional array with 12 rows (for the month) and
31columns (for the days), as the following examples shows,
Dim Sales Amounts (11, 30) As Double
Now suppose you decide to have your array hold information for more than
one year. If you want to track ales amount for 5 years, you could declare a three-
dimensional array with 5 layers, 12 rows and 31columns as the following examples
shows,
Dim Sales Amounts (4,11, 30) As Double
Note that, because each index varies from 0to its maximum. Each dimension
of sales amounts is declared as one less than the required length for that dimension.
Note that the size of the array increases with each new dimension, the three sizes
in the proceeding examples are 31,372 and 1860elements respectively.
ERASING AN ARRAY:
We should always erase your arrays when you are done using it, especially
if you are using dynamic arrays. It’s rather easy:
Dim strFriends (0to2) As String
strFriends (0) =”swathi”
StrFriends (1) =“haseena”
89
strFriends (2) =”fumy”
Erase strFriends
USING LISTS AND ARRAYS WITH FUNCTIONS AND PROCEDURES:
Visual basic has an extraordinary facility for using lists and arrays in
procedures and functions it is always passed by references it means the changing of
array or an entry of an array.
We send array parameters to a Functions or procedures. Just use the name of
the array in two-dimensional array and three-dimensional array of integers.
Dim Pop change (50), city state (3, 10), total Pop (2, 2, 2)
Note that, because each index varies from 0to its maximum. Each dimension
of sales amounts is declared as one less than the required length for that dimension.
Note also that the size of the array increases with each new dimension, the
three sizes in the proceeding examples shows,
Dim Pop change () city state () total Pop (),X1.
If the part of list or array hasn’t yet been filled these commands may not
help the elements respectively.
After they have been defined, Enums can be used as the parameters for
functions and procedures, so they can make code much clearer.
CONTROL ARRAYS :
Some time we can use the same control name more than once while
designing a VB application or use CTRL+C, CTRL+V to copy an existing control
from one place on the form to another, VB asks you whether you really want to
create a control array by popping up the message box. Then click the yes button.
92
If we assign any number to the Index property of a control at design
time, VB automatically creates a control array. We can create a control array
without having to use two controls at design time. We can have up to 255 elements
in a control array, but that would be very unusual, as it would waste too many
Windows resources.
93
Add the following code to the event procedure template.
Private Sub txtMoney_Change (Index As Integer)
If Index = 0 then
MsgBox “Sudha”
Else
Msgbox “Jaya”
End If
End Sub
94
The event procedure can use the index to determine what to do. When we
type in the text box with the Index property of zero, VB activates the If clause
inside this event procedure and so displays text telling us which box we typed in.
otherwise, VB processes the Else clause. The If-Then-Else, combined with the
index parameter, lets the event procedure determine where we typed.
Adding and Removing Controls in a Control array :
We can add a control to a control array at design time, also we can remove it
by changing the control name or deleting the control at design time. Once create a
control array, we must change all the names of all the controls in the control array
before VB will let us eliminate the Index property.
The Load statement :
Once we have created a control array at design time, we can add controls
while the application is running. To do this, we use a method called Load
statement.
Load txtMoney (I)
where I will be the index of the element.
When adding controls to a control array at run time, start up a new project
and add the following code to the Form_Load event procedure.
Private Sub Form_Load ( )
Dim I As Integer
For I = 2 to 5
Load txtMoney (I)
txtMoney (I).text = “Text box #” + Str$(I)
Next I
End Sub
If you run this program, VB loads a new element of a control array, the
object is invisible, the visible property of the new control is set to False. We have
95
to change this to true. And all other properties of new control are copied from the
object that has the lowest index in the array. Even if you modify the preceding
Form_Load procedure to read.
96
Static I As Integer
If I < 4 Then
Unload txtMoney (I+2)
I=I+1
Else
Exit Sub
End If
End Sub
Each click on an empty place in the form removes the next controls in the
control array. It will not remove two elements in the control array because of the
line
If I < 4 then ……
This is necessary because we can only load or unload an element of a control
array once. If we try to load or unload a control array element twice in succession,
VB gives a run-time error.
LIST AND COMBO BOXES :
We can give the list of values to the List box. VB automatically adds vertical
scroll bars whenever the list box is too small for all the items it contains. We might
want this application to let the user select a data by number of elements rather than
by scrolling through the list. To allow users to input data as well as make choices
from a list, use combo box.
There are two types of combo boxes, and which one we got depends on the
value of the Style property.
97
• If the value of the Style property is set to the default value of 0, we get
a combo ox with an arrow. If the user clicks the arrow, then drop-
down list of choices given in the box.
• If the value is 1, the user sees the combo box with the list already
dropped down.
In both cases, the user still has a text area to enter information. There is one
other possible choice,
There are also two types of list boxes, and working with the Style property
lets we determine if the box shows little check boxes next to the items.
Sorting Lists and Combo Boxes :
98
The items in List or Combo box can be sorted in ASCII order by simply
setting the sorted property to True.
Manipulating the Items on a List or Combo box :
We usually add or remove items from a list or combo box while the project
is running. Use the AddItem method to add an item to a list or combo box. The
syntax is,
Listname.AddItem item [ index ]
ListName is the control name of the list or combo box, andItem is a String. If the
sorted property is True for the list or combo box, then Item goes where ANSII
order places it. If it is false, VB places Item either at the position determined by the
Index Parameter or at the end of the list when we don’t specify the index.
The Index parameter must be an integer, and value of 0 (not 1) means we are
the beginning of the list. The Index position has no effect on where the item is
added to the list if the sorted property f the list box is set to true.
Other common List and Combo box properties :
List :
This is a property of both list and combo boxes, and it is for all practical
purposes like a zero-based string array that contains all the items on the list.
1stTheBox (0)
1stTheBox (1)
1stTheBox (2)
It gives us another way to initialize the items in the list or combo box instead
of doing it at run time.
ListCount:
99
This is a property of both list and combo boxes, and it gives the number of
items on the list. Since the Index property starts at 0, in order to analyze the
contents of the list using a For-Next loop, write the limits of the loop as,
For I% = 0 to 1stBoxName.ListCount – 1
Text :
It gives the currently selected item stored as a string. This, of course,
changes as the user moves through the list box. This changes as the user moves
through the list box. If we need the numeric equivalent of this string, just apply the
correct conversion function (CInt, CSng, etc).
Columns and MultiSelect :
The columns property controls the number of columns in a list box. If the
value is 0, we get a normal single-column list box with vertical scrolling. If the
value is 1, we get a single column list box with horizontal scrolling. If the value is
greater than 1, we get multiple columns.
The Multiselect property controls whether the user can select more than one
item from the list. There are three possible values for this property.
100
Extended 2 SHIFT+mouse click extends
multiselection the selection to include all list
items between the current
selection and the location of the
click. Pressing and clicking the
mouse selects or deselects an
item in the list.
• Menu Editor utility of VB can be accessed from tools menu in the forms
design screen.
• This utility is used for creating menus. It allows you to create custom
menus for your application and to define their properties.
101
Dialog Box Options:
Caption:
Allows you to enter the menu or command name that you want to appear on your menu bar or in
a menu. If you want to create a separator bar in your menu, you can type a single hyphen (-) in
the Caption box.
To give the user keyboard access to a menu item, insert an ampersand (&) before a letter. At run
time, this is underlined (the ampersand is not visible), and the user can access the menu or
command by pressing ALT and the letter. If you need an ampersand to show in the menu, put
two consecutive ampersands in the caption.
Name:
Allows you to enter a control name for the menu item. A control name is an identifier used only
to access the menu item in code; it does not appear in a menu.
Index:
Allows you to assign a numeric value that determines the control’s position within a control
array. This position is not related to the screen position.
Shortcut:
Allows you to select a shortcut key for each command.
HelpContextID:
Allows you to assign a unique numeric value for the context ID. This value is used to find the
appropriate Help topic in the help file identified by the HelpFile property.
NegotiatePosition:
Allows you to select the menu’s NegotiatePosition property. This property determines whether
and how the menu appears in a container form.
Checked:
Allows you to have a check mark appear initially at the left of a menu item. It is generally used
to indicate whether a toggle option is turned on or off.
Enabled:
Allows you to select whether you want the menu item to respond to events, or clear if you want
the item to be unavailable and appear dimmed.
Visible:
Allows you to have the menu item appear on the menu.
WindowsList:
Determines if the menu control contains a list of open MDI child forms in an MDI application.
Right Arrow:
Moves the selected menu down one level each time you click it. You can create up to four levels
of submenus.
Left Arrow:
Moves the selected menu up one level each time you click it. You can create up to four levels of
submenus.
Up Arrow:
Moves the selected menu item up one position within the same menu level each time you click
it.
Down Arrow:
102
Moves the selected menu item down one position within the same menu level each time you
click it.
Menu List:
A list box that displays a hierarchical list of menu items. Submenu items are indented to indicate
their hierarchical position of level.
Next:
Moves selection to the next line.
Insert:
Inserts a line in the list box above the currently selected line.
Delete:
Deletes the currently selected line.
OK:
Closes the Menu Editor and applies all changes to the last form you selected. The menu is
available at design time, but selecting a menu at design time opens the Code windows for that
menu’s Click event rather than executing any event code.
Cancel:
Closes the Menu Editor and cancels all changes.
MDI FORMS:
103
104
105
UNIT – V
INTRODUCTION TO DATABASE
INTRODUCTION TO DATABASE
• A major change in Visual Basic, with the introduction of Version 6.0, is in its database
management tools.
• New tools based on ActiveX Data Object (ADO) technology have been developed. These
new tools will eventually replace the older database tools, called DAO (Data Access
Object) tools.
• We will only discuss the ADO tools. Microsoft still includes the DAO tools for backward
compatibility.
• In this database table, each record represents a single individual. The fields
(descriptors of the individuals) include an identification number (ID No), Name, Date
of Birth, Height, and Weight.
• Most databases use indexes to allow faster access to the information in the database.
Indexes are sorted lists that point to a particular row in a table. In the example just
seen, the ID No field could be used as an index.
• A database using a single table is called a flat database. Most databases are made up
of many tables. When using multiple tables within a database, these tables must have
some common fields to allow cross-referencing of the tables. The referral of one table
106
to another via a common field is
called a relation. Such
groupings of tables are called
relational databases.
• In our first example, we will use
a sample database that comes
with Visual Basic. This database
(BIBLIO.MDB) is found in the
main Visual Basic directory (try
c:\Program Files\Microsoft
Visual Studio\VB98). It is a
database of books about
computers. Let’s look at its
relational structure. The
BIBLIO.MDB database is made
up of four tables:
• The Authors table consists of author identification numbers, the author’s name,
and the year born. The Publishers table has information regarding book
publishers. Some of the fields include an identification number, the publisher
name, and pertinent phone numbers. The Title Author table correlates a book’s
ISBN (a universal number assigned to books) with an author’s identification
number. And, the Titles table has several fields describing each individual book,
including title, ISBN, and publisher identification.
• Keeping track of all the information in a database is handled by a database
management system (DBMS). They are used to create and maintain databases.
Examples of commercial DBMS programs are Microsoft Access, Microsoft
FoxPro, Borland Paradox, Borland dBase, and Claris FileMaker. We can also use
Visual Basic to develop a DBMS.
• Visual Basic shares the same ‘engine’ used by Microsoft Access, known as the Jet
engine. In this class, we will see how to use Visual Basic to access data, display
data, and perform some elementary management operations.
107
ADO Data Control
• The ADO (ActiveX Data Object) data control is the primary interface between a
Visual Basic application and a database.
• It can be used without writing any code at all! Or, it can be a central part of a
complex database management system.
• This icon may not appear in your Visual Basic toolbox. If it doesn’t, select Project
from the main menu, then click Components.
• The Components window will appear.
• Select Microsoft ADOData Control, then click OK. The control will be
added to your toolbox.
• As mentioned in Review and Preview, previous versions of Visual Basic used
another data control. That control is still included with Visual Basic 6.0 (for
backward compatibility) and has as its icon:
• Make sure you are not using this data control for the work in this class. This
control is suitable for small databases. You might like to study it on your own.
• The data control (or tool) can access databases created by several other
programs besides Visual Basic (or Microsoft Access). Some other formats
supported include Btrieve, dBase, FoxPro, and Paradox databases.
The data control can be used to perform the following tasks:
1. Connect to a database.
2. Open a specified database table.
3. Create a virtual table based on a database query.
4. Pass database fields to other Visual Basic tools, for display or
editing. Such tools are bound tools (controls), or data aware.
5. Add new records or update a database.
6. Trap any errors that may occur while accessing data.
7. Close the database
Data Control Properties:
108
• As a rule, you need one data control for every database table, or virtual table, you
need access to. One row of a table is accessible to each data control at any one
time. This is referred to as the current record.
• When a data control is placed on a form, it appears with the assigned caption and
four arrow buttons:
The arrows are used to navigate through the table rows (records). As indicated,
the buttons can be used to move to the beginning of the table, the end of the table,
or from record to record.
Bound Data Tools
Most of the Visual Basic tools we’ve studied can be used as bound, or data-aware,
tools (or controls). That means, certain tool properties can be tied to a particular
database field. To use a bound control, one or more data controls must be on the form.
109
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
Keyword Description
the easiest way to create a new JET database is to use Microsoft Access.
110
1. Start Microsoft Access
2. From the menu, select File → New or press Control-N
3. Select "Blank database"
4. Navigate to where you want to save your database in the filesystem, and give it a name
You can then use the various database and security utilities to set things like the engine type,
encryption, optional system database, and users / passwords.
111
• An empty JET database can be created from Windows by creating a new ODBC DSN (Data
Source Name) and creating the database from the ODBC connection window.
• Start the ODBC Data Sources applet from the Windows Control Panel, and click Add to
make a new DSN. You should see a screen like the one on the right. Select the driver for
Microsoft Access, and click Finish.
• You should be presented with a screen for configuring a new Microsoft Access DSN, like the
one on the right. Click the Create button, to get the New Database window up.
• you should now see the New Database window. Navigate to where you want to put your JET
database, enter a name, and choose any special options like engine type (Format),
encryption, and whether to have a separate system database, then click OK to create your
database. You can now cancel out of the ODBC Data Sources applet without making the
new DSN if you like, as you probably want to connect to it via OLE-DB anyway!
The DAO data control is the primary interface between a Visual Basic application and a
database. It can be used without writing any code at all! Or, it can be a central part of
a complex database management system.
112
• The data control (or tool) can access databases created by other programs besides
Visual Basic (or Microsoft Access). Some other formats supported include dBase,
FoxPro, and Paradox.
1. Connect to a database.
2. Open a specified database table.
3. Create a virtual table based on a database query.
4. Pass database fields to other Visual Basic tools, for display or editing. Such tools are
bound to the database, or data bound controls.
5. Add new records, delete records, or update records.
6. Trap any errors that may occur while accessing data.
7. Close the database.
• As a rule, you need one data control for every database table, or virtual table, you
need access to. One row of the table is accessible to each data control at any one
time. This is referred to as the current record.
DatabaseName Returns or sets the name of the source database for the data
control. Must be a fully qualified path and file name.
113
Recordset A set of records defined by a data control’s Connect,
DatabaseName, and RecordSource properties. Run-time only.
RecordSource Determines the table (or virtual table) the data control is attached
to.
Visible Establishes whether the data control appears on the form at run-
time.
114
❖ Add the fields to be included in the report.
❖ The selected fields appear on the report.
❖ Add the selected fields one by one in the Report Fields List Box.
❖ Click on Next to continue
❖ Choose the fields on which the report is to be sorted out.
❖ Click on Next to continue.
❖ Select the fields on which the computations are to be carried out.
❖ Choose the fields based on which the records must be selected from the
database.
❖ Click Next to continue.
❖ Select the layout of the report. The selection of the style will depend upon
the type of data that are likely to have on the report.
❖ The report can be previewed.
Creating a report without a wizard:
❖ Click on the New file icon or select New from the File menu.
❖ It will display the create New Report dialog box.
❖ From that you can select Custom and click on the Data File button.
❖ You will be asked to select a database file.
❖ It will display the Design/Preview window.
❖ Here you can add the filed that you want to print and view the report.
Design and preview window:
• The default tab is the Design tab. This window is divided in to two parts. The
large white area is where you actually insert the fields and the gray area on the
left side with several rows.
• The row will be titled as Title, Page Header, Details, Page Footer and summary.
This is to help you correctly insert and correct the data that should appear on the
report.
115
DATA REPORT.
Introduction:
❖ Data Report is the new offering from Microsoft product to replacing crystal
report.
❖ In order to use Data Report you need to use ADO or Data environment.
We need to follow the following steps to generate a report using the Data Report.
1. Create a data source using DAO.
2. Add the Data Report object to your project.
3. Place textboxes representing the various fields that you want on the Data
Report object.
4. Like the Textboxes to the various fields of the data source
5. Display the report using the Show method.
Data Report:
116
❖ On the component dialog box click on the “Designer” tab and select “Data
Report” close the dialog box.
❖ Click on Project menu select ‘Add Data Report’ this item to a data report
designer to the IDE.
❖ It will not be placed on your form.
❖ Open then Project Explorer window it display another item called DataReport1
along with Form1.
❖
118
7. Page Footer: Give the page footer here. This can be the page number or any
relevant text like the date of
report etc.
8. Report Footer: The summary for the report in this section. This can contain
address the bibliography,
contact address etc. The report footer appears between the last
page header and page footer.
Data Report Controls:
The controls that are placed under the Data Report tab on the toolbox.
1. TextBox Control (RptTextBox) →To display text or other formatted data.
119
2. Label box (RptLabel) → To display the labels on the report to identify fields
or sections.
3. Imagecontrol (RptImage) →To display pictures on the report. This control
cannot be tied to a data control.
4. Line control (RptLine) →To Draw lines on the report
5. Shape control (Rptshape) →To draw rectangles, circles etc on the report.
6. Function control (Rptfunction) → This is a special text box that calculates
values as the report is generated.
❖ Click on Project menu select Data report and click Data environment from
ActiveX designer.
❖ Display the Data environment dialog box.
❖ Select Connection. Right click on the connection1 select properties.
❖ Display the data link properties.
❖ From provider tab, select Microsoft jet 3.52 OLE DB providers.
❖ Click on the Next command button it will display the connection tab.
❖ Select the data base name.
120
❖ Click on the Test connection, it will display the message box “Test
connection succeeded”.
❖ Click OK button.
❖ Right click on the connection1 and select Add command from data
environment dialog box.
❖ Right click on the command1 and select properties; it will display the
command1 properties window.
❖ Select table from data base objects.
❖ Select the table name from the object name.
❖ Click SQL statement and type the query (ex: select * from table name).
❖ Come back to dataenvironment1 dialog box.
❖ Drag the SQL command1 from dataenvironment1 dialog box to data report
detail section.
❖ Press F4, set the following properties.
❖ Data source → data environment1
❖ Data member → command1
❖ Click project menu select project1 properties. Select data report from startup
objects.
❖ Press F5
❖ In detail section the reports are displayed.
Displaying the Report:
Example:
Private sub Command1_Click()
DataReport1. Show
End Sub
121
QUESTION BANK
5 marks:
1. Explain about toolbars in VB.
2. Discuss about name property in VB.
3. Explain about textbox.
4. How start a new window in detail?
5. Explain about making of form responsive.
6. What meant by input boxes in VB?
7. Difference between Rich textbox and Textbox.
8. How to declare a variable in VB?
10 marks:
1. Discuss about creating a control in VB.
2. Explain about message box in VB.
3. Describe about command button in VB.
4. Explain about Data Types in VB.
5. Explain about Picture box in VB.
6. Explain about control statements in VB.
7. Describe about various types of String function.
122