software-development-with-visual-basic
software-development-with-visual-basic
UNIT-I
Introduction To Visual Basic
The Visual Basic is an event driven programming language. The “Visual” part refers to the method used
to create the Graphical User Interface (GUI). The “Basic” part refers to the BASIC language.
It is derived from the original BASIC language. It is the medium for developing windows based
application.
After click on the Standard EXE from the New Project screen the opening screen will be displayed.
Title bar:
The title is displayed on the title bar. [“Project1-Microsoft Visual Basic [design]”].
The titlebar in Visual Basic is the header area at the top of the form which displays your application - it
commonly displays an icon, followed by the name of the software currently running (visual Basic,
Microsoft Word, etc) and at the furthermost right hand side it will contain the minimize, maximize, exit
icons.
Menu Bar:
This Menu Bar displays the commands that are required to build an application. The main menu items have
sub menu items that can be chosen when needed. The toolbars in the menu bar provide quick access to the
commonly used commands and a button in the toolbar is clicked once to carry out the action represented by it.
Toolbox:
2
The Toolbox contains a set of controls that are used to place on a Form at design time thereby creating the
user interface area. Additional controls can be included in the toolbox by using the Components menu item on
the Project menu.
A Toolbox is represented in figure 2 shown below.
Control Description
Pointer Provides a way to move and resize the controls form
Displays icons/bitmaps and metafiles. It displays text or acts as a visual container for
PictureBox
other controls.
TextBox Used to display message and enter text.
Frame Serves as a visual and functional container for controls
CommandButton Used to carry out the specified action when the user chooses it.
CheckBox Displays a True/False or Yes/No option.
OptionButton control which is a part of an option group allows the user to select only
OptionButton
one option even it displays mulitiple choices.
ListBox Displays a list of items from which a user can select one.
Contains a TextBox and a ListBox. This allows the user to select an ietm from the
ComboBox
dropdown ListBox, or to type in a selection in the TextBox.
HScrollBar and
These controls allow the user to select a value within the specified range of values
VScrollBar
Timer Executes the timer events at specified intervals of time
DriveListBox Displays the valid disk drives and allows the user to select one of them.
DirListBox Allows the user to select the directories and paths, which are displayed.
FileListBox Displays a set of files from which a user can select the desired one.
Shape Used to add shape (rectangle, square or circle) to a Form
Line Used to draw straight line to the Form
used to display images such as icons, bitmaps and metafiles. But less capability than
Image
the PictureBox
Data Enables the use to connect to an existing database and display information from it.
OLE Used to link or embed an object, display and manipulate data from other windows
3
based applications.
Label Displays a text that the user cannot modify or interact with.
Project Explorer
Docked on the right side of the screen, just under the tollbar, is the Project Explorer window. The
Project Explorer as shown in in figure servres as a quick reference to the various elements of a project
namely form, classes and modules. All of the object that make up the application are packed in a project.
A simple project will typically contain one form, which is a window that is designed as part of a
program's interface. It is possible to develop any number of forms for use in a program, although a
program may consist of a single form. In addition to forms, the Project Explorer window also lists code
modules and classes.
Properties Window:
The Properties Window exposes the various characteristics of selected objects. Each and every form in
an application is considered an object. Now, each object in Visual Basic has characteristics such as color and
size. Other characteristics affect not just the appearance of the object but the way it behaves too. All these
characteristics of an object are called its properties. Thus, a form has properties and any controls placed on it
will have propeties too. All of these properties are displayed in the Properties Window.
Menu Bar:
This Menu Bar displays the commands that are required to build an application. The main menu items
have sub menu items that can be chosen when needed. The toolbars in the menu bar provide quick access to the
commonly used commands and a button in the toolbar is clicked once to carry out the action represented by it.
File Contains options for opening projects, closing projects, printing projects, etc.
Edit Contains options such as cut, paste, find, undo, delete, etc.
View Contains options for displaying IDE windows and tool bars.
Project Contains options for adding features such as forms to the project.
Diagram Contains options for editing and viewing the design of databases.
Tools Contains options for IDE tools and options for customizing the environment.
Add-Ins Contains options for using, installing and removing add-ins. Add-ins are typically
independent software vendor (ISV) products that extend Visual Basic’s features
Toolbars:
The toolbar in the menu bar provide quick access to the commonly used commands.
Standard toolbar:
The standard toolbar contains buttons that are shortcut to some commonly used items.Some of them are
open Project, Save project, cut, copy and paste.
Edit Toolbar:
Contains buttons that are shortcuts to some commonly used menu items.
Frequently used when editing code.
Debug Toolbar
Debugging code is essential to producing a successful Visual Basic application. One of the most useful Visual
Basic toolbars helps identify and correct coding errors. The Debug toolbar allows programmers to click buttons
and navigate through code as it executes.
Contains buttons that are shortcuts to some commonly used menu items. Frequently
used when aligning and selecting the objects.
Object Browser
The Object Browser allows us to browse through the various properties, events and methods that are
made available to us. It is accessed by selecting Object Browser from the View menu or pressing the key F2.
The left column of the Object Browser lists the objects and classes that are available in the projects that are
opened and the controls that have been referenced in them. It is possible for us to scroll through the list and
select the object or class that we wish to inspect. After an object is picked up from the Classes list, we can see
its members (properties, methods and events) in the right column.
A property is represented by a small icon that has a hand holding a piece of paper. Methods are denoted by little
green blocks, while events are denoted by yellow lightning bolt icon.
Object naming conversions of controls (prefix)
Form -frm
Label-lbl
TextBox-txt
CommandButton-cmd
CheckBox -chk
OptionButton -opt
ComboBox -cbo
ListBox-lst
Frame-fme
PictureBox -pic
Image-img
Shape-shp
Line -lin
HScrollBar -hsb
VScrollBar –vsb
Single document interface (SDI)
SDI:
A single documents interface or SDI contains single data window. An example, of the SDI interface in
the WordPad application included with Microsoft windows. In WordPad, we can only one document at a time.
We must close one document in order to open another.
A SDI application usually doesn’t contain window menus on its menu bar because we can’t move between data
windows. When user opens new data file, the data replace the data currently shown in the open window.
MDI:
MDI stands for Multiple Document Interface, a Graphic User Interface which is able to show multiple
documents can be showed at one time is known as MDI. The most feasible example of MDI can be
several latest applications which include all the latest web browsers and applications such as Facebook
and twitter. There is also another difference which comes in the form of grouping which exists
whenever an MDI is used but this option is not available in SDI and can only be achieved with the help
of command window.
Note: You can also run Visual Basic from command line using /sdi or /mdi parameter to put IDE in the
selected mode.
Toolbox:
The toolbox is a floating window that allows you to add controls to a userform.
It is not possible to add controls using menu commands.
When a userform is activated the Toolbox is displayed automatically in a floating window.
To add a control, click on the corresponding icon on the toolbox and drag it onto the userform.
Select Objects - Select Objects is the only item in the Toolbox that doesn't draw a control. When you select it,
you can only resize or move a control that has already been drawn on a form.
1.choose Project/Components.
3.click on ok.
we can add multiple tabs to the toolbox in order to make it easier to see what components you have
available.To add another tab,do this:
The intial form window takes up a part of the center of the screen.To customize the form window by
adding controls and changing the size,the result is the intial form window.
10
ii. Select the Start option from Run menu by using the mouse or by pressing ALT+R, S.
iii. Press F5.
After a short delay, the form will pop-up super-imposed on the Visual Basic IDE and looking like as follows:
To return to developing an application click on the exit(x) button on the form, or open the Run menu and click
the End option, or use the End tool.
1.2.2 Working with the Properties Window:
i. Display the properties window by pressing F4 if it is not visible.
ii. Move to the properties window and select an item from the properties in the list box.
iii. Enter the new setting for the property.
iv. Press ENTER to accept new string.
Keyboard Shortcuts:
The following keyboard shortcuts used for manipulating the properties window:
Key Action
SHIFT+CTRL+letter key Moves to the first item beginning with that letter.
DOWN ARROW Moves to the next item in the properties list box.
UP ARROW Moves to the previous item in the properties list box.
PAGE DOWN/END Moves to the last item displayed in the properties list box or to the last item.
PAGE UP/HOME Moves to the first item displayed in the properties list box or to the first
item.
F4 Brings up the properties window.
COMMON FORM PROPERTIES
The Form consists of many properties. Some of the commonly used properties are:
Caption
Name
Appearance
11
BorderStyle
ControlBox
Enabled
Font
Height, Width
Icon
Left, Top
MousePointer, MouseIcon
StartUpPosition
Visible
WindowState
Caption:
This property sets the title of the form. It can be changed at runtime. It must be meaningful and
informative to the user.
Name:
It is used only in code. It gives the name by which the Form is referred to in the user code. The name of
a form cannot be changed at runtime.
Appearance:
This property determines whether the form will have a three-dimensional look. The default value of 1
indicates the form will appear three-dimensional. If it changes to 0, the form will appear flat.
BorderStyle:
This property determines the type of window that the user will view at runtime. It consists of five values.
The default value, 2-Sizable, allows the user to size and shape the form via the hot spots located on the
boundary of the form.
The other values are:
1-Fixed Single
3-Fixed Double
4-Fixed ToolWindow
5-Sizable ToolWindow
0-None
i. Set the Borderstyle value to 0-None, the application does not consists of no border. The form created
without a border cannot be moved, resized, or reshaped.
ii. The value 1-FixedSingle, the user no longer be able to resize the window. The users minimize and
maximize the form window.
iii. The third setting 3-FixedDouble not used for ordinary forms, but it is commonly used for dialog
boxes. It gives a nonsizable (it has no hot spots).
12
iv. The 4-Fixed ToolWindow setting not used very often. Under windows 95/98, this displays the form
with a close button. The fifth setting 5-Sizable ToolWindow like an FixedToolWindow setting.
ControlBox:
The value of this property is True or False. If it is set to True, the Control Box is visible on the top left-
hand corner of the form. The minimize and maximize button are displayed on the title bar of the Form. The
value of this property is set to False the user not access the minimize and maximize commands.
Enabled:
This property consists of two values. The default value is True. If it is set to False, the form cannot
respond to any events such as the user clicking on the form.
Font:
To access the Font property press Ctrl+Shift+F. It includes the following:
Font Name: Name of the font.
Font Bold: If set to true, the text will be displayed in bold.
Font Size: Set the size of the text in points.
Height, Width:
This property indicates the height and width of the form. The user can change their values directly via the
properties window.To perform this users enter the value in the appropriate line in the right-hand column of the
properties window.
13
Icon:
This property determines the icon of the user application will display when it is minimized on the
toolbar. To choose an icon for user applications go to properties window and select the Icon property. Click the
box containing three dots a dialog box will appear.
From this dialog box we can choose the icon for the application
Left, Top:
These properties determine the distance between the left or top of the form and the screen. To control
these properties by using the Form Layout window.
MousePointer, MouseIcon:
The MousePointer is a useful property it set the shape of the mouse pointer. The default value is 0, but
as the pull-down list indicates, there are 17 other values. Set the MosuePointer property to a value of 99, the
user able to use a custom icon.
StartUpPosition:
It is another way to decide on the initial position of the form at run time. It is more precise than using
the Form Layout window.
Visible:
AThis property consists of two values. The default value is True. Set the value of this property to False, the
form will no longer be visible.
WindowState:
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 the form. A setting of 0 is the normal default
setting.
14
SCALE PROPERTIES
The scale properties are need to position objects or text in a form accurately. The following properties
that affect the scale used in a form:
ScaleMode
ScaleHeight, ScaleWidth
ScaleLeft, ScaleTop
ScaleMode:
It is used to change the units used in the forms internal coordinate system. It consists of seven
possibilities. The default value is 1.
ScaleHeight, ScaleWidth:
Using this property we can set the own scale for the height and width of the form.
ScaleLeft, ScaleTop:
These properties describe what value visual basic uses for the left or top corner of the form. The original
(default) value for each of these properties is 0. These properties are most useful when the user working with
graphics like ScaleHeight and ScaleWidth.
1.5 COLOR PROPERTIES
Using Color properties specify the background color (BackColor) and the foreground color (Forecolor)
for text and graphics in the form.
1.5.1 The BackColor and ForeColor Properties via the Color Palette:
To set the Backcolor property, open the properties window and select BackColor (represented by
hexadecimal code-base 16). To set colors is to choose one of the color properties and click the down arrow in
the Settings box. This opens up a tabbed dialog box with two tabs.
15
The System tab on this dialog box gives the colors currently used by windows for its various elements.
To click on the Palette tab, the color grid will appear. Select any color from the Palette and the Color code for
that color is placed in the settings box. The background color of the form will automatically show the user
changes to the BackGround property.
To the left of the palette, a dark box enclosed in a lighter box. The inner box displays the current
foreground color, and the outer box displays the current background color.To change the foreground color by
clicking the inner box and the clicking any of the colored boxes displayed.To change the background color,
click the outer box and then click any of the colored boxes displayed.To go back to the default colors specified
in the Windows control panel, click the Default command button at the right.
To create own colors for the color palette consists of the following steps:
Click one of these blank boxes, and then click the Define Colors command button.
This opens the Define Color dialog box.
Change the amount of color to suit the user needs by adjusting the controls in the dialog box.
Press the Add Color button to create the custom color or the Close button to cancel.
16
ALTERING A FORM
How Can We Resize Or Altering A Form At Design And Run Time? (5 Marks)
Altering a Form:
One way to resize a form is common to all Microsoft windows
applications: Move the mouse to one of the hot spots of the form.
The hot spots are the sides or corners of the form. The mouse
pointer changes to a double-headed arrow when you’re at a hot
spot. At this point you can hold the mouse button down and drag
the form to change its size or shape.
To change the position of the form at run time, follow these steps:
Move the cursor to the Form Layout window. (The cursor
will change to a four-headed arrow).
Drag the form to the position in which you want it appear
when the user starts your program.
The changes in the Form Layout window are run-time changes only. The position of the form in the
design window in the center of your screen doesn’t reflect the user changes.
The following keyboard shortcuts used for manipulating the properties window:
Key Action
SHIFT+CTRL+letter key Moves to the first item beginning with that letter.
DOWN ARROW Moves to the next item in the properties list box.
UP ARROW Moves to the previous item in the properties list box.
PAGE DOWN/END Moves to the last item displayed in the properties list box or to the last item.
PAGE UP/HOME Moves to the first item displayed in the properties list box or to the first item.
F4 Brings up the properties window.
Name:
It is used only in code. It gives the name by which the Form is referred to in your code. The name of a
form cannot be changed at runtime.
Appearance:
19
This property determines whether the form will have a three-dimensional look. The default value of 1
indicates the form will appear three-dimensional. If it changes to 0, the form will appear flat.
BorderStyle:
This property determines the type of window that the user will view at runtime. It consists of five
values. The default value, 2-Sizable, allows the user to size and shape the form via the hot spots located
on the boundary of the form.
The other values are:
1-Fixed Single
3-Fixed Double
4-Fixed ToolWindow
5-Sizable ToolWindow
0-None
Set the Borderstyle value to 0-None, the application does not consists of no border. The form created
without a border cannot be moved, resized, or reshaped.
The value 1-FixedSingle, the user no longer is able to resize the window. The users minimize and
maximize the form window.
The third setting 3-FixedDouble not used for ordinary forms, but it is commonly used for dialog boxes.
It gives a nonsizable (it has no hot spots).
The 4-Fixed ToolWindow setting not used very often. Under windows 95/98, this displays the form
with a close button. The fifth setting 5-Sizable ToolWindow like a FixedToolWindow setting.
ControlBox:
The value of this property is true or False. If it is set to True, the Control Box is visible on the top left-
hand corner of the form. The minimize and maximize button are displayed on the title bar of the Form.
The value of this property is set to False the user not access the minimize and maximize commands.
Enabled:
This property consists of two values. The default value is True. If it is set to False, the form cannot
respond to any events such as the user clicking on the form.
Font:
To access the Font property press Ctrl+Shift+F. It includes the following:
Font Name: Name of the font.
Font Bold: If set to true, the text will be displayed in bold.
Font Size: Set the size of the text in points.
Height, Width:
This property indicates the height and width of the form. The user can change their values directly via
the properties window.
To perform this users enter the value in the appropriate line in the right-hand column of the properties
window.
Icon:
This property determines the icon your application will
display when it is minimized on the toolbar. To choose an
icon for user applications go to properties window and
select the Icon property. Click the box containing three dots
a dialog box will appear.
From this adjacent dialog box we can choose the icon for
the application
Left, Top:
These properties determine the distance between the left or
top of the form and the screen. To control these properties by using the Form Layout window.
MousePointer, MouseIcon:
The MousePointer is a useful property it set the shape of the mouse pointer. The default value is 0, but
as the pull-down list indicates, there are 17 other values. Set the MosuePointer property to a value of 99,
the user able to use a custom icon.
StartUpPosition:
20
It is another way to decide on the initial position of the form at run time. It is more precise than using
the Form Layout window.
Visible:
This property consists of two values. The default value is True. Set the value of this property to False,
the form will no longer be visible.
WindowState:
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 the form. A setting of 0 is the normal
default setting.
SCALE PROPERTIES
List Out And Explain About The Scale Properties. (5 Marks)
The scale properties are need to position objects or text in a form accurately. The following properties
that affect the scale used in a form:
ScaleMode
ScaleHeight, ScaleWidth
ScaleLeft, ScaleTop
ScaleMode:
It allows you to change the units used in the forms internal coordinate system. It consists of seven
possibilities. The default value is 1.
ScaleHeight,ScaleWidth:
Use this property when you set up your own scale for the height and width of the form.
ScaleLeft,ScaleTop:
These properties describe what value visual basic uses for the left or top corner of the form. The original
(default) value for each of these properties is 0.
These properties are most useful when you are working with graphics like ScaleHeight and ScaleWidth.
COLOR PROPERTIES
Write Short Notes On Color Properties. (5 Marks)
How Can We Work With Color Palette? (2 Marks)
Using Color properties specify the background color (BackColor) and the foreground color (Forecolor)
for text and graphics in the form.
The BackColor and ForeColor Properties via the Color Palette:
To set the Backcolor property, open the properties window and select BackColor (represented by
hexadecimal code-base 16). To set colors is to choose one of the color properties and click the down
arrow in the Settings box. This opens up a tabbed dialog box with two tabs.
The System tab on this dialog box gives the colors currently used by windows for its various elements.
To click on the Palette tab, the color grid will appear. Select any color from the Palette and the Color
code for that color is placed in the settings box. The background color of the form will automatically
show the user changes to the BackGround property.
21
To the left of the palette, a dark box enclosed in a lighter box. The inner box displays the current
foreground color, and the outer box displays the current background color.
To change the foreground color by clicking the inner box and the clicking any of the colored boxes
displayed.
To change the background color, click the outer box and then click any of
the colored boxes displayed.
To go back to the default colors specified in the Windows control
panel, click the Default command button at the right.
To create own colors for the color palette consists of the following
steps:
Click one of these blank boxes, and then click the Define
Colors command button. This opens the Define Color
dialog box.
Change the amount of color to suit the user needs by
adjusting the controls in the dialog box.
Press the Add Color button to create the custom color or the
Close button to cancel.
22
End Sub
Private means that the variables declared and the code used only by this function. The Form_Load() is
the name of the function. End Sub means end of this sub-routine.
The above Form_Load event is triggered when Visual Basic loads a form in memory.
Private Sub Form_Load()
BackColor=vbRed
End Sub
the above code changes the background color to red after run the program.
Working with the Form_Click Event:
To display the Form_Click procedure in the code window by using the following steps:
o Move to the event drop-down list box on the right and click the down arrow.
o Move through the box until the user get to the click item. To quickly go to a specific event
procedure by pressing the first letter of the item.
Example: Pressing C will quickly take you to the click procedure.
o Click on it.
After complete the above steps the VB does the following:
o Gives the new event procedure template for the Form_Click event procedure.
o Adds a dotted line between the Form_Load event and the Click event.
o Moves the cursor to the blank line before the End Sub line in the Click event procedure
template.
o Press the TAB key once or the SPACEBAR a few times and type print “You Clicked the
mouse once.”
o Now press F5 to run the application. The print command sends the exact text found between
the quotation marks directly to the form.
23
If the user press ENTER or click the OK command button, the offending word remains highlighted, and
the user either type the correct replacement or move the mouse pointer to the “f” and press DEL. After
you made the correction and run the program again.
24
Visual basic can find some syntax errors after you finish typing a line. To make sure this feature is on,
choose Tools|Options and then go to the Environment page. Move to the item marked Auto Syntax
Check and make sure that it is checked (on).
CREATING STAND-ALONE WINDOWS PROGRAM
How Can We Create The Stand-Alone Windows Programs? (2 Marks)
One of the most exciting features of Visual Basic is the ability
to change your projects into stand-alone Microsoft
windows programs.
To make a stand-alone VB application, simply go to the File
menu and choose the Make Project EXE File option (ALT+F,
K). This opens a dialog box like as follows:
The default name for the .exe version of your file is the project
name. For the stand-alone program, the Windows desktop uses
the same icon that Visual Basic uses for the executable version
of the Project.
THE TOOLBOX
Discuss About Toolbox. (5 Marks)
The toolbox contains set of tools. It itself contains the icons
representing the controls you can add to your forms.
The standard edition of Visual Basic comes with more than 20
different controls; the professional and Enterprise editions add
many controls.
It is located on the left of the VB screen, but it need not be visible at
all times. If the toolbox is not visible, make it visible in order to
work with a control. To open the toolbox, use the Toolbox tool or
go to the view menu and choose Toolbox (ALT+V,X).
The Pointer:
The first item on the toolbox is not a control but is used to manipulate controls after you create them.
Click the pointer when you want to select, resize, or move an existing control. The Pointer is
automatically activated after you place a control on a form.
Command Buttons:
It is also called as push buttons. The user will click on this button and the computer will perform the
task associated with the button.
Image Controls:
It is used to display the pictures. It uses the fewest Windows resources for displaying images. The
command button also used to display the picture.
Picture Box:
It can display a graphic from a bitmap, icon, or metafile, JPEG, GIF files.
Text Boxes:
It is used to display text or to accept user input. It is sometimes called as edit fields. It can wordwrap
automatically or display multiple lines of text.
All the ordinary windows editing tools, such as cutting and pasting, are available when you enter
information in a text box. This means users can automatically use such shortcuts as CTRL+X to cut,
CTRL+C to copy, and CTRL+V to paste. The usual limit for a text box is approximately 32,000
characters.
Labels:
Use labels for information that users shouldn’t be able to change. It is used to identify objects. It
responds to 12 events, usually they are used passively-for display purposes only.
CREATING CONTROLS
25
Example:
To create an application with five command buttons symmetrically, double-click on the Command
Button icon five times. This stacks five command buttons in the center of the form.
Now we can move the buttons to the particular location. Change the captions by adjusting the Caption
property of the command buttons via the Properties window.
26
Steps:
Imagine a rectangle that surrounds only those controls you 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 you want to select. Then release the mouse button. The grouped control now
contains sizing handles.
Once the user selected a group of controls, when you move any control in the group VB menus the other
controls in a similar way.
The next method is to select each control by moving the mouse pointer to it and holding down the left
mouse button while pressing CTRL.
To take controls out of their temporary grouping and treat them individually again:
Move the mouse pointer to any place outside the selected controls and click.
The Tools|Format menu has multiple submenus that let you resize and reshape a group of controls. The
Format|Align submenu is used to align controls so that their left edges match, their centers are aligned,
and so on.
The Format| Make Same Size menu is used to make a group of controls all the same width, height, or
both:
Locking Controls:
Once the control is positioned on the form, the user want to lock the control by using Lock feature. By
choosing Format |Lock Controls or Lock Control tool from the toolbar, you want prevent yourself from
inadvertently moving a properly positioned control. This item is a toggle, choosing it again frees up
controls we can move them again.
Deleting Controls:
To delete the control by using the following steps:
Move the mouse pointer until it is inside the control, and click the left mouse button to
select it.
Press DEL, or open the Edit menu and choose the Delete option by pressing ALT+E, D.
To delete many controls at once, first select the controls as one unit and press DEL key or Delete menu
option.
27
To make a command button display a picture first, to set the Style property to 1. After that, you need
only specify the picture to be used as the value of the other three properties.
Shortcuts for Setting Properties:
To set the Caption property for all the command buttons on your form. Se the caption for first command
button and immediately select another command, the Caption property for the new control is highlighted
in the properties window.
To select a group of controls, the Properties window will show only the common properties that the
controls in the group share. Change one of them and all of them change.
Discuss About The Event Procedure Of Command Button. (5 Marks & 10 Marks)
Write Down The Format For An Event Procedure Template. (2 Marks)
Who Do You Make A Command Button As Escape Button? (5 Marks)
SIMPLE EVENT PROCEDURES FOR COMMAND BUTTON
Writing an event procedure for a Command button is similar to writing one for a form. The VB opens
the code by either double-clicks a control or press F7 for shortcut.
General Form for an Event Procedure Template:
Private Sub ControlName_EventName()
End Sub
Example:
Consider the command button with the caption “Click here for help!” and the name property is
CmdHelp. Now the event procedure template look like as follows:
Private Sub CmdHelp_Click()
End Sub
To add a simple Print statement to this above procedure and run the application by pressing F5.
Print “No Help is yet available. Sorry”.
After that click command button the information printed to the form behind the control.
End Sub
Private Sub Command2_LostFocus()
End Sub
Some Final Points on Command Buttons:
One of the methods for activating a command button is common to all Windows applications: move the
focus by pressing TAB, and then press the SPACEBAR when the focus is where you want it to be. Both
clicking and using the Tab|SpaceBar combination tell VB to activate the Click event procedure if you
wrote one for that control.
It is possible to create an escape button for a form a user can activate an escape command button by
pressing Esc on the keyboard. Use an escape button to allow users to cancel an action.
To set the Cancel property to True, the user makes that button as escape button. Setting the Cancel
property to True for one button automatically sets it to False for all the other command buttons on the
form, use only one escape (cancel) button per form.
Once the user set this property press Esc, VB will trigger the Click event procedure for this button,
regardless of where the focus is.
29
Many Windows applications allow pressing ALT and one other key, the access key, to quickly activate
a control or a menu item. These access keys are underlined in the caption of the control or name of the
menu item.
VB makes it easy to set up an access key for any object that has Caption property. When the user set the
caption, place and ampersand (&) in front of the letter you want to be the access key.
When the application is running, the user can activate this button either by pressing the ALT+the
underlined character or by clicking on the button.
Discuss About Image Controls. (5 Marks)
IMAGE CONTROLS
The Image Controls is used to hold pictures. It can be used to display icons or pictures created with a
program such as Microsoft Paintbrush. They can also hold Windows metafiles of Jpegs or Gifs. Jpeg
format is also the common format used by most digital cameras.
This controls respond to the Click event, the user use the images to substitute for the command buttons.
To load a picture into an image control by resetting the value of Picture property. If the user uses the
Picture property for the image control, this opens up a dialog box that lets you choose what image file to
load.
To reset the Picture property directly by copying an image from a graphics program to the Windows
clipboard and then using Copy command on the Edit menu to paste the image in to the image control.
Properties of Image Controls:
The BorderStyle property for an image control has only two possible settings: you can enter have no
border (setting=0) or a fixed single border (setting=1).
The important property is stretch property. This determines whether the image control adjusts to fit the
picture, or the picture adjusts to fit the control. This property is set to True the picture resizes to fit the
control. The default value of False indicates the control resizes itself to fit the picture.
List Out And Discuss About The Properties Of Text Box. (10 Marks)
What Is The Use Of Text Box? (2 Marks)
TEXT BOXES
The text boxes are the primary method for accepting input and displaying output in Visual Basic.
Standard Properties of Text Boxes:
It consists of 50 properties. The standard properties are:
Name
Font
Enabled
Visible
ForeColor and BackColor
Name:
This property indicates the name of the text box is used only for the code. (The Microsoft’s Prefix for
the Name property of a text box is txt).
Font:
To set the font properties via the Font dialog box available from the Properties window, but the user can
only use one font per text box.
Enabled:
This property affects whether the textbox will respond to events. If the text box is displayed, the user
cannot enter text inside it. It also grayed.
It consists of two settings. The default value is true.
Visible:
This property consists of two values. The default value is True. If it is change to False the text box will
disappear.
ForeColor and BackColor:
It ForeColor affects the color of the text that is displayed. The BackColor affects the rest of the text box.
Both of these can be set independently of the surrounding container.
It is easiest to set them using the color palette from the Properties window.
Some Special Properties for Text Boxes:
Text:
30
The default value for this property is set to Text1, Text2 and so on. If you want a Text box to be empty
when the application starts, select the Text property and blank out the original setting.
Alignment:
This property controls how text is displayed. The default value is 0, which indicates the text is left-
aligned. Use a value of 1 and text is right-aligned. Use a value of 2 and text is centered.
MultiLine:
This property determines whether 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.
VB automatically word-wraps when a user types more than one line of information into a multiline text
box. The multiline text boxes are the usual method for displaying large amounts of text in Visual Basic.
The limit for a multiline text box is approximately 32,000 characters.
ScrollBars:
This property determines whether a text box has horizontal or vertical scrollbars. Without scrollbars, it
becomes much harder for the user to move through the data contained in the text box, thus making
editing the information that much more difficult.
The four possible settings for the ScrollBars property are:
Value Meaning
0 The default value is 0. The text box lacks both vertical and horizontal scrollbars.
1 The text box has horizontal scrollbars only.
2 The text box has vertical scrollbars only.
3 The text box has both horizontal and vertical scroll bars.
BorderStyle:
There are only two possible settings for the BorderStyle property for a text box. The default value is 1,
which gives the single-width border, called a fixed single. If you 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. Any setting other than 0 will limit the user’s ability to enter data into that text box to that number of
characters.
PasswordChar:
The asterisk (*) symbol used as a password character. This feature is combined with the MaxLength
property to add a password feature to your programs.
Locked:
This True/False property prevents users from changing the contents of the text box. Users can scroll
highlight text, but won’t be able to change it.
Event Procedures for Text Boxes:
The text boxes can recognize 23 events. VB monitors the text box and calls the Change event procedure
whenever a user makes any changes in the text box. One of the most common uses of the Change event
procedure is to warn people that they should not be entering data in specific text box at this moment.
Explain About Label Properties. (2 Marks & 5 Marks)
LABELS
o It is used to display information. The common use is to identify a text box or other control by describing
its contents.
o The icon for a label is the bold, caption letter A, and Microsoft’s suggested prefix for the Name property
of labels is lbl.
o The labels have 34 possible properties. Most of them overlap with the properties for text boxes and
forms.
Example:
The Caption property that determines what they display. This property is set to be the same as
the default Name property: Label1 for the first label.
The Name property for the control is used only for the code you write.
The ForeColor property affects the color of the text that is displayed. BackColor affects the rest
of the label.
Useful Properties for Labels:
Alignment:
31
This property 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.
BorderStyle, BackStyle:
The BorderStyle property has the same two possible values as text boxes. The default value is 0,
indicates the label does not contain border. Set the value to 1, the label resembles a text box.
The BackStyle property determines whether the label is transparent or opaque.
AutoSize, WordWrap:
The labels can be made to grow automatically in a horizontal direction to encompass the text. This is the
function of the AutoSize property.
Set the WordWrap property to True, the label will grow in the vertical direction to encompass its
contents, but the horizontal size will stay the same.
Event Procedures for Labels:
The labels respond to 18 events. For example, they can respond to clicking, double-clicking, or the
Change event. The most common event procedures for a label are mouse events.
Mouse Event Procedures:
Name Event That Caused It
MouseDown User clicks one of the mouse buttons.
MouseUp User releases a mouse button.
MouseMove User moves the mouse pointer to a control or to a blank area of the form.
Explain About ‘Navigating Between Controls. (5 Marks)
What Is The Use Of Tabindex And Tabstop Property? (2 Marks)
How Can We Assign The Access Key For Text Boxes? (2 Marks)
NAVIGATING BETWEEN CONTROLS
The mouse is the most common way to move from control to control in a Windows application, but the
applications have to allow for using the TAB key.
The Tab Order is the term used in a Windows application for the sequence of controls that pressing
TAB moves you through.
In a VB application, the order in which you create the controls is the order used for the tab order. The
first control create at design time is the one that receives the focus when the application starts.
The user press TAB when the focus is at the last control that the user created, the focus moves back to
the first control.
TabIndex Property:
Using this property to change the setting for the tab order both design and run time. If the user set this
value to 0 for a control, this control automatically becomes the first control in tab order, and all the other
controls moved upward in tab order.
TabStop Property:
This properties consists of two settings i.e. True/False. This property controls whether the user can tab
to the control.
Example:
If the user set the TabStop property of a command button to False, the user can directly click on
it but wouldn’t be able to tab to it and press the SPACEBAR to activate it.
32
The user can add more informative, title to a message box. The full form of the message box statement
by adding two options to it.
MsgBox MessageInBox, TypeOfBox, TitleOfBox
The three different groups of built-in integer constants to specify the kind of message box.
Symbolic Constant Value Meaning
vbOkOnly 0 Display OK button only
vbOkCancel 1 Display OK and Cancel buttons
vbAbortRetryIgnore 2 Display Abort, Retry, and Ignore buttons
vbYesNoCancel 3 Display Yes, No, and Cancel buttons
vbYesNo 4 Display Yes and No buttons
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
Consider the following statement
MsgBox “Will have Yes and No Buttons”,vbYesNo
The next group of number controls which button is the default button for the
box.
Symbolic Constant Value Meaning
vbDefaultButton1 0 First button is default
vbDefaultButton2 256 Second button is default
vbDefaultButton3 512 Third button is default
33
Example:
MsgBox “Welcome to JAIRAM COLLEGE”,vbOkCancel+vbExclamation+vbDefaultButton2,
“Test Message 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 the title.
Write Short notes on GRID. (5 Marks)
THE GRID
The grid is used to accurately position the controls. In order to control the grid, choose Tools|Options
(ALT+T,O) and then go the General page on the options dialog box.
Show Grid:
The user can turn the grid on or off by changing the
Show Grid setting. The default setting is on.
Grid Width, Grid Height Boxes:
The width and height text boxes indicate the distance
between grid marks. The default is 120 twips. Change
these both to 60, and the grid becomes twice as fine.
Align Controls to Grid:
This checkbox determines whether controls
automatically move to the next grid mark or whether
they can be placed between grid marks.
It is possible to align an item to the grid even if the
users choose this option is off. To do this, select the
control by clicking it once and choosing Format| Align |
to Grid.
Explain About The ASCII Representation Of Forms. (5 Marks)
THE ASCII REPRESENTATION OF FORMS
All the information about the controls and form is stored in text format that can be read using text editor
or word processor.
Using the text representation of a program makes it easy to check that the properties of the various
controls and forms are exactly what you want.
Steps:
Start a new Standard EXE project.
Set the caption of the form to “Jairam”
Add the command button in the default size, in the default location, and using the default name of
Command1 by double-clicking on the Command Button tool.
Add a Click procedure to the command button with a single line of code:
Private Sub Command1_Click()
Print “Never Ever Ever Give Up”
End Sub
VERSION 5.00
34
The idea of the ASCII form representation is simple: It contains a textual description of the form’s
properties.
The listing begins with the five version used, followed by the name of the form and the current settings
of all the properties associated with the form.
||**********************UNIT-I COMPLETED********************||
UNIT-II
STATEMENTS IN VISUAL BASIC
Explain about the statements with example. (5 Marks)
What Is Statement? (2 Marks)
Discuss About The Comment Line Statement In VB With Example. (2 Marks)
What Is The Use Of End Statement? (2 Marks)
A statement is an executable combination of tokens. Smallest individual units in a program are known
as tokens.
The VB can detect many typos only if the Auto Syntax Check turned on in the Editor page of the
options dialog box. If a statement the user entered cannot be analyzed, a message box pops up and often
helps you find out what caused the problem.
The VB ignores case and spacing, except within quotation marks. The statements in VB rarely use line
numbers, and each statement generally occurs on its own line.
The lines are limited to 1,023 characters but a statement can be extended to the next line by using the
underscore character _ proceeded by a space at the end of the line.
The line continuation character should only need the lines that are longer than the width of the screen.
Example:
MsgBox “Jairam College”_
vbOkOnly, “Test Button”
Comments:
These statements are statements that help explain the code to any users. They are not processed by VB.
To comment the statement by using single quotation mark (‘)
Example:
Private Sub Command1_Click()
‘This program was written by Chilamb
End Sub
The comment statement also called as remark statements. We can also use the rem keyword for a
comment.
Private Sub Command1_Click()
Rem comments describing the procedure
End Sub
To add comments to the ends of lines, it is easier to use the single quotation mark because the Rem form
requires a colon before it.
PrintForm ‘Dump the current window
PrintForm :Rem a bit more cumbersome
Everything on a line following a comment symbol or the Rem keyword is ignored, regardless of
whether it is an executable VB statement or not.
The End Statement:
When VB processes an End statement, the program stops. In a stand-alone program, after the
End statement, all windows opened by the program are closed and the program is cleared from memory.
Many professional programmers prefer to use only one End statement in their code. They place this End
statement in the QueryUnload event for the main form.
VARIABLES
1. EXPLAIN ABOUT VARIABLES. (5 Marks)
HOW CAN WE ASSIGN THE VALUES TO THE VARIABLE? (2 Marks)
WHAT IS VARIABLE? (2 Marks)
A variable is a placeholder to store values during a program’s execution. The variables in VB are
declared using the DIM statement and the following syntax:
Dim variablename [As type]
Example:
36
Dim a as Integer
The name of the variable:
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 within the same scope.
Variable Assignment Statements:
The assignment statement is used to give a new value to the variable. It is also used to copying
information from source to destination. VB uses an equal sign for this operation.
Example: InterestRate=.05
The variable name always appears on the left of the equality sign, and the value always appears on the
right.
SETTING PROPERTIES WITH CODE
How Can We Set The Properties By Using Code? (5 Marks)
Discuss About Boolean Properties. (5 Marks)
To change a property setting for a VB object with code, place the object’s name followed by a period
and then the name of the property on the left side of the equal sign, and put the new value on the right-
hand side.
object. property=value
Examples:
To blank the value of text button by using the following code:
Text1.Text=””
To change the setting for the text property to the text in the quotation marks.
Text1.Text=”This is the text”
To change the caption on a command button called command1, by using the following code
Command1.Caption=”Addition”
If you want to set a button (command5) to be first button in tab order,
Command5.TabIndex=0
Default Properties:
Every VB object has a default property. When referring to the default property the users do not use the
property name.
Example: Text1=”Jairam College”
Boolean Properties:
This property that take only the value True or False are called Boolean properties.
Example:
The visible property of a control is a Boolean property. A statement such as
Command1.Visible=False
the above code hides the command button by resetting the Visible property to be False. The control
stays hidden until VB processes the statement that is
Command1.Visible=True
The Not Operator and Boolean Properties:
The usual way to toggle (Change from on to off, and off to on) Boolean properties is with the Not
operator.
Command1.Visible=Not(Command1.Visible)
The VB finds the current value of Command1.Visible, and then the Not operator reverses this value;
that is, if the value was True, it changes to False, and vice versa.
DATA TYPES
Explain About The Various Data Types Used In VB. (10 Marks)
What Is The Use Of Deftype Statement? (2 Marks)
The variables can have a name and data type. The data type of a variable determines how the bits/bytes
representing those values are stored in the computer’s memory. All variables have a data type that
determines what kind of data they can store. The VB handles 14 standard types of data.
String:
37
This datatype holds characters. A variable holding a string is called as string variable. To identify the
variables of this type is to place a dollar sign ($) at the end of the variable name:
Example: sname$
Once the user adds the dollar sign, that variables can only hold strings. It is used to pick up the
information from the text box.
Example: sname$=Text1.Text
This data type holds 2 billion characters for Variable Length and 65,400 for fixed length.
Integer:
This datatype holds only small integer values. To identify the variables of this type is to place a %
(percent) sign at the end of the variable name. [Range: -32,768 to 32,767]. It occupies only two bytes of
memory.
Example: mark1%=73
Long Integer:
This datatype holds a wide range of integers than integer. [Range:-2,147,483,648 and +2,147,483,647]
To identify the variable of this type is to place an ampersand (&) sign at the end of the variable name. It
occupies twice as much space as the Integer.
Example: LI&=123456789
Single Precision:
This is the equivalent of the Floating-Point number. It is used to holds numbers with decimal places. To
identify the variables of this type is to place an exclamation point (!) at the end of the variable name.
Example: spv!=12.345
It occupies 4 byte of memory space and should be used where very high precision is not a must.
Double Precision:
It occupies 8 bytes of memory space and should be used in applications where the requirement of
precision is very high.
The identifier used for double-precision variables is a pound sign (#) and also use this sign at the end of
the actual number.
Example: DPV#=12.345#
Currency:
It is used for holding monetary values. This data type can have 4 digits to the right of the decimal place
and up to 15 to the left of the decimal point.
[Range: -922,337,203,685,477.5808 to 922,337,203,685,477.5807]
The identifier used for this variable is a “at” sign @ and also use this sign at the end of the actual
number.
Example: CV@=12.345@
Date:
This data type used to holds date and time data. It occupies eight bytes of memory.
Example: DOB=#December 31, 1978 11:03 PM#
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 datatype accepts only True or False values.
Variant:
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 to 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)
38
39
Example 1:
Message=”This program was created by”
Message=Message & “ Stephen Flemming ”
MsgBox Message
Example 2: [Use & in the MsgBox itself]
Message=”This program was created by”
Name3=“ Stephen Flemming”
MsgBox Message & Name3
Evil Type Conversions I: Beware of the + Sign for Strings:
Many programming languages use a + sign to join together strings. Although the + still works in VB to
join strings together but it lead to incredibly hard-to-find bugs.
Example:
Private Sub Form_Load()
Dim a As String
Dim b
a=”45678”
b=1234
MsgBox a+b
End Sub
The VB assumes the value of b to be a number. The result also be a number.
ASCII/ANSI Codes:
A computer does not have one kind of memory for text and another for numbers. Anything stored in the
computer’s memory is actually stored as a number.
A code for translating text to numbers is called the ASCII code (American Standard Code for
Information Interchange). The ASCII code associates with each number from 0 through 255 a
displayable or control character, although window cannot display all 255 ASCII characters and uses a
more limited set of characters called the ANSI (American National Standard Institute).
The value of the function Chr(n) is the string consisting of the character of ASCII value n. This
statement
Print Chr(n)
either displays the character numbered n in the ASCII sequence for the font currently in use.
Example: Print Chr (227) ‘Prints the Greek letter (pi) on the screen.
The following code uses the ASCII/ANSI value for the quotation mark, 34, to display a sentence
surrounded with quotation marks.
Print Chr(34)
Print “Welcome to Jairam College”
Print Chr(34)
The Chr function returns a string stored in a Variant. The output of above code is
“Welcome to Jairam College”
The VB also has 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.
Built-in String Constants:
The VB consists of various Built-in string constants. They are:
Character Symbolic Constants
Null Character vbNullChar
Carriage return vbCr
Line feed vbLf
Backspace vbBack
Tab vbTab
Vertical tab vbVerticalTab
Form feed vbFormFeed
Carriage return and form feed vbCrLf
Example:
You can force a break in a message box by setting up the message string using the vbCrLf constant as
shown below:
41
Message$=”Welcome to”
Message=Message$ & vbCrLf & “Jairam College”
MsgBox Message$
Fixed-Length Strings:
It is a special type of string; these variables are created with a DIM statement.
Example:
Dim x As String *20 Fixed-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).
MORE ON NUMBERS
Explain About More On Numbers. (10 Marks)
Discuss About Precedence Of Arithmetic Expressions With Example. (5 Marks)
How VB Treats Numbers Of Different Data Types. (5 Marks)
List Out the Conversion Function In VB. (2 Marks)
To assign a value to a numeric variable in VB, you cannot use a comma to delineate thousand. If use a
decimal point, but we can assign such a number to an integer or long integer, it will automatically be
rounded to an integer value.
The Numeric Operators:
Operator Operation
+ Addition
- Subtraction
/ Division
* Multiplication
^ Exponentiation
\ Integer division
Mod The remainder after integer division
The ordinary division symbol / gives the value that is single-precision, double precision, or currency
answer, depending on the object involved. The backslash throws the remainder value and gives the
integer. Example: 7\3=2
The mod operator provides the remainder after integer division (7 mod 3) =1. When one integer
perfectly divides another the mod operator gives zero (8 mod 2=0).
The combination of numbers, variables, and operators from which VB can extract a value is a numeric
expression.
Parenthesis and Precedence:
An arithmetic expression without any parenthesis will be evaluated from left to right using the rules of
precedence of operators. The following list gives the order (hierarchy) of operations:
Exponentiation(^)
Negation
Multiplication and division
Integer division
Remainder (Mod) function
Addition and subtraction
Example:
Expression: 4*2+16/8+2^3^4
Step 1: 4*2+16/8+8^4
Step 2: 4*2+16/8+4096
Step 3: 8+2+4096
Answer: 4106
Arithmetic on Date Variables:
VB makes it easy to do calculations with date variables.
Example: Dim a As Date
a=Now ‘Gives current day and time
Print a
42
Print a-1000
How VB Treats Numbers of Different Data Types:
When the user assigns a variable or value of one type to a variable of a different type, VB does a type
conversion if in can; otherwise it generates an error at run time.
The below code displays the error message
Dim a as Integer, b as Long
b=1234567
a=b
because the information b is too long to fit into an integer variable. The above code will be rewrite as
Dim a as Integer, b as Long
b=123
a=b
When the user use numbers in the program and do not assign them to a variable of the variant type, VB
assumes the following:
o If a number has no decimal point and is in the range -32,768 to 32,767 it’s an integer.
o If a number has no decimal point and is in the range for a long integer.
o If a number has a decimal point and is in the range for single-precision number, it is assumed to
be single precision.
o If a number has a decimal point and is outside the range for a single-precision number, it is
assumed to be double precision.
Type Conversions:
The process of converting one data type to another is called casting. Use built-in function to force a type
conversion from one variable to another-if the values stored are compatible.
VB will only do a conversion to a numeric type if the result will be in the permitted range for the target
type or if the string is really a number represented in numerals.
The below conversion function used to convert either a string of numerals to a number or to convert
from one type of variable to another.
Conversion Function Meaning
CInt Converts to an integer
CLng Converts to a long integer
CSng Converts to single precision
CDbl Converts to a double precision
CCur Converts to the currency type
The Val function:
This function is used to convert a numeric string to a number. It simply reads through the string until it
encounters a non-numeric character. The number you get from it is determined by where it stopped
searching.
Example: Val(“30something”)=30
Converting Numbers Back to Strings:
Using Str function, convert a number to a string. The Str and Str$ functions convert numbers to strings
but don’t clean them up in any way.
Example:
Str(143)=”123”
Str(143.456)=”143.456”
Evil Type Conversions II:
Conversion from strings of numerals to numbers. VB’s evil type coercion facility occasionally makes
this neat feature dangerous.
Example:
Dim a As Integer, b as String
a=2
b=”1,234”
a=a*b ‘bug
Print a
NUMBER IN VISUAL BASIC
Bits, Bytes, and Hexadecimal (Base 16) number in Visual Basic:
43
The color properties by hexadecimal format base 16. The binary digit contains base 2. Eight bits form a
byte, and half a byte forms a nibble.
Binary Decimal
0 0
1 1
10 2
11 3
100 4
101 5
To convert binary numbers to hexadecimal format, group of digits from right to left in groups of four
and convert.
Example: 11010111 (1101 0111, in two groups of four) is hexadecimal D7:1101 is 13 in decimal
format and D in hexadecimal format and 0111 is 7 both decimal and hexadecimal formats.
Working with Colors:
The settings for the color properties are indicated by hexadecimal coding. Every color code in VB is
made up of six hexadecimal digit, from &H000000& to &HFFFFFF&.
Hex Color Code Color
&H0000FF& Maximum Red
&H00FF00& Maximum Green
&HFF0000& Maximum Blue
To change color settings directly by
o Move to the properties window, and select Backcolor and Forecolor.
o Decide the color
o Enter the appropriate hexadecimal code
CONSTANTS
Explain About Constants With Example. (5 Marks)
What Is Constant? (2 Marks)
The values do not change throughout the execution of an application is called constant. It is also used
for storing values like variables.
Creating our own Constants:
Syntax:
[Public|Private] Const constantname [As type] =expression
The constantname should be a valid name.
As type is the data type.
The expression is the numeric or string value that has to be assigned to the constant.
Example: Const pi=3.14
Scope of the Constant:
The constants are declared in the declaration section of the form, standard, or class module. It also
declared by public keyword. (Accessed throughout the application).
It also declared by with in procedure (Accessed only the procedure).
THE SUPPLIED CONSTANT FILE:
The VB comes with hundreds of useful constants for working with the
built-in functions, objects, and methods.
The built-in constants are available for pasting into the code window
from the object browser. The Object Browser pops up when you press F2
or choose Object Browser from the view menu.(ALT+V+O)
To paste a constant into your code from the Object Browser:
o Make sure the cursor is where you want the constant to appear in
the code window.
o Click on the Copy to Clipboard button in the Object Browser (the third button in the first line)
o Go to where you want the constant in your code and press CTRL+V
INPUT BOXES
44
45
Fonts in which all characters are the same width are called non-proportionally spaced fonts; fonts where
characters may be different widths are called proportionally spaced fonts. Courier New is the most
common non-proportionally spaced font and Arial is a common proportionally spaced font. Most fonts
in Windows are proportional.
The VB always reports the current position as the values of two properties of the form or picture box:
CurrentX and CurrentY.
CurrentX refers to the horizontal position where VB will display the information.
CurrentY refers to the vertical position where it will display the information.
If you change the value of these properties, you change where the next Print statement will display its
information. The CurrentX position to be 100, all text will start 100 pixels over from the left side of the
form.
Example:
FormName.CurrentX=Value
FormName.CurrentY=Value
Whenever you use the Cls method to clear a form, VB resets the CurrentX and CurrentY values to zero.
After clearing the form using the Cls method, the next Print statement puts information in the top left
corner. Using the above property we cannot specify how much space a character or string in taking up,
so we can use the following built-in methods.
TextWidth
TextHeight
The syntax for the TextWidth method is
FormName.TextWidth(string)
after processing this statement, VB returns the value for the width of the string inside the parentheses,
using the current font and reporting the results in the current scale.
The syntax for the TextHeight method is
FormName.TextHeight(string)
this gives the height of the string inside the parentheses. The TextHeight is used to determine the
amount of vertical space and TextWidth and amount of horizontal space you need to display a string.
Suppose you want to display information at the beginning of the tenth line of text as it would appear in
the ordinary coordinate system.
CurrentY=Me.TextHeight(“I”)*9
CurrentX=0
Example: Centering Text Inside a Form:
To display a message in the exact center of a form by using the following steps:
o Find the current value of the ScaleHeight and ScaleWidth properties.
o Divide these values in half.
o Find the value of the ScaleLeft and ScaleTop properties for the form.
o Add the results from step 2 to the values from step 3. This gives you the coordinates of the
exact center of the form.
o Use the TextWidth method on the string you want to center.
o Subtract half the value VB obtains form step 5 from the value in step 4, and make this the
value of CurrentX.
o Similarly, subtract half Me.TextHeight(string) from the value of CurrentY obtained in step 5.
Example:
Private Sub Form_Resize()
Dim message As String
Dim w As Integer
Dim h As Integer
Dim l As Integer, t As Integer
Cls
message = "welcome to Visual Basic!"
l = Me.ScaleWidth / 2
t = Me.ScaleHeight / 2
46
l = Me.ScaleLeft + l
t = Me.ScaleTop + t
w = Me.TextWidth(message) / 2
h = Me.TextWidth(message) / 2
CurrentX = l - w
CurrentY = t - h
Print message
End Sub
The Font Properties in Code:
To assign a font name in code, place the name in quotation marks on the right-hand side of an
assignment statement using the Name property of the Font object:
o ObjectName.Font.Name=”Courier New”
o Object.Font.Name=”Arial”
You can change all the properties of the Font object via code. Except for Font.Size, they are all Boolean
properties. (True or False)
o ObjectName.Font.Size=18
o ObjectName.Font.Bold=True
o ObjectName.Font.Italic=True
o ObjectName.Font.Underline=False
Displaying Tabular Data in a Non-proportionally Spaced Font:
The Print Zones are always set 14 columns. The VB recalculates this distance depending on the font
characteristics in effect.
Each time you use a comma in a Print method, VB displays the data to the next print zone.
Example:
Me.Print FirstName$,MiddleInit$,LastName$
tries to have the value of the string variable FirstName$ printed in the first zone, the value of the
variable MiddleInit$ at the beginning of the SecondZone, and the value of the variable LastName$
printed at the beginning of the third zone.
The Tab and Spc Commands and Semicolons:
Normally, after VB processes a statement involving the Print method, it moves to the next line.
CurrentY increases by the height of the current font and CurrentX is set back to zero. You can also use
an empty Print statement to add a blank line.
If you want to suppress the automatic carriage return and line feed, place a semicolon at the end of the
statement.
Private Sub Form_Load()
Show
Me.Font.Name = "Courier"
Me.Print "welcome to"
Me.Print "Jairam college"
Me.Print
Me.Print "welcome to"
Me.Print "Jairam college"
Me.Print
End Sub
The Tab function lets you move to a specific column and start
printing there.
Syntax:
Print Tab(ColumnNumber%);
ColumnNumber% is an integral expression. If the current column position is greater than its value, Tab
skips to this column on the next line. If the value is less than 1, VB moves to the first column.
The Spc function has a syntax similar to the Tab function:
Spc(Integer%)
this function inserts the specified number of spaces into a line, starting at the current print position and
using spaces the width of an average character. The value inside the parenthesis can’t be negative.
(Unit – II to be Continued…)
47
(UNIT-II Continued…)
THE FORMAT (Form) FUNCTIONS
Explain about the format function. (5 Marks)
Write down the syntax for format function. (2 Marks)
Discuss about predefined format strings. (5 Marks)
The format function works with number and a template also called a format string. The syntax is
Format(NumericExpression, FormatString$)
Example:
Me.Print Format(123.456789,”###.##”)
The above statement yields a string “123.46” that will be printed on the form.
Example:
Me.Print “The interest rate is “&Format(payment,”####.##”)
The above statement the extra space after the work “is” is essential because it does not leave the space
for an implied +sign in front of the number.
A # is the placeholder for a digit, except that leading and trailing zeros are ignored.
Example:
Me.Print Format(123.450,”###.###”)
The above statement yields 123.45
If you want to have display leading and trailing zeros, use a zero in place of the # in the format string.
Example:
Me.Print Format(123.450,”000.000”) Yields 123.450
Me.Print Format(123.450,”0000.000”) Yields 0123.450
To display number with commas every three digits. For this place a comma between any two-digit
placeholder.
Example:
M$=”Your balance is” &Format(balance, “$###.##”)
If you need to display a symbol, such as -,+,$, or a space, you use it in the format string exactly in the
place you want it to occur.
Predefined Format Strings:
Visual Basic makes it even easier to deal with the most common formatting situations by adding what
are called named formats to the Format function.
Example:
Me.Print Format(Amount, “Currency”)
instead of
Me.Print Format(Amount,”###,###.##”)
this is because the Currency named format is defined to be the same as ###,###.##
Name of Format Description
General Number Gives you a string of digits with no thousands separator.
Currency Uses the appropriate thousands separator and displays two digits to the right of the decimal point.
Fixed Displays at least one digit to the left and two digits to the right of the decimal point.
Standard Uses the appropriate thousands separator, and at least one digit to the left and two digits to the
right of the decimal point.
Percent Gives you the number in percentage form. Always displays two digits to the right of the decimal
point.
Scientific Uses Visual Basic’s version of scientific notation.
Yes/No Displays No if the number is 0; otherwise, displays Yes
True/False Displays False if the number is 0; otherwise, displays True
On/Off Displays Off if the number is 0; otherwise display On
48
The following table gives you the various formats for date and times.
Name of Format Description
General Date Displays a date and/or time. If there is no fractional part, you get a date. If there is no integer part,
you get a time. If there are both, you get both.
Long Date Displays a date using the format that windows uses for full dates.
Medium Date Displays a date using the middle date format.
Short Date Displays a date using the short date format.
Long Time Displays a time with the hours, minutes, and seconds.
Medium Time Displays time in 12-hour, format using only hours and minutes and AM/PM.
Short Time Displays the time using a 24-hour clock.
Example:
Private Sub Form_Load() Output:
Show
Me.Font.Size = 12
Me.Print Format(Now, "General Date")
Me.Print Format(Now, "Long Date")
Me.Print Format(Now, "Medium Date")
Me.Print Format(Now, "Short Date")
Me.Print Format(Now, "Long Time")
Me.Print Format(Now, "Medium Time")
Me.Print Format(Now, "Short Time")
End Sub
PICTURE BOXES
Explain about picture boxes. (5 Marks)
Using picture box we can display icons, gifs, jpges, bitmaps, and Windows metafiles. It responds to the
Click and Double-click events. It is also called as “forms within forms”.
Example:
It have CurrentX and CurrentY properties as well as the same Scale properties as forms,
so you can accurately position text inside them.
You can mix fonts and font sizes when you print to a picture box.
You can add controls to a picture box by working with the toolbox in the same way that
you would add controls to a form.
The main difference between picture and forms is that you use the Height and Width properties of the
picture box rather than the ScaleHeight and ScaleWidth properties of the form.
Example:
Picture1.CurrentX=Picture1.Height/2-TextHeight(“A”)/2
The main advantages to using a picture box rather than a form to display data are that
Information displayed in a picture box will not be obscured by any controls on the form.
It takes less memory.
You can have more than one picture box on a single form.
Working with picture boxes:
Picture boxes have 50 properties and respond to 19 events. Example: Font, Visible, Enabled, and so on.
If AutoSize is True, the picture box will automatically resize itself to fit the image. The Cls method
works in much the same way for picture boxes as it does for forms: it erases whatever image and text
were placed in the picture box while the program was running and resets the CurrentX and CurrentY
properties.
The Move method lets you move the picture box around at run time. The TextHeight and TextWidth
methods are used, as with forms, to accurately size text in order to position it better.
There are two ways to display an image inside a picture box (or form) at design time.
To load a picture by setting the Picture property via the Properties window.
To paste a picture directly into the picture box.
To add a picture at run time by two ways:
To assign the Picture property of one object to the Picture property of the other.
Example: Picture2.Picture=Picture1.Picture
Copies the image from the first picture box to the second.
49
Use LoadPicture function to attach a file containing a graphical image to a picture box at run time. The
Syntax for this function is
PictureBoxName.Picture=LoadPicture([filename])
(Or) for forms
[FormName.]picture=LoadPicture([filename])
If you leave out the optional filename, the current image is cleared from the form or picture box. The
filename should include the full path name if the file isn’t in the current directory. The LoadPicture
statement without a filename will also clear a picture that was added at design time.
50
51
DETERMINATION LOOPS
52
53
INDETERMINATE LOOPS
What is indeterminate loop? (2 Marks)
Explain about various forms of do…loop statement. (10 Marks)
Repeating an operation until you reach a predetermined specific goal or until certain initial conditions
have finally changed is called indeterminate loop.
Relational operators
These operators are used to check conditions
Symbols Checks (Tests for)
<> Not equal to
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
Looping Statements:
Do… Loop:
It is used to repeat the execution of a block of statements based on the condition.
Do
Visual Basic Statements
Until condition is met
Sophisticated Indeterminate Loops
VB provides solution to complicated looping statements.consider the
following example:
Dim Namecount
Namecount = 0
Entry$ = InputBox$("Namo - ZZZ to end")
Do Until Entry$ = "ZZZ"
Namecount = Namecount + 1
Entry$ = InputBox$("Namo - ZZZ to end")
Loop
Now the user types the first name before the loop starts. Once this is done,
the program does an initial test.
The loop is entered and 1 starts being added to the counter only if this test
fails. (Notice that this kind of loop also works if there is nothing in the list
except the flag.) Figure shows a picture of what Visual Basic does for this
type of loop.
The Do While Loop
Visual Basic has other kinds of loops. These loops consist of replacing the keyword Until with the
keyword While.
This new loop may seem superfluous since you can always change a Do Until into a Do While by
reversing the relational operator.
For example:
Do
Loop Until X$ <> “ ”
is the same as
DO
Loop While X$ = “ ”
and
DO
Loop Until Number > 5
is the same as
Do
54
Example:
Private Sub Command3_Click()
Dim c As Integer
Do Until (c > 10)
Print c
c=c+1
Loop
End Sub
Syntax IV:
Do
<Statements>
Loop Until (Condition)
It executes the statements and then tests the condition. The loop will be executed at least once and then
tests the condition. It executes till the condition is false.
Example 1:
Private Sub Command4_Click ()
Dim i As Integer
Do
Print i
i=i+1
Loop Until (i > 10)
55
End Sub
Example 2:
Private Sub Command5_Click()
Do
n$ = InputBox("non-zero number? please!")
Number = Val(n$)
Loop Until Number <> 0
End Sub
Example 3:
Private Sub Command6_Click()
Total=0
PassNumber=0
Do
Total=Total+0.1
PassNumber=PassNumber+1
Print PassNumber,Total
Loop Until Total=1
End Sub
Do Loop with And,Or,Not
These loops are used to combine two conditions. This is most commonly done with And, or and Not
keyword. For example suppose you want to continue a process while a number is greater than zero and a
text box is empty. it’s much easier to say
Example:
Do While Number > 0 And Text1.Text = “”
Than to say
Do Until Number <= 0 And Text1.Text <> “”
While…Wend Loop
This Loop structure allows performing a series of steps based on a condition.
Syntax: While < condition>
< Statements>
Wend
The condition is evaluated first. If it is true, the statements in the block are executed. When the Wend
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 is true.
Example:
Private Sub Command5_Click()
Dim i As Integer
While (i <= 10)
Print i
i=i+1
Wend
End Sub
MAKING DECISIONS
Explain about decision making statements. (10 Marks)
Explain about the various control structures in VB. (10 Marks)
A program is a set of statements that are normally executed sequentially in the order in which they
appear. To change the order of execution of statements based on certain conditions.
The Visual Basic supports the following Control Statement or Decision Making Statements:
Simple-If
If-Else
Else-If Ladder
Nesting of If…Else
Select Case
Simple-If:
It is a powerful decision making statement, used to control the flow of execution of statement.
56
Syntax:
If <condition> Then
<Statement>
End If
Example 1:
Private Sub Command1_Click()
If Val (Text1.Text) <=10 Then
MsgBox "Hello"
MsgBox Text1.Text
End If
End Sub
Example 2:
You can use an If-Then to determine which button was pressed in a message box. Assign the values of
the MsgBox function to a variable and then use If-Then to check the value.
Private Sub Command2_Click()
x = MsgBox("Yes/No", vbYesNo)
If x = vbYes Then
Print "yes button clicked"
End If
End Sub
The Else: ( If Else)
It 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 If
Example:
Private Sub Command3_Click ()
If Val (Text1.Text) >=5 Then
Text1.Text = Text1.Text * 5
Else
Text1.Text = Text1.Text + 5
End If
End Sub
Combining conditions
Combining conditions in an If-Then:
You can also use the keywords And, Or, and Not in an If-Then.
Example:
Private Sub Command4_Click()
If Val(Text1.Text) >= 5 And Val(Text2.Text = 2) Then
Text1.Text = Text1.Text * 5
Else
Text2.Text = Text2.Text + 5
End If
End Sub
The Block If-Then
To process multiple statements if a condition is True or False is called as Block If-Then structure.
Syntax:
If <condition> Then
<Lots of statements>
Else
57
<More statements>
End If
Example 1:
Private Sub Command5_Click()
If Val(Text1.Text) >= 10 Then
Text1.Text = Text1.Text * 2
MsgBox Text1.Text
Text1.Text = Text1.Text * 5
MsgBox Text1.Text
Else
Text1.Text = Text1.Text * 3
MsgBox Text1.Text
End If
End Sub
Example 2:
You can easily use If-Then to determine whether the user has entered a string in the form of a date or a
number. The procedure depends on the variant data type combined with two new Boolean functions.
(functions that return either True or False)
Private Sub Command6_Click()
Dim dt
dt = Text1.Text
If IsDate(dt) Then
MsgBox dt
Else
MsgBox "please enter the text in the form of a date!"
End If
End Sub
The IsNumeric function to determine whether the variable can be converted to a number.
Private Sub Command7_Click()
Dim nt
nt = Text1.Text
If IsNumeric(nt) Then
MsgBox nt
Else
MsgBox "Enter numeric number"
End If
End Sub
Example 3:
To find whether a file or files exist with a specific extension. The functions needed are:
Dir$(filespec) or Dir(filespec)
The difference between the two is that Dir$ returns a string and Dir returns a string stored in a variant.
Filespec is a string expression that contains the filename or file pattern- it is not case sensitive.
Private Sub Command8_Click()
x$ = Dir$("*.exe")
If x$ = "" Then
Print "no text files found"
Else
Print "first file found is "; x$
End If
End Sub
The above code checks whether the current directory contains any .Txt files.
Combining the If-Then with Loop
We can also use the control statement within the loop structure.
Else-If Ladder:
58
There is another way of putting ifs together when multipath decisions are involved. A multipath
decision is a chain of ifs in which the statement associated with each else is an if.
Syntax:
If <condition> Then
<Statement-1>
ElseIf <condition> Then
<Statement-2>
ElseIf<condition> Then
<Statement-3>
Else
<Statement-4>
End If
Example:
Private Sub Command9_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 Then
Grade = "First"
MsgBox Grade
ElseIf marks > 49 Then
Grade = "Second"
MsgBox Grade
Else
Grade = "Fail"
MsgBox Grade
End If
End Sub
In the above example 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.
SELECT CASE
Explain about select case with example. (5 Marks)
Select Case…End Select:
It is used when the program has to execute one of several groups of statement, depending on the value
of an expression.
Syntax:
Select Case testexpression
[Case expression list-1
statement-1]]
[Case expression list-2
statement-2]]
.
.
.
[Case Else
[else statements]]
End Select
The test expression is an integer expression or characters. The expression list are constant or constant
expressions and known as case labels.
59
The select case statement tests the value of a given expression against a list and when a match is found,
a block of statements associated with that case is executed.
If more than one case expression matches with the test expression, the statements of the first case only
are executed. The case else is executed when if no match is found between the test expression and the
case expression.
Example1:
Private Sub Command10_Click()
Dim b As Integer
b = Val (Text1.Text) / 2
Select Case b
Case 10
MsgBox "good"
Case 8
MsgBox "not good"
Case 6
MsgBox "ok"
Case Else
MsgBox "bad"
End Select
End Sub
Example2:
Private Sub Command11_Click()
Dim a As Integer
a = Val (Text1.Text) / 2
Select Case a
Case Is <= 5
MsgBox "ok"
Case Is > 10
MsgBox “good"
Case Else
MsgBox “Default”
End Select
End Sub
NESTED IF-THEN’S
Explain About Nested If-Then’s With Example. (5 Marks)
When a series of decisions are involved, use 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
Example:
Private Sub Command12_Click ()
If Val (Text1.Text) >= 15 Then
If Val (Text2.Text) < 15 Then
Text2.Text = Text2.Text + 7
Else
Text2.Text = Text2.Text + 5
End If
Else
60
Text1.Text = Text1.Text + 7
End If
End Sub
In the above example condition-1 is false, the Statement-4 will be executed, and 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.
THE GOTO
Explain about GOTO statement with example. (2 Marks)
VB retains the unconditional jump or GOTO. It is used to transfer control from one place to another
place in a program. It leads to spaghetti code: code that is hard to read and harder to debug. To use a
GoTo in VB, you must label a line. Labels must begin with a letter and end with a colon. They must also
start in the first column.
Example:
Private Sub Command1_Click()
a = InputBox("Enter the value")
If a = 10 Then
GoTo a
MsgBox a
a: Print a
End If
End Sub
STRING FUNCTIONS
Explain about string functions. (10 marks)
How can we find the length of a string? (2 marks)
What is the use of mid function? (2 marks)
Write a program to find the number of periods In a string (5 marks)
Discuss about instr, instrrev function. (5 marks)
A built-in function is a prepackaged piece of code that accomplishes a single task. The VB consists of
various built-in functions.
String Functions:
A string is a collection of characters. The VB consists of powerful string-handling functions. The
information in VB text boxes is usually kept as strings or strings contained in variants, string functions
are far more important in VB in many other programming languages.
To build up a string of spaces or a string of repeated characters. The function
Space(NumberOfSpaces)
gives you a string consisting of only spaces, with the number of spaces determined by the value inside
the parentheses. The function
String(Number, StringExpression$)
where Number specifies the number of times the characters are repeated. The StringExpression specifies
the characters to be repeated. You can also use the extended ASCII/ANSI code in the second position.
Example:
X$=String(10,”a”)
X$=String(10,”abaayvs” ‘ only first character is used.
X$=String(10,22) ‘122=Asc(“Z”)
The Trim function (Trim$) removes spaces from both the left and right ends of a strings. The
LTrim(LTrim$) removes spaces from the left end, and RTrim(RTrim$)removes spaces form the right.
Example:
A$=” Jairam college “
T=Trim$(A$)
The LCase(LCase$)function forces all the characters in a string to be lowercase. Similarly,
UCase(UCase$) switches all the characters in a string to uppercase.
Example:
A$=”Jairam college“
B$=UCase$(A$)
61
The second position controls where the change will start, and the third position controls how many
letters to put out from the string on the right-hand side of the equals sign.
Example:
Mid(S$, 1, 5) =”QuickBasic by Microsoft”
gives the same result as before.
If the right-hand side has fewer characters than the number given in the third position of the left-hand
side demands, VB changes as many characters as occur on the right-hand side.
Example:
Mid(S$, 1, 5) =”VB”
` gives S$ the value “VBwerBasic”. The mid statement makes changes within a string but never
changes the length of the original string. You can leave out the last position, for example
Mid (“In the beginning “, 8) =”middle was”
Changes the string to
“In the middle was”
The InStr Function
This function tells you whether a string is part of another string. It also tells you the position at which
the substring starts.
Syntax:
InStr ([where to start,] start to search, string to find)
The optional first position specifies from which position to start the search. If you leave this entry out,
the search automatically starts from the first position.
Example:
Pharse$=”QuickBasic was Visual Basic’s distant ancestor”
X%=InStr (1, phrase$,”BASIC”)
the value of X% is 6, starting at the sixth position.
The visual basic is search the string starting from the first position until it finds the substring. If it
doesn’t find the string, it gives back a value of 0.
Example:
X%=InStr(1,pharse$,”basic”)
the value of X% is 0. The InStr function defaults to being case sensitive.
Syntax 2:
InStr([start, ]string1,string2[,compare])
where the compare parameter specifies the type of string comparison. If you set it to 0 then the
comparison is case sensitive regardless of the current setting of Option Compare. If you use the built-in
constant vbTextCompare, you get a case-insensitive comparison again.
Example:
X%=InStr(1, phrase$, “basic”, vbTextCompare)
will always give you the value 6.
The InStrRev Function:
The VB 6 adds an InStrRev function that starts searching from the back end of the string.
Syntax:
InStrRev(OriginalString, Substring[, Start[,Compare]])
The Compare option same as InStr function. One common use of InStrRev would be to check the
extension at the end of a filename that a user typed.
Example:
Dim TestFileName As String, Location As Long
TestFileName=”Full.Extension.html”
Location=InStrRev(TestFileName, “.”)
MsgBox “Your extension is “&Mid(TestFileName, Location)
The Nifty (New) Replace Function:
This function is used to search and replacement tasks. Suppose you want to change the string
“JavaScript is the best Scripting Language”
To read
“VBScript is the best Scripting Language”
63
Example 1:
TestString$=”JavaScript is the best Scripting Language”
TestString$=Replace(TestString$, “JavaScript”, “VBScript”)
Example 2:
S$=”Java is the best programming language”
K$=Replace(S$, “Java”, “Visual Basic”)
Other Uses for the Replace Function:
Syntax:
Replace(Expression,Find,ReplaceWith[, Start][,Count][, Compare]]])
The optional Start parameter lets you tell VB the position at which to start looking for the string that
needs to be replaced.
The count parameter specifies the number of times you want to do the substitution if these are multiple
copies of the same string inside the original string.
If you omit this parameter the default behavior of Replace is to replace all occurrences of the string.
Example:
TestString=”AAAAAA”
TestString=Replace(TestString,”A”,”Z”,1,1) ZAAAAA
the Compare parameter case-insensitive replacements by using the constant vbCompareText.
If you use the empty string as your ReplaceWith value, you will remove the substring from the original
string.
Example:
S=Replace(“1-800-555-1212”,”_”, VbNullString)
gives “18005551212”
The following table summarizes the results from this and other special situations in the Replace
If Resulting String
The original sting is the empty string An empty string (“ “)
The string that you want to replace is an empty string The original string
The Start parameter is greater than the length of the original string An empty string
The Count parameter is 0 The original string
The original string is null An error
function:
64
where the optional second parameter allows you to round past the decimal point. If you leave it off, you
get an integer.
Example:
Round(3.7) 4
Round(3.786, 2) 3.79
Other Useful Numeric Functions:
The additional numeric functions used to perform the mathematical or engineering type calculations.
Sign():
This function gives you a +1 if what is inside the parentheses is positive, -1 if negative, and a 0 if its
zero.
Example:
Sgn(-5) -1
Sgn(5) 1
Sgn(0) 0
Abs():
It gives the absolute value of whatever is inside the parentheses.
Example: Abs(-1) =1=Abs(1)
Sqr():
This function return the square root of the numeric expression inside the parentheses, which must be
non-negative or a run-time error follows.
Example: Sqr(4)
Exp():
This function gives e (e is roughly 2.7182) to the power x, where e is the base for natural logarithms,
and x is the value in the parentheses. The answer is single precision if x is an integer or is itself a single-
precision number; otherwise, the answer is a double-precision number.
Log():
The log function gives the natural logarithm of a number. To find the common log (log to base 10) use
Log10(x)=Log(x)/Log(10)
Function Result
this gives the common logarithm of the
value inside the e=Exp(1#) Value of e in double precision parentheses.
Trig Functions: Log 10(X) Log(X)/Log(10)
The VB has the Log a(X) Log(X)/Log(a) built-in trigonometric
function Sin(sine), Cot(X) 1/Tan(X) Cos(cosine), and
Tan(tangent). The Sec(X) 1/Cos(X) only problem is that VB
expects the angle inside the parentheses following the functions to be in radian measure.
To convert from degrees to radians, you need the value of π. The formula is
radians=degrees* π/180
The following table provides the inverse trigonometric functions.
FINANCIAL FUNCTIONS
Explain about financial functions. (5 Marks)
The VB comes with a library of financial functions for handling standard calculations that everyone will
occasionally need to do.
The Pmt function returns the payment for an annuity based on periodic, constant payments and a
constant interest rate. The annuity is a term for a series of payments made overtime.
Example:
66
When you have a mortgage, you start out with a (large) amount, make (many) payments over
time, and end up with a zero balance.
Syntax:
Pmt(RatePerPeriod,NumPeriods,WhatYouStartWith,WhatYouEndUpWith,WhenDoYouPay)
Example: X=Pmt (.08/12, 30*12, 100000, 0, 1)
RatePerPeriod Usually the interest rate is quoted per year.
NumPeriods This is the number of periods.
WhatYouStartWith In a mortgage, this would start out as the balance(Initial balance)
WhatYouEndUpWith In a mortgage, this would be zero.
WhenDoYouPay Do you pay at the beginning of the period or at the end. Use a 0 for the
end of the month and a 1 for the beginning.
Other Financial Functions:
FV:This function returns the future value of annuity based on periodic payments and a constant interest
rate.
Syntax: FV (rate, nper, pmt [, pv [, type]])
(OR)
FV(InterestRatePerPeriod,NumPeriods,PaymentPerPeriod[,StartAmount[, WhenDue]])
Example: Retirement calculation
For all financial functions, moneys paid out will be given by negative numbers; moneys received are given
by positive numbers.
IPMT: This function gives the interest paid over a given period of an annuity based on periodic, equal
payments and a constant interest rate.
Syntax: IPMT(rate,per,nper,pv,fv,due)
Where rate is the interest rate per period, and per is the period in the range 1 through the number of periods
(nper).
Example:The interest paid in first month of the third year of a 30-year $100,000 mortgage at 8 percent is
IPMT(.08/12,25,360,100000,0,1)
NPer:This function tells you how long it will take to accumulate an annuity.
Syntax: NPer(rate,pmt,pv,fv,due)
Example: Suppose you are getting 5 percent on your money and you have $100,000 in the bank. To
calculate how long it would take to spend the $100,000 that you have saved if you withdraw the money at
a rate of $1,000 a month, use
NPer(.05/12,-1000,100000,0,1)
PV:This function tells you how much periodic payments made over the future are worth now. (The
technical term for this is present value)
Syntax:
PV(rate,nper,pmt,fv,due)
The rate is the interest rate per period, nper is the total number of payments, pmt is the number of
payment made each period and fv entry is the future value or cash balance you want after you’ve
received the final payment.
Example: PV(.06/12,120,-1000,0,1)
NPV:This is the net present value function. This function is used when you start out by paying money as
startup costs but then get money is succeeding years.
Syntax:
NPV(RatePerPeriod, ArrayOf())
To fill the array with the appropriate values in the correct order. The first entry could be negative
number representing startup costs and the remaining entries a positive number representing value
received. At least one entry must be positive and one entry must be negative.
Rate: This function gives the interest rate per period for an annuity.
Syntax:
Rate(nper,pmt,pv,fv,due,guess)
The Remaining Financial Functions:
SLN and DDB: These functions return the straight line and double declining balance depreciation of an
asset over a given period.
Syntaxes: SLN(Cost,SalvageValue,LifeExpectancy)
67
and
DDB(Cost,SalvageValue,LifeExpectancy,PeriodOfCalculation)
IRR and MIRR: The IRR gives the ordinary internal rate of return, and MIRR gives the modified rate in
which you allow payments and receipts to have different interest rate.
Syntaxes: IRR(ValueArray(),Guess)
and
MIRR(ValueArray(),FinanceRate,ReinvestRate)
The ValueArray() contains the receipts and disbursements and must contain at least one negative value
and one positive value. Start with a guess of 1 percent (.01)
||******************Unit – II Completed******************||
UNIT-III
FUNCTION PROCEDURES
Explain about function procedures. (10 Marks)
List out the two kinds of general procedures in VB. (2 Marks)
What is Function? (2 Marks)
What is a Sub Procedure? (2 Marks)
There are two kinds of general procedures in VB. They are:
Function Procedures
Sub Procedures
The function procedures, or user-defined functions, as a self-contained piece of code designed to
message data and return a value.
The sub procedures are smaller “helper programs” that are used called as needed. Sub procedures are
thus generalizations of the event procedures. Unlike functions, which normally return values,
procedures simply do things.
Both sub and function procedures perform the following:
Help you break down larger tasks into smaller ones.
Automate repeated operations.
Make it clearer what it is you are trying to accomplish by “naming” a piece of code.
All these features can dramatically reduce debugging time.
Function Procedures:
Defining your own functions when you use a complicated expression more than once in a project.
To generate a random integer between 1 and 10
ri=Int((10*Rnd)+1)
Suppose the same program needs a random integer between 1 and 40.
ri=Int((40*Rnd)+1)
Writing a Simple Functions
To add the function to the current form by
Open the code window by double-clicking anywhere in the form or by pressing F7.
Choose Tools | Add Procedure from the Tools menu. This pop up the Add procedure
dialog box.
68
Click the Function radio button and type a name for your function. [Example:
RandomRange]
Click on OK, and a function template for the form as shown in the following figure:
70
The following call statement to test will not produce any error message that is it works very fine.
Scope of Variables Used in Function Procedures:
The form-level variables are visible to all the functions attached to that form. Any variable dimmed
inside the body of a function procedure will be local to the procedure regardless of whether there is a
form-level variable with the same name.
The parameters of the function are automatically local; they don’t need a Dim statement.
Example:
Public Static Function AnExample(f As Integer) As Integer
Dim count As Integer
End Function
The variables f and count will have no relation to any other variables named f and count outside the
function.
In addition to local variables, you can also have static variables inside your functions. You can make
all the variables in a Function Procedure static by putting the keyword Static before the name of the
function.
Public Static FunctionName(parameter list)
Leaving Functions Prematurely:
Sometimes you are forced (or want) to exit a function prematurely; you can do this with the Exit
Function statement.
Example:
Public Function pre(x) As Single
If x < 0 Then
Exit Function
Else
Statements
End If
End Function
This function bails out if a negative value is sent to it. Calling the function with a negative value returns
a value of 0-the default value of any numeric variable.
Sub procedures
Explain about sub procedures with example. (5 Marks)
To define a Sub Procedure in much the same way you would with a Function Procedure. Use Tools|
Add Procedure. Now click the Sub option button.
The structure of the simplest kind of Sub Procedure is,
Public Sub proce()
‘Many print statements
End Sub
The first line of the Sub procedure is called the header. Next in the header is the keyword Sub followed
by the procedure’s name. Headers can have access specifiers. The name of the Sub procedure also must
follow the rules for variable names.
The parameter list, enclosed in parentheses, for the information the Sub Procedure will use. After the
header are the lines that contain the statements that make up the procedure. These statements are also
called the body. Finally, there are the keywords End Sub used to indicate the end of a general procedure.
You can call the Sub Procedure, by using the name of the procedure, followed by the arguments
(parameters), separated by commas if there are two or more:
NameOfProcedure Argument1, Argument2, ….
(OR)
Call NameOfProcedure(Argument1, Argument2,…)
71
You can use the Call keyword, you must use parentheses around the argument list; when you omit the
Call keyword, you must omit the parentheses.
If the parameter is not a variant, then any variables must be of the exact same type as the ones you
specified for the parameters.
Summary of how to Code and Use Sub Procedures:
A sub procedure is a part of a program that performs one or more related tasks, has its own name, is
written as a separate part of the program, and is accessed by using its name followed by the correct
number and type of parameters separated by commas. A sub procedure must have the form.
Sub SubProcedureName(parameter1, parameter2,…)
Statements
End Sub
Next, when VB executes statements of the form.
SubProcedureName(parameter1, parameter2,…) (OR)
Call SubProcedureName(parameter1, parameter2,….)
Example:
Sub ManyBeeps(X as Integer)
Dim I As Integer
For I=1 to X
Beep
Next I
End Sub
Since I is dimensioned inside the procedure, it is a local variable, now we can write:
ManyBeeps 10 (OR) Call ManyBeeps(10)
JAIRAM ARTS & SCIENCE COLLEGE, SALEM-08
STAFF ID: SCS86 CLASS: III B.Com (CA) ‘A’
SUBJECT: SOFTWARE DEVELOPMENT WITH DATE:
VISUAL PROGRAMMING
(UNIT-III Continued…)
ADVANCED USES OF PROCEDURES AND FUNCTIONS
Explain about the advanced uses of procedures and functions. (10 Marks)
Discuss About Passing By Reference And Passing By Value. (10 Marks)
Passing by Reference, Passing by Value:
There are actually two ways to pass arguments to a function variable as an argument. These are called:
1. Passing by reference
2. Passing by value
When you pass an argument variable by Reference, any changes to the corresponding parameter inside
the procedure will change the value of the original argument when the procedure finishes.
When you pass an argument by Value, then the original variable retains its original value after the
procedure terminates-regardless of what was done to the corresponding parameter inside the procedure.
Example:
Sub Triple(Num As Integer)
Num = 3 * Num
Print "I am in the Procedure (pass by reference) and "
Print "the parameter variable has value " & Num
Print
End Sub
Sub Form_Load()
Dim Amt As Integer
AutoRedraw = True
Amt = 2
Print "I am in the Form_Load and " & " the variable is now " & Amt
Print
Triple Amt
Print "I called the procedure and the variable " & " is now " & Amt
72
End Sub
So the value of Amt variable has been changed because only one memory location is involved for both
Amt and Num.
Now the previous Form_Load procedure with the key statement changed to Triple(Amt). So that the
variable Amt is passed by value because it is surrounded by parentheses.
This time two memory locations are involved one for Amt and another for Num. VB sets aside a second
temporary memory location for the parameter Num.
This location exists only for the procedure’s use and VB copies the value of Amt into this location.
After VB finishes processing the code in the procedure, Num’s temporary memory location is
reclaimed.
Since only the value in the temporary memory location (Num) was actually tripled, the value of the
original variable Amt remains the same as it was before we called the procedure.
When VB leaves any procedure, it releases the memory locations it had temporarily set aside for all
variables that were passed by value.
If some of the variables sent to a procedure or function never be passed by reference, you can specify
that they will only be passed by value. To do this, add the ByVal keyword before the parameter in the
argument list of the function or procedure.
Example:
Function Example(X As Integer, ByVal y As Single)
In this example, any integer variable passed to the parameter X may be passed by reference (the default)
or by value(when enclosed in parentheses), but any single-precision variable passed to the parameter Y
will always be passed by value, whether or not it is enclosed in parentheses.
Sub programs that have Optional Arguments:
VB permits you to have optional arguments in the functions and procedures you define yourself, just as
it does in some of its functions. Optional arguments can be of any type, but they must be the last
arguments in a function or procedure.
Example:
Sub ProcessAddress(Name As String, Address As String, Optional zipplus4 As String)
In the above example zipplus4 is optional. You can even provide a default value for any optional
argument.
Example:
Sub ProcessAddress(Name As String, Address As String, Optional zipplus4 As String=”0000”)
73
In this example, the value “0000” will be used when you don’t send a zipplus4 code to the procedure.
You can use the IsMissing Function to determine if a Variant Parameter is missing.
Syntax: IsMissing(argname)
The argname must contain the name of an optional variant procedure argument.
Sub ProcessName(FirstName As String, LastName As Variant)
If IsMissing(LastName) Then
MsgBox “we really need your middle initial!”
End If
End Sub
USING THE OBJECT BROWSER TO NAVIGATE AMONG YOUR SUBPROGRAMS
How can we navigate the subprograms using object browser? (5 Marks)
One of the easiest ways to navigate through the code in your project is with the Object Browser.
Steps:
1. Bring up the Object Browser
2. Choose your project by name from the libraries/projects list box.
3. Up to now all our projects have a single form and all the code is attached to that form. The name
of the form will be same as the value of the form’s name property and when you click on it, the
members(second) column of the Object Browser will show the procedures attached to that
form(including the event procedures) . Double-Click on the name of the subprogram whose code
you want to work with.
The easiest ways to hide the Object Browser is to right-click inside of it and then choose Hide from its
context menu. Supply the description of your procedures that can show up in the Object Browser.
To add these descriptions, you can work from the Code Window or the Object Browser itself. To work
from the Object Browser do the following steps:
1. Highlight the function or procedure you want to document.
2. Right click and choose properties from the Context menu that pops up.
3. In the Procedure attributes dialog box shown here, enter the description you want in the
Description text box.
74
You will often need a way to increase the size of a form-level dynamic array inside a function or
procedure without losing the information that is already in it. We can do this with a variation on the
ReDim command to ReDim Preserve.
Example: ReDim Preserve Errand (11) As String
in a function or procedure to increase the number of entries in the array Errand() to 11 without losing
the first 10 items. Similarly, the statement
ReDim Preserve Errand (9) As String
drops off the last entry in the Errand one-dimensional array but preserves all the others.
Local Arrays:
You use a local array when you want to keep the information hidden in a single function or procedure
and there by avoid side effects. To set up a local fixed array, simply use the Dim statement inside the
function or procedure with the size.
Example:
Private Sub ProcedureName()
Dim Errand(13) As String
End Sub
To set up a local dynamic array, use the appropriate ReDim statement in the function or procedure.
VB allocates space for that array only while the function or procedure is active and reclaims space as
soon as the function or procedure ends.
Private Sub ProcedureName()
Dim DynamicLocalArray() As String, Temp As Integer
Temp=CInt(InputBox(“How many items?”))
ReDim DynamicLocalArray(Temp) As String
….
End Sub
Static Arrays:
An array, whose contents remain the same no matter how often the function or procedure is used, is
usually called a static array.
To set up a static array inside a function or procedure, you use the Static keyword:
Private Function FunctionName () As String
Static Errand(13) As String
End Function
The information you store in a static array remains intact.
Some Ways of Working with One-Dimensional Arrays:
Values inside one-dimensional arrays are most often assigned by using a For-Next loop or, Do loop
Static Errand(29) As String
Index = 0
Do
NextErrand$ = InputBox("Enter the string")
If NextErrand$ <> "zzz" Then
Errand(Index) = NextErrand$
Index = Index + 1
End If
Loop Until Index = 30 Or NextErrand$ = "zzz"
NumberOfItems = Index
In the above example, the temporary variable, NextErrand$, is set up to hold the information before it is
added to the one-dimensional array.
Once you know the entry is acceptable, we fill in the entry and move the index up by one. This process
continues until the index becomes 30 or NextErrand$ is zzz.
The Erase Statement
VB allows you to reclaim the space used by a dynamically dimensioned array done with the Erase
statement.
Example: Erase Errand would erase the Errand array and free up the space it occupied.
76
If an array were not dimensioned dynamically the Erase command would simply reset all the entries
back to zero for numeric one-dimensional arrays, to the null string for string one-dimensional arrays,
and to null for variant one-dimensional array.
Using the Erase command on a fixed or static one-dimensional array gives a fast method to “zero out”
the entries. (It sets them to the null string for string arrays.)
One-Dimensional Arrays with Index Ranges
VB has a command that eliminates the zeroth entry in all one-dimensional arrays is done by the Option
Base 1 statement. This statement is used in the Declarations section of a form or module, and it affects
all one-dimensional arrays in the module.
All new one-dimensional arrays dimensioned in that form or module will begin with item 1. After
Option Base 1, Dim Errand$(30) sets aside 30 spots rather than 31.
Example: Dim SalesInYear(1980 To 1997)
The array will have 18 boxes labeled SalesInYear(1980), SalesInYear(1981),….SalesInYear(1997). The
keyword To marks the range to be used for the indexes. Put the smaller number first. You can use both
positive and negative long integers for the range.
Finally, you can always find out the lower index or upper index in an array by using the commands
LBound and UBound. LBound gives the lowest possible index and UBound the highest in a list.
Dim f (3 To 35)
Print “Lower bound of f is “ & LBound(f)
Print “Upper bound of f is “ & UBound(f)
Iterating Through Array Entries:
VB allows you two ways to construct a loop that iterates through all the elements in an array. The
fastest is to use the LBound and UBound functions in a loop:
Dim I As Integer
For I =LBound(AnArray) To UBound(AnArray)
…..
Next I
“For each” to walk through the items in an array. The format for a For-Each that works through the
items in an array looks like this:
Dim Item As Variant
For Each Item In AnArray
…..
Next
where the Item variable must be a variant. For-Each for an array is so much slower than using a For-
Next.
Assigning Arrays:
One of the more useful features added to VB6 is the ability to make array assignment. Suppose you
have a dynamic array called MyErrands and another called YourErrands that hold the same type of
information.
MyErrands=YourErrands
will automatically change the size of the dynamic array named MyErrands to be the size of the array
YourErrands and copy all the information from YourErrands into the corresponding slots in the
MyErrands array.
Example:
ReDim M(1 To 10) As String
Dim f(3 To 37) As String
Print “Lower Bound of M is “ & LBound(M)
Print “Upper Bound of M is “ & UBound(M)
M=f
Print “Lower Bound of M is now “ & LBound(M)
Print “Upper Bound of M is now “ & UBound(M)
The Array Function:
It is possible to store an array in a variant. This technique gives you a quick way to swap the contents of
two nondynamic arrays.
Example:
77
Dim i As Long
Dim a(1 To 20000) As Long
Dim b(1 To 20000) As Long
For i = 1 To 20000
a(i) = i
b(i) = 2 * i
Next i
Dim array1 As Variant, array2 As Variant, temp As Variant
array1 = a()
array2 = b()
temp = array1
array1 = array2
array2 = temp
Print "the third entry in array1 is now” & array1 (3)
If you want to create an array in a variant directly use the Array function.
Syntax: Array (arglist)
where the arglist argument consists of a list of items separated by commas.
Example:
Dim A As Variant
A=Array(1,2,3,4,5)
78
VB has an extraordinary facility for using lists and arrays in procedures and functions. Arrays are
always passed by reference.
This means any changes you make to the array or to the entries in the array will persist after VB leaves
the function or procedure.
The arrays passed by reference you don’t need to use form-level arrays unless you want the array to be
visible everywhere.
To send an array parameter to the procedure or function, just use the name of the array followed by
opening and closing parentheses in the list of parameters.
Example:
Private Sub Example(List#(), Array$(),BigArray%(), X%)
Where List# is a one-dimensional array of double-precision variables, Array$ is a two-dimensional
string array, and BigArray% is a three-dimensional array of integers.
The above example would allow the procedure to use a list of double-precision variables, an array of
strings, a three-dimensional array of integers, and a final integer variable. To call the procedure, you
might have a fragment like this:
Dim PopChange#(50), CityState$(3,10), TotalPop%(2,2,2)
Now
Example:
PopChange#(), CityStates$(), TotalPop%(), X1#
would call the procedure Example by sending it the current location of the three arrays and the integer
variable.
Example:
To write a function procedure that would take a list of numbers and return the maximum entry.
Function FindMax(A() As Single) As Single
Dim Start As Integer, Finish As Integer, I As Integer
Dim Max As Single
Start = LBound(A)
Finish = UBound(A)
For I = Start To Finish
If A(I) > Max Then Max = A(I)
Next I
FindMax = Max
End Function
80
For Example:
Type RecordOfSalary
Salaries(1 To 12) As String
SalInPrevYear As Long
End Type
You can then use a loop plus one individual statement to fill a record rather than using 13 statements.
||***********************End of Unit –III***********************||
Text Book Referred:
2. “Visual basic 6 From the Ground up” by Gray Cornell
UNIT-IV
THE WITH STATEMENT
Explain about with statement. (5 Marks)
The With Statement is used for quickly getting at the parts of a record.
Example:
With YourName
.Name=”Howard”
.Salary=100000
.SocSec=”036-78-9987”
End With
You can even most With statements if one of the components of a record is itself a record:
Dim MyStats As ExpandVitalInfo
With MyStats
.Name=”Gary Cornell”
With .Salary
.SalInJan=1000
.SalInFeb=2000
.
.
End With
End With
You can also use the With statement with properties of objects.
Example:
With txtBox
.Height=2000
.Width=2000
.Text=”This is a text box”
End With
You can also nest Withs when dealing with objects or records.
Example:
With txtBox
.Height=2000
.Width=2000
.Text=”This is a text box”
With .Font
.Bold=True
.Size==18
End With
End With
ENUMS
Explain about ENUMS. (5 Marks)
An enumerated data type is another user-defined type which provides a way for attaching names to
numbers, thereby increasing comprehensibility of the code.
The enum keyword automatically enumerates a list of words by assigning them values 0, 1, 2, and so on.
One of the new features is called enumerated constants or Enums.
82
You place the definition of the Enum in the declaration section of the form or module.
Example:
Enum DaysOfTheWeek
Sunday=1
Tuesday
Wednesday
Thursday
Friday
Saturday
End Enum
The visual basic automatically assigns successive integers to the days of the week (Monday=2,
Tuesday=3, and so on.)
Example:
If Weekday(Now) =Friday Then
MsgBox “Friday”
After they have been defined, Enums can be used as the parameters for functions and procedures.
Example:
Function SalaryMultiplier(X As DaysOfTheWeek) as Single
Select Case X
Case Saturday, Sunday
SalaryMultiplier=1.5
Case Else
SalaryMultiplier=1.0
End Select
End Function
Finally, you can also use Enums to create constants that do not follow any order,
Enum BonusLevel
NoBouns=0
StandardBonus=5
SpecialBonus=10
BossesBonus=100
End Enum
and use code like this,
Dim YourBonus As BounsLevel
YoursBonus=SpecialBonus
to give the YourBonus variable the value 10.
CONTROL ARRAYS
Explain about Control Arrays. (10 Marks)
The user want to use the same control name more than once while designing a Visual Basic application
or use CTRL+C, CTRL+V to copy an existing control from one place on the form to another, Visual
Basic asks you whether you really want to create a control array by popping up the message box.
When visual basic creates a control array, it gives the first control an Index property to zero, the second
control an Index property of 1, and so on.
Like most properties of visual basic objects, you can change the Index property at design time using the
properties window.
Working with a Control Array:
Suppose you want to work with the Change procedure for one of the two elements of the txtMoney
textbox control array.
When you move to the Code window, by double-clicking one of these text boxes from the control array.
Instead of having no parameters, as the Change procedure ordinarily does, this event procedure now
uses a new parameter, Index As Integer.
The index parameter is the key to the smooth functioning of control arrays.
Example:
Private Sub txtMoney_Change (Index As Integer)
83
If Index=0 Then
MsgBox “You typed in the text box with index 0”
Else
MsgBox “You typed in the text box with index 1”
End If
End Sub
(UNIT-IV Continued…)
The Load Statement: (Continuation… of Adding and Removing Controls in a Control Array)
The Load method is used to controls while the application is running. The syntax for using Load is
pretty simple the txtMoney control array it would be.
Load txtMoney(I)
Where, I will be the index of the element.
Private Sub Form_Load()
Dim I As Integer
For I = 2 To 5
Load txtMoney(I)
txtMoney(I).Text = "Text box #" + Str$(I)
MsgBox txtMoney(I).Text
Next I
End Sub
If you run this program, you won’t see any of your new controls! Because whenever VB loads a new
element of a control array, the object is invisible-the Visible property of the new control is set to False.
84
You’ll need to change this to true, even if you do, there is another problem you’ll need to cure: all other
properties of your new control are copied from the object that has the lowest index in the array.
Private Sub Form_Load()
Dim I As Integer
For I = 2 To 5
Load txtMoney(I)
txtMoney(I).Text = "Text box #" + Str$(I)
txtMoney(I).Visible = True
MsgBox txtMoney(I).Text
Next I
End Sub
You will only see the text box with index number 5. This is because the Left and Top properties start
out the same for all four of the newly created controls.
Private Sub Form_Load()
Dim I As Integer
Const SPACING = 10
txtmoney(0).Move 0, 0
txtmoney(0).Text = "Text Box in control array #0"
txtmoney(0).Width = TextWidth(" Text Box in control array #0 ")
txtmoney(1).Move 0, txtmoney(0).Top + txtmoney(0).Height + SPACING
txtmoney(1).Text = "Text Box in control array #1"
txtmoney(1).Width = TextWidth(" Text Box in control array #1 ")
For I = 2 To 5
Load txtmoney(I)
txtmoney(I).Text = "Text Box in control array #" + Str$(I)
txtmoney(I).Move 0, txtmoney(I - 1).Top + txtmoney(I - 1).Height + SPACING
txtmoney(I).Visible = True
Next I
End Sub
85
I=I+1
Else
Exit Sub
End If
End Sub
If you try to load or unload a control array element twice in succession, Visual Basic gives a run-time
error.
LIST AND COMBO BOXES
Explain about list and combo boxes. (10 Marks)
Use list boxes when you have a fixed list of choices. VB automatically adds vertical scroll bars
whenever the list box is too small for all the items it contains.
On the other hand, you might want this application to let the user select a president by number rather
than by scrolling through the list, use a combo box.
There are actually two types of combo boxes based on Style property.
o If the value of the Style property is set to the default value of 0, you get a combo box with an
arrow. If the user clicks the arrow, we will see the drop-down list of choices given in the box.
o If the value of the Style property of a combo box is 1, the user sees the combo box with the list
already dropped down.
There are two kinds of list boxes, and working with the Style property.
You can even change this property at runtime using one of the built-in constants vbListBoxStandard or
vbListBoxCheckBox.
Sorted property is False, VB places Item either at the position determined by the Index parameter or at
the end of the list when you do not specify the index.
The Index parameter must be an integer or integral expression. An Index value of 0 (not 1) means you
are at the beginning of the list. The Index option has no effect on where the item is added to the list if
the Sorted property of the list box is set to True.
Example:
Private Sub Form_Load()
List1.AddItem "George Washington"
List1.AddItem "Jonh Admas"
List1.AddItem "Thomas Jefferson"
End Sub
You can also remove an item from a list while the program is running by using RemoveItem.
Syntax: ListName.RemoveItem Index
ListName is the control name for the list or combo box and Index is the position where the item was
located.
In addition to removing individual items on a list, you can use the Clear method to remove all the items
on the list.
Syntax: ListName.Clear
Other Common List and Combo Box Properties:
The Font properties determine which font is used to display the items in the list or combo box. The
BackColor and ForeColor properties control determine what colors are used for the background and
foreground.
The Height, Left, Top and Width control determine the shape and location of the list or combo box.
Most Frequently used Properties:
List:
This property is a Zero-based string array that contains all the items on the list. This gives you another
way to initialize the items in the list or combo box instead of doing it at run time.
When you choose the List property in the Properties Window, VB opens up a list box where you can
type the items. You’ll need to place each item on a separate line, and this must be done by pressing
CTRL+ENTER and not the ENTER key between items.
List Count:
This property gives you the number of items on the list.
Dim i
For i = 0 To List1.ListCount - 1
If List1.List(i) = "TheItem" Then
List1.RemoveItem i
Exit For
End If
Next i
List Index:
The value of the ListIndex property gives the index number of the highlighted item. If no item was
selected, the value of this property is -1.
Example:
Suppose you’ve stored information about the presidents in a string array named presidentinfo, which is
dimensioned as being from 1 to 42, and you need to get at the item in this array containing information
about the president that the user has selected from the list1 list box is achieved using the following code.
ReDim president(1 To 42)
president(1) = "George Washington"
president(2) = "John Adams"
A statement such as,
If ListIndex = -1 Then
MsgBox "No President Selected"
Else
info = president(List1.ListIndex + 1)
87
End If
Text:
This is a property gives the currently selected item stores as a string. If lstBoxName is the name of the
list box, then the value of the lstBoxName. Text property for a list or combo box is the same as that of
lstBoxName.List (ListIndex) as long as only one item was selected.
88
The flex grid control lets you build spreadsheet-like features into your projects or display tabular
information neatly and efficiently. Moreover, the flex grid version works faster and uses fewer
Windows resources than a control array.
This control displays a rectangular grid of rows and columns at design time. How many rows and
columns you see at design time depends both on the number of rows and columns you have set and the
current size of the grid.
Each grid member is usually called a cell. Cells can hold text, bitmaps, or icons, and you can even have
some cells holding text and others holding graphics.
Users can move from cell to cell by using the arrow keys or the mouse; VB handles such movement
automatically. As the user of your control moves around the grid, VB keeps track of what the current
cell is as the values of the Row and Col properties.
Users can work with contiguous groups of cells in the grid, usually called regions, by clicking a cell and
dragging the mouse or by pressing SHIFT plus an arrow key to select the region.
General Properties of the Flex Grid Control
The Height and Width properties tell you how large the grid will
appear. The Enabled property determines whether the grid will notice
keystrokes or mouse activity.
If you set the ScrollBar property to a nonzero value, VB automatically
adds the appropriate scroll bars when there is information on the grid
that cannot be seen.
The CellFontBold, CellFontItalic, CellBackColor, and CellForeColor
properties affect the text or color of the current cell.
Most Important Properties:
Cols, Rows:
These properties determine the number of rows and columns in the grid. The default values for each of
these properties are 2, but you can reset them in code or via the Properties window, as needed. They
must be integers.
Syntax:
o GridName.Cols=NumOfCols%
o GridName.Rows=NumOfRows%
Example: .GridName.Cols=10
Col, Row:
These properties set or return the row and column for the currently selected cell inside the grid. These
properties are only available at run time. The top left corner cell has Col value 0 and Row value 0.
ColPosition, RowPosition:
These properties used let you move whole rows and columns around in your grid.
Syntax:
o GridName.ColPosition(number)[= value]
o GridName.RowPosition(number)[= value]
Example:
The below code specifies every time they click in a cell, the column containing that cell moves to a
random location within the grid:
o Sub MSFlexGrid1_Click()
MSFlexGrid1.ColPosition (MSFlexGrid.MouseRow) =Int(Rnd*Rows)
End Sub
ColWidth, RowHeight:
These two properties specify the width of a specific column or height of a specified row. They can only
be set via code. Both are measured in twips.
Syntax:
o GridName.ColWidth(ColNumber%)= Width
o GridName.RowHeight(RowNumber%)=Height
Text, TextMatrix:
The Text property sets or returns the text inside the current cell. The TextMatrix properties set or
retrieve the text in an arbitrary cell without needing to change the Row and Col properties.
Syntax:
89
o TextMatrix(rowindex, colindex)=[string]
Example:
MSFlexGrid1.Cols=4
MSFlexGrid1.Rows=4
MSFlexGrid1.Col=3
MSFlexGrid1.Row=3
MSFlexGrid1.Text=”This would go in the bottom right corner”
MsgBox MSFlexGrid1.Text & “is in cell 3, 3”
MSFlexGrid1.Col=0
MSFlexGrid1.Row=0
MsgBox MSFlexGrid1.Text & “is in cell 0, 0”
90
The string expression on the right-hand side contains the entire contents of the selected region. The
contents of each cell on the same row are separated from the adjacent cell by the tab character, and each
row is separated from the next by the carriage return character.
Example:
Private Sub Form_Load()
Dim S$
MSFlexGrid1.Rows = 3
MSFlexGrid1.Cols = 3
MSFlexGrid1.Row = 0 : MSFlexGrid1.Col = 0
MSFlexGrid1.ColSel = 2 : MSFlexGrid1.RowSel = 1
S$=Str$(1)+vbTab+Str$(2)+vbTab+Str$(4)
S$=S$+vbCr+Str$(4)+vbTab+Str$(5)+vbTab+Str$(6)
MSFlexGrid1.Clip=S$
End Sub
FillStyle:
Sometimes you want what the user enters into one cell of the selected region to fill up the entire region.
You can control this by changing the FillStyle property from its default value of 0 to the value 1. In
addition, when FillStyle is 1, any image assigned with the Picture property automatically fills all cells in
the selected region.
HighLight:
This has three values. The value 0 means that the user can’t tell when a cell is selected. The other two
values 1 and 2 give the user a visual clue.
AllowUserResizing:
This determines whether the user can resize a row or column at run time using the mouse. The possible
values are:
Constant Value Description
flexResizeNone 0 The user can’t resize rows or columns.
flexResizeColumns 1 The user can resize columns.
flexResizeRows 2 The user can resize rows.
flexResizeBoth 3 The user can resize both rows and columns.
AllowBigSelection:
This True/False property determines whether clicking on a column or row header selects the entire row
or column.
Sorting a Grid
One of the most powerful features of the flex grid is its ability to sort rows according to the columns you
select. If you change the Sort property at design time, the grid stats out sorted. If you change it at run
time, VB sorts the rows of the grid immediately after it processes the statement.
Syntax: FlexGridName.Sort=Value
The some of the possible values are:
Constant Value Description
flexSortNone 0 None
flexSortGenericAscending 1 Sort in ascending order
flexSortNumericAscending 3 Ascending but converts strings to numbers
flexSortStringAscending 7 Ascending but case-sensitive
Events and Methods for Grid Controls
Grids respond too many of the standard events. The Click event determine whether the user clicked
inside the grid and the KeyPress event to send what a user is typing inside the grid directly to the
currently selected cell.
EnterCell, LeaveCell:
EnterCell is triggered when the user clicks inside a cell that is different from the one currently selected.
LeaveCell is triggered right before the active cell changes to a new one.
RowColChange:
This event is also triggered when the current cell changes. It occurs after LeaveCell and EnterCell.
91
SelChange:
This event is activated when the selected region changes.
Methods for Resizing a Grid:
There are also methods that let you insert or delete rows from a grid.
Syntax:
o GridName.AddItem Item$ [,Index%]
o GridName.RemoveItem Index%
The optional index parameter allows you to add the row at a specific location. The string given by Item$ is
placed in the first column of the new row; you separate successive items in the same row by tab characters
(vbTab)
CODE MODULES: GLOBAL PROCEDURES AND GLOBAL VARIABLES
Explain about code modules in detail. (10 Marks)
When you start building larger projects with VB, you will probably want to reuse code as much as
possible. For this reason you will often want to store your procedures and functions in separate modules
rather than leaving them attaching to a form.
A Standard (code) module is where you put code that you want to be accessible to all code in a project.
Standard modules have no visual components. They are also useful for reusing code. You add a new
Standard module by choosing Project | Add Module; you add an existing one to your project by
choosing Project | Add File. By convention, Standard modules have a .bas extension.
The Sub and Function procedures in code modules are available to the whole project that is they have
global scope. This is because your placement of a procedure or of a declaration of a variable or constant
determines which parts of the project can use it.
If you attach a procedure to a form, the procedure will default to being usable only by procedures
attached to the form. If you put the procedure in code module, the procedure will default to being
available to the whole project.
Example:
Start up a new project with two forms and two command buttons. Name the button on Form1
cmdOnForm1 and name the button of Form2 cmdOnForm2. Change Private keyword to the Public
keyword in the cmdOnForm2_Click event procedure.
Public cmdOnForm2_Click ( )
MsgBox “This is the code in the now public click event attached to Form2”
End Sub
JAIRAM ARTS & SCIENCE COLLEGE, SALEM-08
STAFF ID: SCS86 CLASS: III B.Com (CA) ‘A’
SUBJECT: SOFTWARE DEVELOPMENT WITH DATE:
VISUAL PROGRAMMING
(UNIT-IV Continued…)
(Continuation… of Code modules: global procedures and global variables)
Public cmdOnForm1_Click ( )
Form2.Show
Form2.cmdOnForm2_Click
End Sub
If you run this and click on the button on Form1, you’ll see the message box, proving that we accessed
the event procedure on Form2. If you went back and changed the Public keyword back to Private
keyword in the event procedure on Form2, you wouldn’t.
Public Variables:
To make a variable attached to a form into a global variable to every part of a project, use a statement of
the form.
Public VariableName As VariableType
Then somebody can see that variable by using FormName.NameOfVariable. The Public identifier on
variables or procedures attached to a code module, you don’t need to use the name of the code module.
Example:
o If you added the following line to the Declarations section of any code module named
MyCode.bas
92
93
statement passes control to Windows, and VB gets control back only the operating system has finished
processing the events in its queue. Thus, if you changed the above code to read.
Private Sub Form_Load()
Show
Do ‘an infinite loop
DoEvents
Loop
End Sub
The form will close normally when you click on the Exit button. Tight loops are tricky-even DoEvents
is not a cure-all! So you can simply put an End statement in the Query_Unload event of that form in
order to end this program naturally.
ACCESSING WINDOWS FUNCTIONS
How can we access the windows functions? (5 Marks)
Windows itself can be thought of an interlocking set of DLLs containing hundreds of specialized
functions. These are called Application Programming Interface (API) functions. Some tasks, such as
learning whether users have swapped their mouse buttons or putting a window always on top, or
checking or setting the state of the keyboard, must be done with an API function. You can even use an
API function to reboot a user’s computer and start a program when windows reboots.
API statement requires a special type of declaration called Declaration statements. There are two
possibilities for the general form of the Declare statement. For a sub program in a DLL use.
o [Public | Private ] Declare Sub name Lib “libname” [Alias “aliasname”][([arglist])]
For a function use
o [Public | Private ] Declare Function name Lib “libname” [Alias “aliasname”][([arglist])]
[As Type]
The Lib keyword tells VB that a DLL is being called. The libname argument is the name of the DLL
that contains the procedure you will be calling. The Alias keyword is used when the procedure has
another name in the DLL but you don’t use it.
The Declare statement for the Window API version of the Beep function look like this:
o Declare Function APIBeep Lib “kernel32” Alias “Beep” (ByVal dwFreq As Long, ByVal
dwDuration As Long) As Long
the dwFreq parameter gives the frequency of the beep, and the dwDuration parameter gives the duration
in milliseconds.
ERROR TRAPPING
Explain about error trapping. (5 Marks)
The command that activates (enables) error trapping within a given procedure is
o On Error GoTo…
Where, the three dots stand for the label that defines the error trap. The labeled code must be in the
current procedure. You cannot jump out of a procedure using an On Error GoTo command. A label is
any identifier ending with a colon that satisfies the rules for variables.
o ErrorTrap:
‘Error code goes here
Usually, the error-trapping code is inside that procedure. When one procedure has been called by
another VB will look to see if an error trap was enabled in the earlier procedure if one does not exist in
the second procedure.
The On Error GoTo command should transfer control to a piece of code that identifies the problem and,
if possible, fix it.
If the error can be corrected, the Resume statement takes you back to the statement that caused the error
in the first place. However, you can’t correct an error if you don’t know why it happened. You identify
the problem by means of either the Err function of the Err object. This gives you an integer that you can
assign to a variable. For example if you write.
o ErrorNumber=Err.Number
The value of the variable ErrorNumber is the error number. Visual Basic can identify more than 80 run-
time errors. Examples:
94
Suppose an event procedure will be using the printer. Somewhere in the procedure, before the error can
occur, place a statement such as this:
o On Error GoTo PrinterCheck
Now, before the End Sub, add code looks like this:
Exit Sub
PrinterCheck:
ErrorNumber=Err.Number
Beep
Select Case ErrorNumber
Case 57
MsgBox “Your printer may be offline”
Case 68
MsgBox “Is there a printer available?”
Case Else
MsgBox “Error with” & ErrorNumber & “occurred”
End
End Select
More on Error Code Explanation
the 57 Device I/O error (for example, trying to print when the printer is offline)
Resume 68 Device unavailable (the device may not exist or is currently unavailable.
482 A general printer Error
Statement:
A variant on the Resume statement lets you bypass the statement that may have caused the problem. If
you use Resume Next VB begins processing at the statement following the one that caused the error.
You can even use On Error Resume Next to automatically bypass any code that causes an error.
You can also resume execution at any line of code that has been previously identified with a label. For
this, use Resume Label.
Both the Resume and Resume Next statements behave differently that is for the Resume statement, VB
will call the original procedure again. For the Resume Next command, VB will execute the statement
after the call to the original procedure. You will never get back to the original procedure.
The Erl (Error Line) Function:
Erl is one of the error handling function used to find the line that caused the error.
Disabling Error Trapping:
If you are confident that you will no longer need an error trap, you can disable error trapping with the
statement On Error GoTo 0
More on the Err Object:
VB provides the special Err object, which can be analyzed when an error occurs. Number property of
the Err object (Err.Number) gives you the error number.
The Err.Description gives a understandable description of the error. The Err.Source gives you the source
of the error if you are accessing another Windows application through OLE.
All the Err objects properties are reset to 0 after VB processes either a Resume or a new On Error
Statement. You can also use Err.Clear to reset the Err objects properties. If you want to generate an
error for testing purposes, use the Raise method of the Err object. Its syntax is Err.Raise(Number).
CREATING AN OBJECT IN VISUAL BASIC
How can we create an object in VB. (5 Marks)
You can build objects in three ways in VB. One is by adding custom properties to an existing form and
then using that form as a class (template) for new instances of the form. Each new instance of the form
will have the new properties.
The second way is by using a special type of module called a class module.
95
Class modules have the advantage that they can be compiled separately and used by other Windows
applications-even other VB program.
The third alternative is to create a custom control. In all three cases you start with same ideas for adding
properties to these classes (templates). First off, what are the most basic things you will want to be able
to do with a new property?
o You want to get its current value.
o You want to assign a new value to it.
For the first situation, you use a special type of procedure called a Property Get procedure. For the
second, you use a Property Let procedure. If the value you are assigning is itself an object, you use a
Property Set rather than a Property Let.
Example:
Suppose you want to add a custom property to a form that will tell you whether a form named
frmNeedsToBeCentered is centered, and also to center it if you set the property to True. Set up a Private
variable in the declarations section of the form.
o Private IsCentered As Boolean
Then add the following procedures to the form:
Public Property Let Center(x As Boolean)
IsCentered=x
If x Then
Me.Move(Screen.Width-Me.Width)/2,Screen.Height-Me.Height)/2
End If
End Sub
The first line of code uses the Private variable to store the current value of the property. Use the
following code.
o Me.Center=True
to center the form. From another form or code module, you can use a line of code like this:
o frmNeedsToBeCentered.Center=True
It might also be useful to know whether a form is centered. For this you need to use a Property Get
procedure that returns a Boolean:
Public Property Get Center() As Boolean
Center=IsCentered
End Sub
This picks up the current value of the IsCentered Private variable that you are using to hold the
information about the current value of the property.
Sub Form_Load ()
If Me.Left=(Screen.Width-Me.Width)/2 And Me.Height=Screen.Height-Me.Height)/2 Then
IsCentered=True
End If
End Sub
JAIRAM ARTS & SCIENCE COLLEGE, SALEM-08
STAFF ID: SCS86 CLASS: III B.Com (CA) ‘A’
SUBJECT: SOFTWARE DEVELOPMENT WITH DATE:
VISUAL PROGRAMMING
96
The syntax for the Property Let procedure template look like this:
[Public | Private] [Static] Property Let name [(arglist)]
[Statements]
[name=expression]
[Exit Property]
End Property
Use Public to make the Property Let procedure accessible to every procedure in every module. Use
Private to make the Property Let procedure accessible only to other procedures in the module where it is
declared.
Use the Static keyword if you need the Property Let procedure’s local variables preserved between uses.
The Exit Property keywords give you a way to immediately exit from a Property Let procedure. The
name of the Property Let procedure must follow standard variable-naming conventions, except that the
name can, and most often will, be the same as a Property Get or Property Set procedure in the same
module. The usual syntax for a Property Get procedure template looks like this:
[Public | Private] [Static] Property Get name [(arglist)] [As type]
[Statements]
[Name=expression]
[Exit Property]
End Property
The last type of Property procedure is the Property Set statement. Use this when you need to set a
reference to an object instead of just setting a value.
[Public | Private] [Static] Property Set name [(arglist)]
[Statements]
[Exit Property]
[Statements]
End Property
If you choose Tools | Add Procedure and choose “property” type, VB automatically gives you the
following templates:
Public Property Get ExampleProperty () As Variant
End Property
BUILDING YOUR OWN CLASSES
How can we build your own classes? (5 Marks)
The most common way to build a new class (template) for new objects in VB is to use a class module. A
class module object contains the code for the custom properties and methods that objects defined form it
will have. You can then create new instances of the class from any other module or form in your project.
A class module cannot have a visible interface of its own. Each class module you create gives you,
naturally enough, a single class (template) for building new instances of that class. However, you can
have as many class modules in a project as you like.
Once you have a class module, you use the New keyword to create new instances of it. For example, if
FirstClass is the name of a class module in your project, you would create an instance as follows:
o Dim AnInstance As New FirstClass
You use Property procedures to define the properties of your class and use Public Sub and Public
Function procedures for its methods.
Creating a New Class Module:
You create a new class module at design time by choosing Project| Add Class Module. Each class
module can respond to only two events: Initialize and Terminate. They are triggered when someone
creates an instance of your class or terminates it.
||***********************End of Unit –IV***********************||
Text Book Referred:
3. “Visual basic 6 From the Ground up” by Gray Cornell
UNIT-V
CRYSTAL AND DATA REPORTS
CRYSTAL REPORTS
97
Click on Field and Select New. Or click on the icon (in picture) that represents a new report.
98
This figure will display the various tables and the relationship between each of them. If you think there
are too many tables and views and you do not need all of them, then you can delete some of them.
Click on the button 'Back'. You will see the following figure.
99
You can select the items that you do not need and click on remove to remove them one by one. When
you are sure you have only those tables that you need click Next to continue. You will see the figure
with the selected tables and their relationship. Click Next to continue. You will see the following figure.
In this dialog box you can add the fields that you wish to include in your report the fields that you select
here will appear on the report. However the selection criteria for the selected records need not depend on
these fields alone. When you have selected the fields and added them one by one in the 'Report fields'
ListBox. Click on Next to continue. You will see the following figure.
100
In this dialog box you can choose the fields on which the report is to be sorted out. For example, you
can sort all the details based on the City, or the Product that a customer uses, or the Turnover of the
company, etc. Select the fields on which the criteria is to be built and then select the sort order.
For example, you can sort the details in the ascending order or descending order. When you are through
with this click Next to continue. You will see the following figure.
In this dialog box you must select the fields on which you have to perform calculations like group total,
sub-total, etc. For example if you want to know the number of customers in a particular city, then select
Customer_City and add it to the "Total Fields' ListBox. Here you can also choose if you want to total
the number of customers for a city or if you want to the add the figures for a particular column. For our
example choose Count. Then Click next to continue. You will see the following figure.
In this dialog box you must choose the fields based on which the records must be selected from the
database. In the Report Fields ListBox you are presented with the fields that you have selected for the
report. If none of these fields meet your requirements to determine the selection criteria, you can scroll
down further and select from the fields that have not been included in the report. Build your selection
criteria and click Next to continue. You will see the following figure.
101
In this dialog box you can select the layout of the report. Select the report layout style that you think
suits you best. The selection of the style will depend upon the type of data that you are likely to have on
the report.
For example, if you are going to have the total amount out-standing from a customer and your report
will hold the status of customer for a city or area then you can choose Trailing Break Style or the Drop
Table style. It’s suggested that you preview the various types of reports possible before settling for a
particular style.
Next you can preview the report. The preview of the report will look like this
So we have created a report from scratch with the help of a Wizard or and Expert. Let us see how we
can create a report without the help of a Wizard. Remember that the steps required to create a report will
be more or less the same.
102
From the extended set of buttons displayed select Custom and then click on the Data File button.
You will be asked to select the database file. Select Test.mdb in order to complete this example. (In
case you do not have such a database file with such tables create them for the sake of this exercise).
Next you will see a figure like one as shown in the next page.
103
This is called the Design/Preview window. Here you can design and view the report as you go on
adding fields to it.
The Design/Preview Window
This is the window where you design your reports. The default tab is the Design tab. This window is
divided into two parts. The Large white area is where you actually insert the fields are the gray area on
the left side with several rows.
The rows will be titled as Title, Page Header, Details, Page Footer and Summary. Each of these titles is
separated by a line ha extends into the large white area. This is to help you correctly insert and correct
the data that should appear on the report.
If you click on the Preview tab, a preview of the report will be displayed. You can zoom to get a letter
view of the report. The button to zoom is
In the figure above, the Insert Data Field dialog box displayed over the design window consists of the
list of fields that you can display on the report. Apart from the list box there are three buttons "Insert",
"Done" and "Browse Field Data".
To insert a field select it and push the Insert button. Your mouse pointer will suddenly acquire a square
tail. This is tells you that you were selected a field and you can insert it at a location on the report.
Move the pointer to the location where you wish to display the selected field and click on the muse. The
field will get inserted at that location.
Let Us get back to the Insert Data Yield Dialog box. Select Customer_Name from the list of fields
displayed in the ListBox. Click on the 'Insert' button.
Notice that your mouse pointer has acquired a 'tail’. Move the mouse pointer to the section 'Details' on
the 'White Area' and click the left mouse button.
The Customer Name field gets placed there along with the heading. You can change the column heading
later if you do not like the current heading. Similarly add two more columns namely Order_Date and
Order_Value to the report.
Click on the Preview tab to view the report. You will see a list of the customers with the Order Date and
Order Value. Some of the problems with this report are:
1. The customer names are repeated.
2. There are no sub-totals for individual customers.
3. There is no grand total of the Order Value.
Let us see how we can correct them. We are at liberty to call on the 'experts' for help. We will first sort
the listing on Customer_Name. Click on the 'Reports' Menu Option. From the menu items select 'Sort
Records'. You will see the following dialog box.
104
From the list of items in the Report Fields ListBox on the left add the Customer_Name to the Sort
Fields ListBox on the right. Select the Ascending (default) order for sorting the records.
Now Click the Preview tab to see the result. To avoid repeating the Customer_Name (or for that matter
any field) for every occurrence, click on Format. From the menu click on 'Fields'. You will see the
following dialog box.
(Unit –V Continued…)
(Continuation the Design/Preview Window…)
Click on the ‘Suppress if Repeated' option button, to include Sub-Totals for the Order_Value for each
customer, right click the mouse on the Order_Value in the Details section. From the pop-up menu
select_Insert Sub-Totals. You will see the following dialog box.
105
The message displayed will be "When the report is printed the records will be sorted and grouped by"
Next to this message is a drop-down combo box. Click on the down arrow to view the list of fields that
you can group by. Select Customer_Data Customer Name. A message will appear at the bottom of the
dialog box. "The subtotals will be printed on any change of Customer_Data.Customer_Name".
Click OK to accept the changes. To add the Grand Total to represent the total of all Order_Values,
once again right click the mouse on the Order_Value in the Details section. From the pop-up menu
select 'Insert Grand Total'. You will see the following dialog box.
Select 'Sum' from the drop-down ComboBox. You have a wide choice of options to choose from for the
Grand Totals column.
Now preview your report. Your report should look like this.
Save the report in your directory. It will have an extension name ".rpt"
Calling Crystal reports from Visual Basic
So you have learnt how to create a report using Crystal Reports. We need to be able to call the report
that we have created from our application. In order to be able to call Crystal Reports from our program
we must first add the Crystal Reports control to our program.
Start a new project. The Crystal Reports control should be added to the form from where you intend to
call the report.
You will not find the control on your toolbox, to add it to your toolbox right click the mouse on the
toolbox and select Components from the pop-up menu. From the list of components select Crystal
Reports Control 4.6.
106
Add an instance of the Crystal Reports control on your form. Since this control is not visible during
runtime it will appear as an icon at design time. Right Click on the icon and select
Crystal Properties from the menu.
The most important property to set here is the ReportFileName. This is set in the General Tab. Set it to
the filename under which you saved your report. Under this tab you can also specify if your report
should go to the printer or to the window or to a file.
Add a CommandButton to your form. In the click event of the CommandButton add the following line
of code.
CrystalReportl. Action = 1
If you are going to use more than one report file in your program then you need to set the
ReportFileName before you run the report.
You see the ReportFileName as follows
CrystalReportl. ReportFileName = "C:\azam\vb-exersices\crysl.rpt"
CrystalReportl. Action = 1
Most of the properties that you see in the Property pages are available at runtime and can be modified
when needed. You can for example use a selection formula to select the records that appear on the
report.
If you want the report to display selected records, for example you want to see details of the customer
whose Customer_Code is C455 then add the following line in the SelectionFormula ListBox under the
Selection Tab.
{CustomerJData.Customer_Code} = "C455"
Run the program and you will see the details of customer C455 only.
DATA REPORTS
Write short note on data reports. (5 Marks)
Explain about data report designer. (5 Marks)
Write short note on various parts of a data reports. (5 Marks)
Explain about various sections of a Data Report designer. (5 Marks)
Write notes on Data Report Controls. (5 Marks)
Write notes on extracting the Data. (5 Marks)
In the last session we saw how to use Crystal Reports to create reports. In the following session we
will take a look at Data Report. Data Report is the new offering from Microsoft perhaps with a view
to replacing Crystal Reports in the long run.
Data Report as it stands today is meant for programmers. A general user of computers will not be
able to get around it. Let us take a look at what Data report has to offer and how we go about using
this toolIn order to use Data Report you need to use ADO or Data Environment. Since we have
covered ADO in the previous chapter we will work using ADO with Data Report.
You need to follow the following steps to generate a report using the Data Report.
1. Create a data source usingADO.
2. Add the Data Report object to your project.
3. Place texboxes representing the various fields that you want on the DataReport object.
4. Link the Textboxes to the various fields of the data source
5. Display the report using the Show method.
This sounds like quite a bit of work. Actually it is quite easy if you have already worked with the
Data Control or the ADO Data Control.
The approach is very similar and you will find it fairly simple unless you are a die-hard fan of Crystal
Reports.
Getting Acquainted With the Data Report Designer
Data Report Designer is not part of your toolbox. To add it to your toolbox, right click on the toolbox
and select Components from the pop-up menu. On the Component dialog box, click on the
‘Designers' tab and select 'DataReport'. Close this dialog box.
Let us take a look at the DataReport object. This will give us an idea about the approach to be taken
for generating a report.
The Data Report Designer is the form on which you design the layout of the report. The DataReport
object is the programmable object that represents the Data Report Designer.
107
Click on 'Projects' In this menu you will see a new item 'Add Data Report'. Select this item to add a
Data Report Designer to your IDE. Please remember that this designer will not be placed on your
form. The Data Report Designer is a separate form by itself. Open the Project Explorer and you will
see another item called DataReportl along with the Forml. Also notice that your toolbox has acquired
a tab called Data Report with its own set of tools.
109
We are now ready to display the data. We have created the recordset. We have assigned the fields in
the Data Report Designer.
We need to link the recordsource to the Data Report. Then we must caU the Show method of the Data
Report. The following lines have to be added to the "Display" command button.
Set DataReportl .DataSource = adors
DataReportl.Show
Run the program now.
Add headers to the report using the RptLableBox controls so that the report looks meaningful.
CREATING MULTIPLE REPORTS
Explain how to create multiple reports. (10 Marks)
The users of your application are not going to be happy with just one report. They will want the data
presented in many and every combination. We can cater to this as well. There are two ways of
handling the 'multiple reports' situation.
For every report that the user wants, we can create a DataReport or we can display different data using
only one or a few DataReport forms. Both the approaches have their merits and demerits.
We have already created one report using one DataReport. Creating more reports using the same
method should not be very difficult.
However displaying more than one report using only one DataReport involves a little work.
Details like Caption, Page Headers, Footers, etc. for each of the reports must be determined. The
heading for the data must also be determined. The data and the source of the data must also be worked
out.
Depending upon the number of reports that you may need to display on form, you have to work out if
it is feasible to create a recordset or a number of recordsets for all the reports. Creating a recordset
every time the user asks for a report may not be a good idea especially in a multi-user environment.
At the same time creating a large number of recordsets and locking up resources will not be the right
thing to do.
ACTIVEX: OBJECTIVES
What is the reason behind the creation of ActiveX? (5 Marks)
What is ActiveX? (2 Marks)
Write short notes on OLE. (5 Marks)
How will you Registering an ActiveX Control. (2 Marks)
The primary purpose of this chapter is to demystify ActiveX. In this chapter we will discuss the
following:
1. What is ActiveX?
2. DDE and OLE, the technologies before ActiveX
3. What is an ActiveX Control?
4. Creating an ActiveX Control
5. Writing the code, adding properties
6. Registering the ActiveX Control.
What is ActiveX?
110
It can be described as an ingredient that will add energy to your document. It can be described as a shot
in the arm for a programmer.
A cocktail, a mix of marketing hype and programming evolution. A health drink like Milo or Horlicks.
By the time you have gone through the following pages, you will be able to decide on a particular
definition, or you may even create your own definition. After all, that is what ActiveX is all about.
Why ActiveX?
The concept of ActiveX was developed for very simple reasons:
To be able to import data from one application to another.
To be able to make changes in the imported data such that the data in the parent application was
also updated.
To be able to place different types of data or 'objects' in one document.
The first technology was DDE or Dynamic Data Exchange.
This technology allowed applications to exchange data.
It also allowed one application to send commands to the other application.
This technology was not very successful, and gave way to newer technology.
Next came OLE, an acronym for Object Linking and Embedding.
Under this technology, one document could display an object from different applications.
As the name suggests, the imported object would get 'embedded' in the host document.
By clicking on an object in the document, the parent application of that object would get
invoked.
The advantage of this technology was that no conversion of data was done from one application
to another.
Let us take a break and discuss another point.
Programmers who work in the C language are very fond of using the term 'function'.
Systems Analysts are very fond of using the term 'reusable functions'.
The top brass in a development set-up likes to talk of ‘reusable code'.
However, all this to a large extent has remained only TALK.
This is because a function can be used or reused only in that program.
Reusable code is limited only to that language.
Therefore programmers came up with libraries where functions would be available for use by
any program.
However, this too had the limitation of the language.
Then came DLLs.
DLLs suffered from version problems. If the date (and camels) did not match, the program would not
work. Take a Visual Basic application from one machine to another to experience first-hand the agony
of DLLs and dates.
OLE 2. The Next Step
OLE 1.0 did not succeed because of various limitations.
The need was for a document to load and save an object that it did not know about.
The application should provide an interface to edit objects that it contains.
To support drag-and-drop of objects that it does not know about.
To execute commands on objects belonging to unknown applications.
Demands of this type meant budding applications/objects that could be used by any other application. A
standard had to be developed or evolved which all object builders would follow.
This example can be seen in the case of hardware. When one talks of RS232C everybody knows what it
means. Anybody in the business of serial communications would build products that follow this standard in
terms of connections, size, number of pins, etc.
Visualize the hardware scenario and use the same analogy for software.
OLE 2.0 attempted to meet all the conditions by bringing together different technologies under one
umbrella.
We first need to understand in simple terms the meaning of an object in this context. An object is (at this
stage of discussion) the data that is embedded in your document. For example, if you have included a part
of a spreadsheet in your Word document, the spreadsheet is an embedded object. The task now is to figure
out how this 'object' can be controlled, invoked, deleted, etc.
111
Microsoft came up with some specifications on Objects and how they should be handled. The
specifications are as under, and are COM specifications. COM stands for Component Ob¬ject Model, the
new buzzword in computers.
1. A common method for applications to exchange objects.
2. A method to identify an object and relate an object with applications that can manipu- late it.
3. A standard set of error codes and an error-reporting and responding system.
4. A system to invoke an object. Check if it is in use, and delete it if it is not in use. This ensures
that memory resources are not blocked.
5. A set of rules for applications to access and manipulate objects.
Let us see how these rules can be applied. Let us take an example of a Word document containing a part
of an Excel spreadsheet.
An application that accepts or requests an object is called as the client or container.
The application that provides an object is called the Server.
Rulel :
Word must know how to accept the spreadsheet from Excel.
Rule2 :
If the user double-clicks on the spreadsheet, Word (or the system) must be able to identify the
object and invoke Excel.
Rule3 :
In case of an error like Excel being corrupted or “This application has performed.../ Error, both
the applications must be notified. A copy of the FIR is to be sent to the MLA!
Rule 4:
Once the modifications have been completed on the object, the instance of Excel must be closed.
This will ensure that resources are not blocked.
Rule 5 :
This ensures that the spreadsheet is presented as a spreadsheet, and that the rules for presenting
spreadsheet data are followed.
Identifying the object: Every time an object is created, identification for this is created. This is called
GUID, which means Globally Unique Identifier. The GUID is a 16Byte value that is totally unique.
The object is identified by the GUID rather than by any name that the user may give.
This means that a Word document for example can have multiple objects from the same or different
applications. Once the object has been identified, the container application allows the object to draw
itself. Identifying the application(s) associated with the object does this.
There is something called 'in-place-editing' where the objects application will take control of the object
and allow the user access to all its tools.
Saving the object: This is called persistence. Very soon our current dictionaries will go out of vogue. If
a document contains multiple objects, how is it going to save itself and all the objects? According to
COM, every object must be able to save and load itself. A set of specifications has been defined for
saving and loading objects, but where and how will different objects store their data?
OLE Structured Storage is the answer. It is like a file system within a file. The file becomes the
directory, known as storage, and each of the objects becomes the file (known as stream) in the
directory. Therefore in our example, the Word file will create a Storage and pass it to the objects.
The objects will save themselves as streams in the Storage. Since the GUID of the objects are also
saved, it is easy for the objects to load themselves as and when required.
OLE Automation
This is a mechanism by which a container application can execute commands in the server application.
This also allows the container application to export or transfer data from the objects to another
application. When Visual Basic was first released, it made developing Windows applications easy.
Longer did programmers have to fight with C and C++ and similar animals. Developers started creating
controls that could be used by other Visual Basic programmers. Microsoft encouraged this trend. A
programmer could buy a number of controls in the market, wire them together and have an application
ready. We have done the same thing in the previous exercises.
Let us take a look at the controls. Each control is independent. It has its data, properties, etc. It can
display as well as draw itself on the form. It can be changed at design time or runtime if necessary. The
functions that make it work are kept in a DLL.
112
The VBX were like the COM objects by design or chance, but their limitation was that they could work
only with Visual Basic. Therefore OLE was taken out of the dungeon and worked upon, it had all the
features for component programming, but could not raise events in the container application.
OLE was thus extended. It came to be known as OCX or OLE Control, which could raise events in the
container applications. We have thus seen the evolution of programming combined with market events.
Let us take a look at another market event that brought about ActiveX.
Microsoft was working steadily on the path to 'docu-centric computing', when suddenly there was a
big bang in the form of the Internet and the World Wide Web. Everybody was talking about it.
Microsoft was not really prepared for it. Microsoft took a closer look at HTML and found that the
concept of'docu-centric computing was very well implemented here. As a leading company, it needed
to tell one and all that it had a technology for the Internet. They called this technology ActiveX.
ActiveX is OLE with some extensions for the Internet.
Now that the cat is out of the bag, let us take a look at some of the properties of ActiveX controls.
Any control or object has
Properties : like BackColour, Font, Resize, Paint, etc.
Events : Click, MouseMove, KeyPress, LostFocus, etc.
Methods: The code associated with the control.
So is the case with an ActiveX object or control.
So How is an ActiveX Control Different?
ActiveX controls are created by using existing controls, or from scratch.
An ActiveX control can be used by other development tools as well.
Controls like MSFlexGrid, Sheridan Controls are all ActiveX controls.
So what is the big idea?
With Visual Basic 5.0 onwards you can create your own ActiveX controls. Any control that you see or
use can be enhanced to suit your requirements.
That control can be used in your organization, or you can sell it to your neighbour and make some pocket
money. An existing control can be restricted and used in your application. The dream of reusable code
has now become a reality, thanks to ActiveX.
Now let us create an ActiveX control.
We know that ActiveX is not a strange, dangerous, complex and shaggy animal. It is a simple thing
after all. Let us create a simple ActiveX first.Click Start your Visual Basic.Start a new project.
Select ActiveX Control from the various options.
You will see a new Form. Notice that it looks like another form that you have been playing around
with. The title bar will say "UserControll". This means that you are creating your own control
(ActiveX Control). Touch your head. You have not grown a horn yet!
Now change the name of the UserControll to a name of your choice. You do so by clicking on the
form and pressing F4. Sounds familiar?
Save this user control in the respective files. An ActiveX control is saved in a file with .ctl extension.
There will also be a .vbp file. You have just created an ActiveX control. Let us see it in action.
Open the project again. Click on File and select Add Project.
Select Standard Exe this time. Observe your Project Explorer. Notice that there are two projects
listed. You will be constantly shifting from one to the other, as you work along, lb the Standard.Exe
project form Forml, add the new User Control that you just created.
You will see another blank window that does not do anything at all. This ActiveX is not active! That
is because you have not added any control on it yet, nor have you set any methods or pictures, etc.
Registering an ActiveX Control
1. First delete the second project where you had tried out the user control.
2. From the file menu choose the option ‘Make….OCX’
This will register the new control in your window system directory. the control is now available to
you and to those who use your system.
3. To add this control in the Toolbox, go to the windows\System directory.
4. Run the command “regsvr32 [controlName].ocx” to register this control.
ActiveX AND WEB PAGES: OBJECTIVES
ActiveX and Internet.
113
114
1. HTTP: Hypertext Transfer Protocol. This protocol is used to transfer pages from the server to the
client.
2. Server: The computer that has the pages that you requested.
3. Client: Your computer that has made the request.
4. URL: Uniform Resource Locator. This contains the information needed to locate the page that you
want. An URL has
The Protocol
The Server name
The Pathname of the file in the server's directory
PageName, the name of the file that has the page
Pagenumber#, the Pagenumber which hold the text that you want.
We will cover tags as we continue with development.
Now let us get back to the ActiveX Control Pad. Right Click the Mouse between the tags <BODY> and
</BODY>. From the pop-up menu choose "Insert ActiveX Controls".
A list of ActiveX control will pop. You will be surprised that there are already so many ActiveX
Controls available on your system.
Select the Calendar Control that we developed.
Now save changes on the file. Open the file using Windows Explorer.
You will see your first HTML page. Congratulations!
The ActiveX based web page would look like the below screen shot.
From the Supplier the retailer will receive goods and pay for them. Retailers will generally have a couple
of 'regular' suppliers.
The regular suppliers will also extend credit and certain Understanding exists between them. The retailer
must keep track of the amount that he has to pay to his suppliers.
This is referred to as 'Payables'. The retailer will also buy from a number of other suppliers who may or
may not extend credit. These suppliers normally supply good* during seasonal or unexpected demand.
The Customer
The Customer is the consumer. He buys from the retailer (normally) in small quantities and pays 'cash on
the barrel'. A number of customers also pay for the goods later.
This is where the retailer has to keep track of payments due from his customers. In commercial jargon this
is referred to as 'Outstanding' or Receivables.
Another important factor now in the distribution set up is the stock.
The Stock
The retailer maintains a stock of goods that he believes will be purchased by the local junta. If he makes a
wrong guess he is left with a lot of stock that has to be disposed of under the banner 'Closing Shop!
Distress Sale!' The stock in the shop or the warehouse of the retailer is called 'Stock on hand'.
Based on the sale of goods, the retailer will replenish the stock. For even* item the retailer will maintain a
'Reorder Level'.
The Re-order Level is a function of various factors like Demand for the goods, the Lead time to supply,
etc. If for example Potatoes are selling like hot cakes' and the lead time to supply (the time between
ordering for and receiving the items') is high then the re-order level is also high.
This is so because, by the time the fresh stock arrives, the retailer should not end up with an empty bin 1 f
the Lead-time to supply is very low then the re-Order level can also be low
Now what should the size of order be? One kilo? One ton? One truckload? This quantity is called
Minimum Order Quantity or Economic Order Quantity. The MOQ is arrived at taking into account
quantity discounts offered by the suppliers, the demand for the goods in his area and other related factors.
You cannot order one kilo of nee from a distributor who deals in truckloads. So you know what is meant
by Minimum Order Quantity.
The retailer must send a Purchase Order to the supplier for goods. The Purchase Order (PO) may be based
on a quotation sent by the supplier or it may be a PO without the rates.
The Supplier will send the goods based on the current prices. Once the goods arrive, they have to be
accepted' in the store. A document called the Goods Received Note' is generated.
This is considered an important document based on which the supplier will be paid this is so because the
supplier may not have sent all the goods ordered or there may be a 'Short Shipment'.
From the above description we see that the retailer carries out the following activity’s
1. Raising a Purchase Order
2. Accepting the goods into the store
3. Making a payment to the Supplier.
4. Selling goods to the Customer.
Sending a quotation (in some cases),
Accepting the Order from the Customer,
Raising an Invoice.
5. Receiving payment from the customer.
6. Maintaining stocks.
Different set of tables are created for supplies, stock and customer and relationships are established between
them depending upon the requirement of the application.
117