VB B.com. (CA) Material
VB B.com. (CA) Material
CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
VISUAL PROGRAMMING
UNIT – I
Introduction to Visual Basic: Getting Started - Working with Visual Basic – The Initial Visual Basic
Screen –The SDI Environment – Toolbars - The Toolbox and Custom Controls and Components –
Starting a New Project – The Properties Window – Common Form Properties – Scale Properties – Colour
Properties.
UNIT – II:
Building the User Interface: Toolbox – Creating Controls – Name Property - Properties of Command
Buttons - Image Controls - Text Boxes – Labels – Message Boxes - Grid. Anatomy of a VB Application –
The Code Window – Statement in Visual Basic – Variables – Data types – Working with Variables –
Constants – Input-Boxes
UNIT- III:
Display Information on a Form - The Format Function - Picture Boxes – Rich Text Boxes – The Printer
Object - Determinate Loops - Indeterminate Loops – Making Decisions – Select Cases – Nested If- Then
– The GOTO – String Functions – Numeric Functions – Date and Time functions – Financial Functions
UNIT - IV:
Function Procedures – Sub Procedures – Advanced Uses of Procedures and Functions – Lists: One–
Dimensional Arrays – Arrays with more than One–Dimension - Using Lists and Arrays with Functions
and Procedures – The With Statement - Enums – Control Arrays – List and Combo Boxes – Menus –
Menu Editor – MDI Forms.
UNIT – V:
Introduction to Database - Working with Data Control: The Data Control - The Bound Control – Coding
– Data Access Object: Functions of the Jet Database Engine – The DAO Object Model - Crystal and Data
Reports: Crystal Report - Data Report – Creating Multiple Reports
TEXT BOOKS: 1. ―Visual Basic 7 From the Group UP‖, Gray Cornell, Tata McGraw Hill Edition
(Unit-1 to Unit –IV)
2. ―Programming With Visual Basic 6.0, Mohammed Azam, 2nd Edition. (Unit – V)
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 1
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
UNIT -1
Introduction to Visual Basic: Getting Started - Working with Visual Basic – The Initial Visual Basic
Screen –The SDI Environment – Toolbars - The Toolbox and Custom Controls and Components –
Starting a New Project – The Properties Window – Common Form Properties – Scale Properties – Colour
Properties.
1. New lets you create new applications by using various wizards or starting from scratch.
2. Existing lets you select and open an existing Visual Basic project.
3. Recent displays a list of Visual Basic projects you've recently opened or created.
A project is a collection of files that make up your application. A single application might consist of
several files, and the project is the collection of those files.
Now the New Project dialog box will appear. We are going to create a simple application. So choose
Standard EXE from the New Project dialog box and click the Open button.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 2
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Now Visual Basic IDE (Integrated Development Environment) window will appear. It contains
several menus, windows, tool bars and toolbox.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 3
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Click on the VB Application wizard, the introduction dialog box will appear, as shown in below Figure.
As you are not loading any default setting, just click on the Next button.
After clicking the Next button, the interface type dialog box will be displayed, as shown in below.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 4
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
3. Explorer Style lets your application take on a Windows Explorer-like interface with topic
summaries in the left window and details for a selected topic in the right pane.
Type the project name in the textbox below, here I am using MyFirstMenu.
Clicking the Next button will bring up a list of menus and submenus that you can add them to your
application.
Check to select a menu item and uncheck to unselect a menu item as shown in above Figure
Choose all the menus and click next, then will get an interface comprises File, Edit, View and Help
menus.
The Application wizard saves you time by creating an initial toolbar.
The next wizard screen to appear is the Resource screen from which you can elect to use resources
in your program, such as multilanguage text files. Simple programs often do not require external
resources.
For this example, keep the option labeled No checked and click the Next button to continue.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 5
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
The next wizard screen is the Internet Connectivity screen from which you can add an Internet
interface to your program if you want one.
Click finish in the next screen. Now the first project is created.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 6
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
The Visual Basic development environment contains these programming tools and windows,
with which we construct your Visual Basic programs:
Title bar
Menu bar
Toolbars
Visual Basic toolbox
Form window
Properties window
Project Explorer
Immediate window
Form Layout window
Title bar:
The title bar is the horizontal bar located at the top of the screen.
It gives the name of the application.
In visual basic, the title bar displays: Project1- Microsoft Visual Basic [design]
This is typical windows application that has multiple states, the title bar changes to indicate
important information.
When we run the program the title bar changes as: Project1- Microsoft Visual Basic [run]
When we debug the program the title bar changes as: Project1- Microsoft Visual Basic [break]
Menu bar:
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 7
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 8
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
TOOLBARS:
Visual basic has multiple toolbars.
The four built in toolbars are
1. Standard
2. Edit
3. Debug
4. Form editor
Standard toolbar:
View Application - Toggles between the host application and the Visual Basicwindow.
Insert Userform - Defaults to a userform but also allows you to insert modules and
procedures.
Save - Saves the application including all the Visual Basic components.
Cut - Removes the selected control or text and places it on the clipboard.
Copy - Copies the selected control or text and places it on the clipboard.
Paste - Inserts the contents of the clipboard at the current location.
Find - Displays the Find dialog box allowing you to search for particular text.
Undo - Reverse the last text editing action.
Redo - Restores the last text editing Undo actions.
Run - Runs the current procedure if the curosr is in a procedure. Runs a userform ifa
userform is currently displayed. Displays the Run dialog box otherwise ??
Break - Stops execution of a program while it is running and switches into breakmode.
Reset - Clears the execution stakc module level variables and resets the project.
Design Mode - Toggles design mode.
Project Explorer - Displays (or toggles) the Project Explorer window.
Properties Window - Displays (or toggles) the Properties window.
Object Browser - Displays (or toggles) the display of the Object Browser window.
Toolbox - Toggles the display of the toolbox that contains userform controls. Thisis only
available when a userform is active.
Help - Opens the Office Assistant.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 9
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Edit toolbar:
List Properties / Methods - Displays a drop-down list in the code window that contains all
the properties and methods available for the object that precedes the period (.).
List Constants - Displays a drop-down list in the code window that contains all theconstants
that are valid choices for the property that precedes the equal sign (=).
Quick Info - Provides the syntax for a variable, method, function or procedurebased on
the location of your position.
Parameter Info - Displays a popup in the code window containing information
about the parameters of the function in which the pointer is located.
Complete Word - Accepts the characters that the editor has automaticallyappended as
you were typing.
Indent - Shifts all the lines (in the current block) to the next tab stop. No shortcutkey by
default but you could add one.
Outdent - Shifts all the lines (in the current block) to the previous tab stop. Noshortcut
key by default but you could add one.
Toggle Breakpoint - Toggles the insertion of a breakpoint at the current line.
Comment Block - Adds the comment character (‘) to the beginning of each line inthe
current selection.
UnComment Block - Removes the comment character (‘) from the beginning ofeach line
in the current selection.
Toggle Bookmark - Toggles the insertioon of a bookmark on or off for the activeline.
Next Bookmark - Moves the focus to the next bookmark in the bookmark stack.
Previous Bookmark - Moves the focus to the previous bookmark in the bookmarkstack.
Clear All Bookmarks - Removes all the breakpoints from the active project (or allprojects
??).
Debug Toolbar
Run / Continue - Run switches from design time to run time. Continue switches from break modeto run
time. When in break mode the name of the button changes to Continue (Ctrl + F8).
Break - Switches from run time to break mode.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 10
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Toggle Breakpoint - Defines a line in a module where Visual Basic suspends execution of theapplication
(F9).
Step Into - Runs the next executable line of code in the application and steps into procedures (F8).
Step Over - Executes the next executable line of code in the application without stepping intoprocedures
(Shift + F8).
Step Out - Executes the remaining lines of the current procedure and breaks at the next line in thecalling
procedure (Ctrl + Shift + F8) - check
Locals Window - Displays the Locals window to show the values of all the local variables.
Immediate Window - Displays the Immediate window to allow you to to run code or query valueswhile the
application is in break mode (Ctrl + G).
Watch Window - Displays Watch window to show values of selected expressions.
Quick Watch - Displays the Quick Watch window to show the values of expressions and variableswhile the
application is in break mode (Shift + F9).
Call Stack - Displays the Call Stack dialog box while in break mode that shows all procedures thathave been
called but not yet run to completion.
Customizing toolbar:
We can build our own custom toolbars or modify the displaying on any existing toolbar.
For example: if we want to add text description for a specify tool follow the steps
1. Right click inside the toolbar which want to customize
2. From the content menu that pops up choose Customize. The customize dialog box opens.
3. Right-click on the button we want to customize. This displays a pop up menu, and choose
Text only from that popup menu
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 11
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
4. Now a tiny toolbar pointed to here in the center of the customize dialog box.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 12
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Control Description
Pointer Provides a way to move and resize the controls form
PictureBox Displays icons/bitmaps and metafiles. It displays text or acts as a
visual container for 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 OptionButton control which is a part of an option group allows the
user to select only one option even it displays mulitiple choices.
ListBox Displays a list of items from which a user can select one.
ComboBox Contains a TextBox and a ListBox. This allows the user to select
an ietm from the 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
VScrollBar range of values
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
Image used to display images such as icons, bitmaps and metafiles. But
less capability than 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 based applications.
Label Displays a text that the user cannot modify or interact with.
To add new components to our toolbox that are already registered with windows, follow the 3 steps:
1. Choose project | component
2. From the dialog box choose which control want to add by clicking in the box that marks the
appropriate component.
3. Click OK
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 13
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 14
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Project Explorer:
Visual Basic organizes applications into what it calls projects.
Each project can have multiple forms, and the code that activates the controls on a form is
stored with the form in separate files.
General programming code shared by all the form in our application can be divided into
different modules, which are also stored separately.
The Project Explorer _is usually located at the far right of the screen.
It contains a Windows Explorer-like tree view of all the customizable forms and general code
(modules) that make up your application.
The Components item leads to a dialog box that was shown in Figure. The Add Tab item is to add a
new tab to the toolbox when you too many controls to fit easily
2. Toolbar:
If you right-click in the toolbar, you will see a context menu similar to this,
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 15
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
which lists all the toolbars that are available. (The checked ones are the ones that are visible.) Click
on any toolbar in the context menu to display or hide it. As you have seen, you can click on the
Customize option in order to add your own toolbars or to customize an existing toolbar.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 16
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
4. Project explorer:
There are actually two context menus available for the Project Explorer window: one for right-
clicking on a project or one of the objects, such as a form, and one for building a user control. The
functionality of both context menus is similar. The following illustration shows the context menu
when you click on a form:
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 17
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Menus:
The following Menus are available in Visual Basic IDE.
File Menu To open and save a new or existing project, to print and to make a
project.
Edit Menu For all existing requirement Cut, Copy, Paste, Find, Undo, etc
View Menu To view the various parts of your project.
Project Menu Inserting or removing forms or objects.
Format Menu for spacing, Placing and appearance controls in the form.
Debug Menu To remove the errors.
Run Menu To compile start and stop a program.
Tools Menu To add Procedure and to customize the environment for your
project.
Add-Ins Menu To add tools likes Data Manager, other Wizards, etc.
Windows Men arranging appearance of various windows.
Help Menu For the On-line help facility.
Altering a form:
The user can change the size and location of forms when the form is running or when the
form starts up. VB has ability to make dynamic changes in response to user events.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 18
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
The title bar of the Properties window says working with the properties of Form1.
The line below the title bar also tells what object we are working with; in this case it reads "Forml Form".
The highlighted line that reads "Caption" in the first column and "Form1" in the second column
The second column of the Properties window always indicates the current setting of the property.
The Settings box mostly works like an ordinary Windows text box as far as how you enter or edit
information
There's another method for changing the setting for a property, which some people prefer:
1. Move the mouse until the mouse pointer is in the right column of the correct line in the Properties
window.
2. Click at the location where you want to insert the text.
3. Enter the text you want to insert.
Finally, the default arrangement in the Properties window is alphabetical.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 19
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
To run VB application:
Select start option from toolbar
Select start option from run menu or by pressing ALT +R,S
Press F5
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 20
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Border style:
Visible:
To view the form in run time we use visible property.
Window state refers appearance of form in run time.
1- Reduces form to icon
2- Maximize the form
0- Normal (default)
SCALE PROPERTIES:
To place the object & control accurately inside the form this property is used.
Scale mode: it change units used in form‘s internal coordinate system
It uses one pixel as the scale.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 21
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Scale height, scale width: it is used to change the height and width of the form
Scaleleft, scaletop: It is used to set the distance between the form and the window in left and top
while executing. It is useful when working with graphics.
The user may change the Forecolor, Backcolor in VB. The format used to store the color details is the
hexadecimal format. The user may change the Backcolor and Forecolor properties via color palette.
COLOR PROPERTIES.
The color value is stored in hexadecimal format and it allow maximum of 16,777,216 different colors. The
user may click color and select color from either system or palette option. The user may even define our own
color and this could be done through define color. Here the user may set the hue and saturation values and
according to that the values may change.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 22
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
We can also create our own color palette. Each of the blank boxes on the bottom of the color palette
represents a possible custom color. To make one, follow these steps,
1. Click one of these blank boxes, and then click the Define Colors command (which is now
enabled). This opens the Define Color dialog box
2. Change the amount of red, green, or blue; color; hue; saturation; or luminosity of the color to suit
your needs by adjusting the controls in the dialog box.
3. Press the Add Color button to create the custom color or the Close button to cancel.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 23
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
UNIT – II
Building the User Interface: Toolbox – Creating Controls – Name Property - Properties of Command Buttons
- Image Controls - Text Boxes – Labels – Message Boxes – Grid. Anatomy of a VB Application – The Code
Window – Statement in Visual Basic – Variables – Data types – Working with Variables – Constants – Input-
Boxes
Text Box :Text box control is a versatile control. It can be used for getting the input from the
user and also display the result. It is called as Edit field or Edit control.
Picture Box : It can display a graphic from a bitmap, icon or metafile as well as enhanced
metafile, JPEG or GIF files.
Label Box : It allows you to display text that you don't want the user to change, such as
caption under a graphics.
Option Button : It allows you to display the multiple choices from which the user can choose
only one option.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 24
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Frame Control : The frame control allows you to create graphical or functional grouping
controls.
To group controls, draw the frame first and then draw controls inside the frame.
List Box : List box displays a list of items. It can occupy some space on the form.
Combo Box : Combo box is also used to display the items. But it can display a single item at a
time. It can occupy a less space on the screen.
Data Control : Data control provides access to database through controls on your form.
H Scroll Bar (Horizontal Scroll Bar) : Provides a graphical tool for quickly navigating
through a long list of items or a large amount of information for indicating the current position on a
scale, or as an input device or indicator of speed or quantity.
V Scroll Bar (Vertical Scroll Bar) : Provides a graphical tool for quickly navigating through a
long list of items or a large amount of information for indicating the current position on a scale, or as
an input device or indicator of speed or quantity.
Command Button : Creates a button that the user can choose to carry out a command. The user
will click on this button and the computer will perform the task associated with the button.
Check Box : It allows you to display the multiple choices from which the user can choose any
number of items.
Drive List Box, Directory List Box & File List Box : These controls are used to
display available Drives, Directories and Files. The user can select a valid Drive on his system. The
user can see a hierarchical structure of directories and files.
Line control and Shape control : These controls are used to draw lines, square, circles,
rectangles and etc.
Image control : It is very similar to the picture box control. Stretch property is available in
Image control. So we can easily resize the images.
OLE (Object Linking & Embedding) : This control allows you to link your program to
another object or program like as Ms Word, Internet Explorer, and Ms Word etc.
Timer control : It is a very important control. It is used for time-related processing. It is mainly
used in the auto save option.
CREATING CONTROLS:
We can get the control on a form by double clicking on its icon in the toolbox. This gives the default size and
shape in the middle of the form.
We can use combination of pointing, clicking, and dragging to manipulate the toolbox.
For example, to draw an item from the toolbox on a form at a specific location with a specific size:
Move the mouse pointer to the tool that the user wants to use and click
Move the mouse pointer to the form and draw the control
Hold the mouse button down and drag the mouse to create the object
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 25
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Use eight little boxes called sizing handles to resize the control
Locating controls only at grid points is called the aligning to the grid or snapping to the grid
Sizing handles
Simply click inside the control by moving the mouse pointer to the control and clicking once.
When the sizing handles are visible, know the control is selected.
The four corner handles let you change the height and width at the same time.
The mouse pointer changes to a double-sided diagonal arrow when you move the pointer to one of the corner
sizing handles.
The four side handles let you change the size in one direction only. At these handles, the mouse pointer
changes to a straight double-sided arrow.
Try resizing a control with the sizing handles by following these steps:
1. Move the mouse pointer to a sizing handle and click and hold down the left mouse button.
2. Drag the mouse until the control is the size you want.
Moving an existing control:
To move an existing control with the mouse, the focus must be at that control. To move an existing control:
Move the pointer anywhere inside the control, click the left mouse button and hold it down.
Drag the mouse until the control is at the location we want it to be and then release the left button.
For finer control movement select the control:
1. Select the control
2. Use ctrl + arrow key to move the control one grid mark at a time
3. Or, adjust the left and top properties in properties window.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 26
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
To create an application with three command buttons double click on the command button icons three times
Click on the tool it will create command buttons in the center of the screen.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 27
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
The alignment used for a group of controls is determined by the control in the group with the black sizing
handles and this is the last control selected in the group.
Choose Format->Align->Left all the controls will move to match up with the command2 control.
Locking controls:
Lock the controls by unnecessarily moving properly positioned controls.
Format->Lock Controls or
Lock Control tool from the toolbar
Deleting Controls:
To delete a control:
Move the mouse pointer until it is inside the control, and click the left mouse button to select it.
Press DEL or Open Edit menu->Choose Delete option by pressing ALT+ E,D.
End Sub
Rules for control name:
Must begin with a letter
After that, use any combination of letters, digits, and underscores.
Name cannot be longer than 40 characters.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 28
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
PROPERTY DESCRIPTION
Name The name of the object so you can call it at runtime
This specifies the command button's background color. Click the BackColor's
BackColor palette down arrow to see a list of common Windows control colours, you must
change this to the style property from 0 - standard to 1 - graphical
Determines whether the command button gets a Click event if the user presses
Cancel
escape
Caption Holds the text that appears on the command button.
Determins if the command button responds to an enter keypress even if another
Default
control has the focus
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 29
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Determines whether the command button is active. Often, you'll change the
Enable
enable property at runtime with code to prevent the user pressing the button
Produces a Font dialog box in which you can set the caption's font name , style
Font
and size.
Height Positions the height of the object - can be used for down
Left Positions the left control - can be used for right
If selected to an icon can change the picture of the mouse pointer over that
MousePointer
object
Hold's the name of an icon graphic image so that it appears as a picture instead
Picture
of a Button for this option to work the graphical tag must be set to 1
This determines if the Command Button appears as a standard windows dialog
Style
box or a graphical image
Tab index Specifies the order of the command button in tab order
Whether the object can be tabbed to ( this can be used in labels which have no
Tab Stop
other function )
If the mouse is held over the object a brief description can be displayed (for
Tool Tip Text
example hold your mouse over one of the above pictures to see this happening
Visible If you want the user to see the button/label select true other wise just press false
Width Show the width of the object
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 30
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 31
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Image controls are windowless objects that are managed by Visual Basic without creating a Windows object.
Image controls can load bitmaps and JPEG and GIF images.
It is used to display a graphic. An Image control can display a graphic from a bitmap, Icon, or metafile, as
well as enhanced metafile, JPEG, or GIF files.
PROPERTY DESCRIPTION DATA VALUE
Left, Top This property determines the distance
between the Image Control and the left
edge and top of the container (form),
respectively.
BorderStyle Returns/sets the border style of the object No border (setting =0)
(Default) Fixed Single border
(Setting=1)
Stretch Returns or sets a value indicating whether True-The graphic resizes to fit
a graphic resizes to fit the size of an Image the control.
control False-(Default) The control
resizes to fit the graphic.
Picture Returns or sets a graphic to be displayed in Picture(Bitmap, metafile, Icon
a control. etc)
The most important property of a image control is Stretch property. It determines whether the image control
adjusts to fits the picture, the picture adjust to fit the control.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 32
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
TEXTBOXES
Textbox is the primary methods of getting input and displaying the output in VB.
A text box object is used to display text on a form or to get user input while a VB is running
In a text box, a user can type data or paste it into the control from the clipboard.
The textbox never treat the user input as number and this means getting numeric input to VB program
requires transforming a string of digits into number by using built in function or automatic type
conversion
The following table summarizes the common TextBox control's properties and methods.
Property/ Method Description
Enabled specifies whether user can interact with this control or not
Index Specifies the control array index
Locked If this control is set to True user can use it else if this control is set to
false the control cannot be used
MaxLength Specifies the maximum number of characters to be input. Default
value is set to 0 that means user can input any number of characters
MousePointer Using this we can set the shape of the mouse pointer when over a
TextBox
Multiline By setting this property to True user can have more than one line in
the TextBox
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 33
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Method
SetFocus Transfers focus to the TextBox
Event procedures
Change Action happens when the TextBox changes
Click Action happens when the TextBox is clicked
GotFocus Action happens when the TextBox receives the active focus
LostFocus Action happens when the TextBox loses it focus
KeyDown Called when a key is pressed while the TextBox has the focus
KeyUp Called when a key is released while the TextBox has the focus
LABELS:
It is used to display static text, titles and screen output from operations.
It is used to identify a textbox or other control by describing its content.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 34
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
1-right-aligned
2-center
6. BorderStyle: Returns/sets the border style of the object. By setting the values as
No border (setting =0)
(Default) Fixed Single border (setting =1)
7. BackStyle: Determines whether the label is transparent or opaque.
8. Autosize: Determines whether a control is automatically resized to display its entire contents. By setting
the values as
True- resized according to the contents
False (default)-does not resizes.
9. WordWrap: Returns/sets a value that determines whether a control expands to fit the text in its caption.
By setting the values as
True- wraps the contents
False (default)-does not wraps the contents.
10. Multiline- True or False - if True, you can have several lines of text, by default, it is set to False
MESSAGE BOX
The message box displays a message in a dialog box, waits for the user to click a button, and returns an
integer indicating which button the user clicked.
Syntax:
Msgbox(Prompt,[buttons],[title])
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 35
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 36
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
THE GRID:
Grid is important for accurately positioning controls. In order to control the grid, choose Tools|Options
(ALT+T, O), and then go to the General page on the options dialog box, as shown in the figure.
This means that form is the name of the object and load is the event that you want to write the code for.
Click the down arrow button and the Drop Down list box will display all the controls that have been placed in
the form.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 37
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
If you intend to write the Command1, then select it from the list by clicking on it. Now click on the Down
arrow button on the other Drop down control. This will list all the events related to the selected object. The
lines given below provide a framework within which you can enter the code.
Private Sub Command1_Click ()
End Sub
The Private means that the variables declared and the code used here can be used only by this function. Then
we have the word Sub. This is short for Sub-routine or Function. Command1_Click() is the name of the
function which is self explanatory. End Sub means end of this subroutine.
Move to the event drop-down list box on the right and click the down arrow.
Move through the box until the user get to the click item.
Select Form_Click event and click on it.
Then Visual Basic does the following:
Gives the user a new event procedure template for the Form-Click event procedure
Adds a dotted line between the Form_Load event and the click event.
Moves the cursor to the blank line before the End Sub line in the click event procedure.
Output
When the user run the form and click once above the form it will show the following output
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 38
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 39
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
VARIABLES
In Visual Basic, Variables are used to store values temporarily during the execution of an application.
Variables have a name (the word use to refer to the value the variable contains) and a data type (which
determines the kind of data the variable can store). Variable is a placeholder in memory for an unknown value
Declaring Variables
To declare a variable is to tell the program about it in advance. Declare a variable with the Dim statement,
supplying a name for the variable:
Dim variablename [As type]
Variables declared with the Dim statement within a procedure exist only as long as the procedure is
executing. When the procedure finishes, the value of the variable disappears. In addition, the value of a
variable in a procedure is local to that procedure — that is, we can't access a variable in one procedure from
another procedure. A naming convention of a variable:
Must begin with a letter.
Can't contain an embedded period or embedded type-declaration character.
Must not exceed 255 characters.
Must be unique within the same scope, which is the range from which the variable can be referenced
— a procedure, a form, and so on.
The optional As type clause in the Dim statement allows us to define the data type or object type of the
variable that we are declaring. Data types define the type of information the variable stores. Some examples
of data types include String, Integer, and Currency
There are other ways to declare variables:
Declaring a variable using the Public keyword makes it available throughout our application.
Declaring a local variable using the Static keyword preserves its value even when a procedure ends.
Implicit Declaration:
In VB, don't have to declare a variable before using it. For example, we can write a function where we don't
need to declare TempVal before using it:
Function SafeSqr(num)
TempVal = Abs(num)
SafeSqr = Sqr(TempVal)
End Function
Visual Basic automatically creates a variable with that name, which we can use as if we have explicitly
declared it. While this is convenient, it can lead to subtle errors in our code if we misspell a variable name.
For example, suppose that this was the function we wrote:
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 40
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Function SafeSqr(num)
TempVal = Abs(num)
SafeSqr = Sqr(TemVal)
End Function
At first glance, this looks the same. But because the TempVal variable was misspelled on the next-to-last line,
this function will always return zero. When Visual Basic encounters a new name, it can't determine whether
we actually meant to implicitly declare a new variable or we just misspelled an existing variable name, so it
creates a new variable with that name.
Explicit Declaration
To avoid the problem of misnaming variables, we can stipulate that Visual Basic always warn us whenever it
encounters a name not declared explicitly as a variable.
To explicitly declare variables
Place this statement in the Declarations section of a class, form, or standard module:
Option Explicit
–or–
From the Tools menu, choose Options, click the Editor tab and check the Require Variable Declaration
option.
This automatically inserts the Option Explicit statement in any new modules, but not in modules already
created; therefore, we must manually add Option Explicit to any existing modules within a project.
Data Types
Variant: By default Visual Basic variables are of variant data types. The variant data type can store numeric,
date/time or string data. We can also declare explicitly a variable as variant. When a variable is declared, a
data type is supplied for it that determines the kind of data they can store .The fundamental data types in
visual basic including variant are integer, long, single, double, string, currency.
String: It is used to hold characters. It can be single character or many. A variable holding a string is called a
string variable. One method of identifying variables of this type is to place a dollar sign ($) at the end of the
variable name: a$=‘ABC‘
Integer: It is used to hold relatively small integer values (between –32,768 and +32,767). One method of
identifying variables of this type is to place a percent sign (%) at the end of the variable name: a$=3
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 41
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Long Integer: It is used to hold integer values (between –2,147,483,648 and 2,147,483,648). One method of
identifying variables of this type is to place a ampersand sign (&) at the end of the variable name:
a&=123456789
Single Precision: Just as there are two integer types for different size values, numbers with decimal points
have different variable types depending on how large and how accurate we want them to be. The least
accurate is called single precision. They have a decimal point, but of seven digits accuracy .It is used to hold
decimal values. One method of identifying variables of this type is to place a exclamation sign (!) at the end
of the variable name: a!=12.345
Double Precision: The double-precision data type is used when we need numbers with up to 16 places of
accuracy. These variables are mainly used in scientific calculations in Visual Basic. One method of
identifying variables of this type is to place a pound sign (#) at the end of the variable name: a#=12.345
Currency: This type can have 4 digits to the right of the decimal place and up to 15 to the left of the decimal
point. Arithmetic will be exact within this range. One method of identifying variables of this type is to place a
‗at‘ (@) at the end of the variable name: a@=12.345
Date: This type gives a convenient way to store both date and time information for any time between
midnight on January 1,100, to midnight on December 31, 9999. We need to surround any assignment to date
variables with two #‘s, for example: Millennium= #January 1,2000#
Byte: It is used to hold between 0 and 255.This is a great convenience when we need to save space , and it
makes certain arrays much smaller .
Boolean: It is used to hold data either true or false .It is considered good programming practice to use this
data type rather than integers for True/False values.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 42
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
3. Static: Variables have a lifetime in addition to scope. The values in module-level and public variables
are preserved for lifetime of an application whereas local variables declared with Dim, exist only
while the procedure in which they are declared is executing. The value of a local variable can be
preserved using Static keyword.
More on Strings
A String is simply a bunch of characters surrounded by double quotes.
String Concatenation
Concatenation of two Strings can be done using ampersand (&).For example:
Name1$=‖Visual‖
Name2$=‖Basic‖
Subject_name$=Name1 & Name2
MsgBox Subject_name
Output will be Visual Basic displayed using message box.
Fixed-Length Strings
A fixed-length string is a special type of string that plays an important role.These variables are created using
Dim statement .Here is an example:
Dim shortstring As String * 10
Dim strshort As String * 10
Both of these statements set up string variables However, this variable will always hold strings of length 10.If
we assign a longer string to shortstring ,as shown below
shortstring=‖antidisestablishment‖
We will get is the same thing as:
Shortstring=‖antidisest‖As we can also see, the variable contains only the left ten characters of the value.
Similarly, if we assign a shorter string to shortstring, like this,
Shortstring=‖a‖
We still get a string of length 10,only this time the contents of the variable are padded on the right so that the
string is really stored in the same way as:
Shortstring=‖a‖
Thus, fixed-strings are ―right padded‖ if necessary.
More on Numbers
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 43
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
We can use a decimal point, but if we assign such a number to an integer or long Integer variable, it will
automatically be rounded to an integer value. If we assign a number larger than the limits for the given
variable ,Visual Basic will give the user an error message at run time.
Here are some examples:
Number Acceptable in an assignment to a nume
variable?
3001 Okay for all number variables
3000001 Okay for all but short Integer variables
30000.01 Okay for all but integer variables (rounded
for them and for long integer variables)
3,001 Illegal because it uses a comma
Hierarchy of Operations:
The following list gives the order of operations:
Exponentiation
Negation (Making a number negative)
Division and Multiplication
Integer division
The remainder (Mod) function
Addition and Subtraction
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 44
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
CONSTANTS
Constants, like variables, are named storage locations in memory with local, form, module, or global scope.
Visual Basic prevents the value of a constant from being changed during program execution. It uses constants
more efficiently than variables, so if we plan to use a value that never changes, we should create a constant.
To create a constant, we use the Const statement with the following syntax:
For example: Const A =10
A naming convention of a constant:
Must begin with a letter.
Can't contain an embedded period or embedded type-declaration character.
Must not exceed 255 characters.
INPUT BOXES
Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns a String
containing the contents of the text box.
Following is an expanded InputBox
Syntax :
variablename = InputBox (prompt[,title][,default][,xpos][,ypos][,helpfile,context])
variablename is a variant data type but typically it is declared as string, which accept the message input by the
users.
The arguments are explained as follows:
Prompt - String expression displayed as the message in the dialog box. If prompt consists of more
than one line, the user can separate the lines using the vbCrLf constant
Title - String expression displayed in the title bar of the dialog box. If the user omit the title, the
application name is displayed in the title bar
default-text - The default text that appears in the input field where users can use it as his intended
input or he may change to the message he wish to key in.
x-position and y-position - the position or the coordinate of the input box.
The twp paratmeters helpfile and context are used together when the user have a help message
attached to the box.
Following example demonstrates the use of InputBox function
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 45
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
* Open a new project and save the Form as InputBox.frm and save the Project as InputBox.vbp
* Design the application as shown below.
Caption ( empty)
Label
Name lbl2
BorderStyle 1-Fixed Single
CommandButton Caption OK
Name cmdOK
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 46
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Here I have entered "Hello World" in text field. As soon as the user click OK the output is shown as shown
below
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 47
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
UNIT- III
Display Information on a Form - The Format Function - Picture Boxes – Rich Text Boxes – The Printer
Object - Determinate Loops - Indeterminate Loops – Making Decisions – Select Cases – Nested If- Then –
The GOTO – String Functions – Numeric Functions – Date and Time functions – Financial Functions
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 48
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Fixed
Displays a minimum of one digit to the left
E.g. Me.Print.Format (1234,‖Fixed‖)
and two to the right of the decimal point.
Gives the result 1234.00
Standard
E.g. Me.Print.Format (1234,‖Standard‖) The same as fixed, except that the number
Gives the result 1,234.00 is also formatted with thousands separators.
Date Formatting:
Date Formats has various values, they are given below
Format Name Description
General Date This is the most flexible date/time format. If the date
E.g. Me.Print.Format(Now,‖General Date‖) expression passed has only an integer portion, only the
Give result 12-10-99 9:14:25 PM date is displayed. Similarly, if it has only a decimal
portion, only the time is displayed
Long Date
This format will display a date in the format specified
E.g. Me.Print.Format(Now,‖Long Date‖)
by our system long date setting
Give result Thursday,December 10,1999
Medium Date
This format will display a date in the format specified
E.g. Me.Print.Format(Now,‖Medium Date‖)
by our system medium date setting
Give result 10-Dec-99
Short Date
This format will display a date in the format specified
E.g. Me.Print.Format(Now,‖Short Date‖)
by our system short date setting
Give result 12-10-99
Long Time
This format will display a date in the format specified
E.g. Me.Print.Format(Now,‖Long Time‖)
by our system long time setting
Give result 9:14:25 PM
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 49
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Medium Date
This format will display a date in the format specified
E.g. Me.Print.Format(Now,‖Medium Time‖)
by our system medium time setting
Give result 09:14 PM
Short Date
This format will display a date in the format specified
E.g. Me.Print.Format(Now,‖Short Time‖)
by our system short time setting
Give result 21:14
PICTURE BOXES
Like image control, picture boxes display icons, gifs, jpegs, bitmaps, and windows metafiles.
The following points describe a PictureBox control:
The pictureBox control comes with a light border around it.
Works as a container: You can place any other control on it, when you move the PictureBox control, all
the controls on it moves along with. That means, it works as a container of other controls.
Similarity with the Form: This control is so similar to a form as both of them support all the graphical
properties, graphical methods and conversion methods.
Supports all the graphical properties: It supports all the graphical properties such as AutoRedraw,
ClipControls, HasDC, FontTransparent, CurrentX, CurrentY, and the Drawxxxx, Fillxxxx, and Scalexxxx
properties.
Supports all the graphical methods: It supports all the graphical methods such as Cls, PSet, Point, Line,
and Circle.
Supports the conversion methods: It supports the conversion methods such as ScaleX, ScaleY,
TextWidth, and TextHeight.
Loading images: Using the Picture property, you can load a picture in design time and run-time. The
LoadPicture function is used to load the picture from your computer. This function is used with both the
PictureBox and Image controls.
We can programmatically load any image in the control using the LoadPicture function:
Picture1.Picture = LoadPicture("c:\windows\setup.bmp")
We can copy an image from one PictureBox control to another by assigning the target control's Picture
property:
Picture2.Picture = Picture1.Picture
The main advantages to using a picture box rather than a form to display data are that
1. Information displayed in a picture box will not be obscured by any controls on the form
2. Picture boxes are less memory-hungry.
3. We can have more than one picture box on a single form.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 50
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
This dialog box is accessed via the Project menu, Components item.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 51
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Once you check "Microsoft Rich Textbox Control 6.0" and click OK, the control is added to your toolbox
(also shown below, circled).
Then you can double-click it to make it appear on your form, as you would with any other control.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 52
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 53
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
DETERMINATE LOOPS
Controlling Program Flow: The parts of a programming language that let to repeat operations or make
decisions are often called Control Structures
Loop: the code that repeats an operation. Two types of loops:
1. Determinate loop: Repeating an operation to a fixed number of times
1. for next loop
2. Nested for loop
2. Indeterminate loop: Indeterminate loops run for an unknown number of repetitions until a condition
is true or while a condition is true.
Four types of indeterminate loops
1. do while. .. loop
2. do. .. until loop
3. while. .. wend loop
4. Do. ... loop while
The For. Next Loop
The For. Next Loop is another way to make loops in Visual Basic.
It comes under the category of determinant loop which means number of times loop repeats is known.
Repeats a group of statements a specified number of times.
Syntax:
For counterVariable = fromValue To toValue step stepvalue
...VB Statements...
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 54
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Next counterVariable
Example:
The following loop counts the numbers from 1 to 100:
Dim x As Integer
For x = 1 To 50
Print x
Next
In order to count the numbers from 1 to 50 in steps of 2, the following loop can be used
For x = 1 To 50 Step 2
Print x
Next
The following loop counts numbers as 1, 3, 5, 7..etc . The above coding will display numbers vertically on the
form.
Nested for:
A loop can be coded within another loop thus forming nested loops.
There can be many levels of nesting.
nesting is possible as long as the inner structure is completely enclosed in the outer structure.
When nesting loops, each loop must have a unique counter variable.
For example, nested loops are needed to display a table of values, to process the elements of a two-
dimensional array, or to sort array elements using the Bubble Sort algorithm
Syntax:
for counter-variable1=start-value to end-value[step step-value]
statements......
for counter-variable2=start-value to end-value[step step-value]
statements......
next counter-variable2
next counter-variable1
Example:
To print the elements of an 2x2 array
for i=1 to 2
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 55
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
for j=1 to 2
print a(i,j),
next j
print
next i
Exiting a For..Next Loop
The Exit For Statement is used to exit directly from the For …Next loop
The Syntax is
For counter=Start To End [Step Increment/Decrement] \
[Statements]
If [Condition] then
Exit For
End If
Next [Counter]
Flow Diagram of For…Next loop
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 56
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
INDETERMINATE LOOPS:
Four types of indeterminate loops
1. do while. .. loop
2. do. .. until loop
3. while. .. wend loop
4. Do. ... loop while
1. do while. ... loop :
The Do While. Loop is used to execute statements until a certain condition is met.
Syntax:
Do While (Expression)
(Code to execute)
Loop
(Expression) can be any legal logical expression that we wish to evaluate to determine whether or not
to exit the loop.
Each time the program reaches Loop it will verify that this expression is True, and if it is False, it will
exit the loop.
Thus, instead of exiting when an expression is True, it now exits only once this expression is false.
Example:
The following Do Loop counts from 1 to 100.
Dim number As Integer
number = 1
Do While number <= 100
number = number + 1
Loop
A variable number is initialized to 1 and then the Do While Loop starts.
First, the condition is tested; if condition is True, then the statements are executed.
When it gets to the Loop it goes back to the Do and tests condition again.
If condition is False on the first pass, the statements are never executed.
Syntax:
Do Until (Expression)
(Code to execute)
Loop
(Expression) can be any legal logical expression that we wish to evaluate to determine whether or not to
exit the loop.
Each time the program reaches Loop it will evaluate this expression.
If the expression is True, it will exit the loop , but otherwise it will continue looping.
Example for Do Until .. Loop statement:
The coding is typed inside the click event of the command button
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 57
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 58
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
MAKING DECISIONS
Control Structures allow applications written in visual Basic to respond to different situations depending upon
the result of a test Conditions. The Condition can be comparison or any expression that evaluates to a numeric
value
The available conditional Structures are:
If…Then Statements
If…Then…Else Statements
If….Then…ElseIf Statements
Select Case Statements
1. If...Then Statement:
Description: The If...Then statement examines the truthfulness of an expression.
Syntax:
If ( expression ) Then
Statement
End If
The program examines a condition. This expression can be a simple expression or a combination of
expressions.
If the expression is true, then the program will execute the Statement.
There are two ways we can use the If...Then statement.
If the conditional formula is short enough, we can write it on one line, like this:
If expression Then Statement
If there are many statements to execute as a truthful result of the condition, we should write the
statements on alternate lines.
Of course, you can use this technique even if the condition you are examining is short.
In this case, one very important rule to keep is to terminate the conditional statement with End If.
If expression Then
Statement
End If
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 59
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
VB comparison operators:
< Less Than
<= Less Than or Equal to
> Greater Than
>= Greater Than or Equal to
= Equal to
<> Not Equal to
Example:
Private Sub Command1_Click()
Dim var1 As Integer
var1 = 10
If var1 = 10 Then
MsgBox "The condition is true."
End If
End Sub
End If
End Sub
The expression is evaluated. If the resulting value is non-zero, the statement(s) after the Then are executed.
If there is an Else and if the expression evaluated to zero, the statement(s) after the Else are executed.
3. Nested If statement:
Description: The If...Then...ElseIf statement acts like the If...Then...Else expression, except that it offers as
many choices as necessary.
Syntax:
If ( expression = value_1 ) Then
Statements_1
ElseIf ( expression = value_2) Then
Statements_2
ElseIf ( expression = value_3) Then
Statements_3
…
Else
Statements_default
End If
The program will first examine expression1.
If expression1 is true, the program will execute Statments1 and stop examining conditions.
If expression1 is false, the program will examine expression2 and act accordingly.
Whenever a condition is false, the program will continue examining the conditions until it finds one.
Once a true condition has been found and its statement executed, the program will terminate the
conditional examination at End If.
Example:
Private Sub Form_Click()
If BackColor = vbRed Then
BackColor = vbBlue
ElseIf BackColor = vbBlue Then
BackColor = vbGreen
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 61
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
4. Select statement:
Description:
If we have a large number of conditions to examine, the If...Then...Else will go through each one of them.
Visual Basic offers the alternative of jumping to the statement that applies to the state of the condition.
Syntax:
The formula of the Select Case is:
Example:
Private Sub Form_Click()
Select Case BackColor
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 62
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Case vbRed
BackColor = vbBlue
Case vbBlue
BackColor = vbGreen
Case vbGreen
BackColor = vbBlack
Case Else
BackColor = vbRed
End Select
End Sub
THE GOTO
The Unconditional control transfer is performed using GoTo Statement.To use GoTo in VB, we must label a
line. Labels must begin with a letter and end with a colon. They must also start in the first column.
Syntax
GoTo LabelName
LabelName :
[Statements]
For Example:
If I=0 then
Goto AB
End If
AB:
MsgBox ―Using GoTo‖
STRING FUNCTIONS
A Built-In function is simply a prepackaged piece of code that accomplishes a single task. Visual Basic is
powerful in handling String functions. The some of the String functions are given below
Function name Syntax Description and its
usage
1.Space Space(NumberOfSpaces) Used to build up a
NumberOfSpaces-specifies the number of spaces string of spaces
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 63
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 64
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 65
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 66
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
NUMERIC FUNCTIONS
Visual Basic is powerful in handling Numeric functions. The some of the Numeric functions are given below
Function
Syntax Description and its usage
name
1.Fix Fix( Expression) Used to throw away the decimal
Expression is any valid numeric expression or number part of the number
2.Round Round(Expression[,number of decimal places]) Used to round the number to the
Expression is any valid numeric expression or number nearest possible integer
Number of decimal places specifies to round past the
decimal point
3.Sgn Sgn(Expression) Returns:
Expression is any valid numeric expression or number +1 If number is greater than 0;
0 If number is equal to 0;
-1 If number is less than 0;
4.Abs Abs(Expression) Returns the absolute value of the
Expression is any valid numeric expression or number number
5.Sqr Sqr(Expression) Returns the square root of number
Expression is any valid numeric expression or number
6.Exp Exp(Expression) Returns e raised to the power of
Expression is any valid numeric expression or number the number(e=2.7182)
7.Log Log(Expression) Returns the natural logarithm of
Expression is any valid numeric expression or number number
8.Sin Sin(Expression) Returns the sine value of number.
Expression is any valid numeric expression or number The number expresses an angle in
radians.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 67
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 68
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 69
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
FINANCIAL FUNCTIONS
Visual Basic comes with a library of financial functions for handling standard calculations that everyone will
occasionally need to do. Before going to financial functions, we have to see the definition for the terms such
as annuity, and what its value in the Mortgage and Retirement calculation. An annuity is a fancy term for a
series of payments made over time. For example, In Mortgage calculation, we have to start out with a (large)
amount, make (many) payments over time, and end up with a zero balance. In the retirement calculation we
made periodic payments over time and thereby ended up with a (large) amount of money at the end.
Function Syntax
Pmt (Pay out Pmt (RatePerPeriod, NumPeriods, WhatYouStartWith, WhatYouEndUpWith,
for annuity) WhenDoYorPay)
RatePerPeriod-Interest rate is quoted per year, but payment is every month. This entry
needs the interest rate per payment rate i.e. the interest rate should be divided by 12
NumPeriods- number of periods
WhatYouStartWith-i.e the initial balance
WhatYouEndUpWith-In Mortgage, this would be zero,For savings plan, this would be the
amount we want to end up with for retirement
WhenDoYouPay-tells about the payment to be paid 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. In all the entries (and the
result as well), moneys paid out are represented by negative numbers; moneys received are
represented by positive numbers.
Mrs.S.PUNITHAVLLI.,MSc.CS(DA)., 70
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 72
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
UNIT - IV
Function Procedures – Sub Procedures – Advanced Uses of Procedures and Functions – Lists: One–
Dimensional Arrays – Arrays with more than One–Dimension - Using Lists and Arrays with Functions and
Procedures – The With Statement - Enums – Control Arrays – List and Combo Boxes
– Menus – Menu Editor – MDI Forms
THE ANATOMY OF A PROCEDURE:
The procedure or Subroutine is the piece of code that gets executed when the control that it is
associated with senses an event. The event means mouse click, mouse move or method invoked bythe code.
Parts of a Procedure or Subroutine:
A procedure consists of the following things:
1. Name
2. Declaration Area
3. Statements
4. Call to Other procedures and/or functions.
5. Terminator.
1. Name:
Every procedure must have a name. The name of a procedure is usually tied to the control. You can
have a procedure called cmdExit_clcik(). This means that this procedure will be executed against the
―Click‖ event of the ―cmdExit‖ button. The ―Sub‖ before the name means that the procedure is a
Subroutine.
2. Declaration Area:
This area is used to declare all the variables, constants etc. However it is considered a good idea to
declare the entire variable at the beginning of the procedure. This makes it easy to locate variables and verify
the same during the process of debugging.
3. Statements:
The procedure deals with basic execution. Procedure will contain VBA (Visual Basic Application)
statements (or code if you like) that will perform the intended task. A procedure can have as many
statements as you care to add but keeping your procedures short and simple will render them easy to debug.
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 73
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
5. Terminator:
All good things come to an end. Every procedure (subroutine in the case) is terminated by the
―End Sub‖ statement.
Introduction to Procedures:
We can simplify programming tasks by breaking programs into smaller logical components. These
components — called procedures — can then become building blocks that let us to enhance and extend
Visual Basic.
Procedures are useful for condensing repeated or shared tasks, such as frequently used calculations, text and
control manipulation, and database operations.
There are two major benefits of programming with procedures:
Procedures allow breaking our programs into discrete logical units, each of which we can
debug more easily than an entire program without procedures.
Procedures used in one program can act as building blocks for other programs, usually with
little or no modification.
There are several types of procedures used in Visual Basic:
Sub procedures do not return a value.
Function procedures return a value.
Property procedures can return and assign values, and set references to objects.
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 74
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
FUNCTION PROCEDURES
Visual Basic includes built-in, or intrinsic functions, like Sqr, Cos or Chr.
In addition, we can use the Function statement to write our own Function procedures.The
syntax for a Function procedure is:
[Private|Public][Static]Function procedurename (arguments) [As type]
statements
End Function
Like a Sub procedure, a Function procedure is a separate procedure that can take arguments, perform
a series of statements, and change the value of its arguments. Unlike a Sub procedure, a Function procedure
can return a value to the calling procedure. There are three differences between Sub and Function
procedures:
Generally, we can call a function by including the function procedure name and arguments
on the right side of a larger statement or expression (return value = function()).
Function procedures have data types, just as variables do. This determines the type of the
return value. (In the absence of an As clause, the type is the default Variant type.)
We can return a value by assigning it to the procedure name itself. When the Function
procedure returns a value, this value can then become part of a larger expression.
For example, we can write a function that calculates the third side, or hypotenuse, of a right triangle, given the
values for the other two sides:
Function Hypotenuse (A As Integer, B As Integer) As String
Hypotenuse = Sqr(A ^ 2 + B ^ 2)
End Function
We can call a Function procedure the same way we call any of the built-in functions in Visual Basic:
Label1.Caption = Hypotenuse(CInt(Text1.Text), CInt(Text2.Text))strX = Hypotenuse(Width, Height)
Example: (Function)
Public Function Sum(n1 As Integer, n2 As Integer) As Integer
Sum=n1+n2
End Sub
The function ―Sum‖ called anywhere in the program. It can be called by simply passing the variables to it as
arguments. Consider the following event procedure.
Event Procedure:
Private Sub CmdFun1_Click()
Dim M1 As Integer Dim
M2 As Integer Dim Tot As
Integer
M1=val(Text1.Text)
M2=val(Text1.Text)
Tot=Sum(m1,m2)
End Sub
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 75
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
SUB PROCEDURES
A Sub procedure is a block of code that is executed in response to an event. By breaking the code ina
module into Sub procedures, it becomes much easier to find or modify the code in our application. The
syntax for a Sub procedure is:
[Private|Public][Static] Sub procedure name (arguments)
Statements
End Sub
Each time the procedure is called, the statements between Sub and End Sub are executed. Sub procedures
can be placed in standard modules, class modules, and form modules. Sub procedures are by default Public in
all modules, which means they can be called from anywhere in the application.
Example:
In this example, we create a sub procedure to sum up two values that are specified by the arguments The
main program can reference a procedure by using its name together with the arguments in the parentheses.
Private Sub cmdCal_Click()
Dim x As Single, y As Singlex
= Val(TxtNum1.Text)
y = Val(TxtNum2.Text)
sum x, y
End Sub
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 76
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
' Both of these statements call a Sub named MyProc.Call MyProc (FirstArgument,
SecondArgument)
MyProc FirstArgument, SecondArgument
Note that when we use the Call syntax, arguments must be enclosed in parentheses. If we omit the Call
keyword, we can also omit the parentheses around the arguments.
' All of the following statements would call a function' named ToDec.
Print 10 * ToDecX =
ToDec
If ToDec = 10 Then Debug.Print "Out of Range"X =
AnotherFunction(10 * ToDec)
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 77
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
It's also possible to call a function just like we would call a Sub procedure. The following statements both call
the same function:
Call Year(Now)Year
Now
When you call a function this way, Visual Basic throws away the return value.
Call Form1.SomeSub(arguments)
If two or more modules contain a procedure with the same name, we may need to qualify it with the module
name. A call to a common procedure from the same module runs the procedure in that module. For example,
with a procedure named CommonName in Module1 and Module2, a call to CommonName from Module2
will run the CommonName procedure in Module2, not the CommonName procedure in Module1.
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 78
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
A call to a common procedure name from another module must specify the intended module. For example, if
you want to call the CommonName procedure in Module2 from Module1, use:
Module2.CommonName(arguments)
For example:
Sub PostAccounts(ByVal intAcctNum as Integer)
.
. ' Place statements here.
.
End Sub
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 79
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
If we specify a data type for an argument passed by reference, we must pass a value of that type for the
argument. we can work around this by passing an expression, rather than a data type, for an argument. Visual
Basic evaluates an expression and passes it as the required type if it can.
The simplest way to turn a variable into an expression is to enclose it in parentheses. For example, to pass a
variable declared as an integer to a procedure expecting a string as an argument, you would dothe following:
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 80
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Example 1:
Dim Num(5) As Integer
―Num‖ is the set of 6 integers.
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 81
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Example 2:
Dim X(10 To 20) As Integer
―X‖ is the set of 11 integers.
X(10) is the first element.
X(20) is the eleventh and the last element.
ONE-DIMENSIONAL ARRAYS:
Declaring Fixed Size Arrays:
The scope of the array will depend upon the method of declaration.
1. To create a local array, use the Dim statement in a procedure to declare the array.
Dim Sum(10) As Single
2. To create a Module array, use the Private statement in the Declaration section of a
module to declare the array.
Private Ser(10) As Single
3. To create a Public array, use the Public statement in the Declaration section of a form.
Public Sun(10) As Single
4. In the case of fixed – size array it is compulsory to enter the upper bound of the array in
the parenthesis.
5. The upper bound is the upper limit for the size of the array.
To specify the lower bound of an array, provide it explicitly (as a long data type) using the TO
keyword.
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 82
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Example
Dim X As Integer
Dim SinX(24) As Integer
X=Lbound(SinX)
Debug.Print X
Dynamic Arrays:
Dynamic arrays are used when the user doesn‘t know the number of elements of an array.
Advantages:
1. A dynamic array can be resized at any time and this helps us to manage memory efficiently.
2. We can use a large array for a short time and then a free memory to the system when we are
no longer using the array.
3. We can increase the size of the array after having declared a smaller array.
ReDim: ReDim is used to declare the array as dynamic by giving it an empty dimension list.
Declaring a Dynamic Array:
We declare the array as dynamic by giving it an empty dimension list
Dim a()
Use the ReDim statement to allocate the actual number of elements.
ReDim
a(11,4)Example:
Dim a() As Integer
This statement will create an open –ended array
ReDim a(12,6)
This will create a two-dimensional array.
The values for the subscript of the array can be passed using variables.
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 83
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Example:
Dim a() As Integer Dim
Months As IntegerDim
Depts As Integer
Months = 12
Depts = 4
ReDim a(Months, Depts)
ReDim Statement: The ReDim statement is used at procedure level to relocate storage space for
dynamic array variables.
Syntax:
More on ReDim:
Only the upper bound of the last dimension in a multidimensional array can be changed when we usethe
Preserve keyword. If we change any other dimension, a run-time error will occur.
Example:
Dim a(11,2,4) As Integer
It can be resized using the Preserve keyword.
Example:
This example uses the ReDim statement to allocate and reallocate storage space for dynamicarray
variables.
Private Sub Form_Load()
Dim a() As Integer
ReDim a(5)
For i= 1 to 5
a(i)= i
Next i
End Sub
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 84
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Object: [Required] Variable or expression. Can evaluate to any data type, including elementarytypes.
Statements: [Optional] One or more statements between With and End With that run on object.
End With: [Required] Terminates the definition of the With block.
Example:
With yourname
.Name=‖howard‘
.Salary=100000
.Socsec=‖036-78-9987‖
End With
ENUMS
An enumeration, or Enum , is a symbolic name for a set of values. Enumerations are treated asdata
types, and we can use them to create sets of constants for use with variables and properties
Declare Enum
An Enum type has a name, an underlying type, and a set of fields, each representing a constant.
The name must be a valid Visual Basic qualifier. The underlying type must be one of the integertypes—
Byte, Short, Long or Integer. Integer is the default.
Example:
Public Enum Days
Sunday=1
Monday Tuesday
Wednesday
Thursday
Friday
Saturday
End Enum
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 85
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
CONTROL ARRAYS
Array is the collection of similar elements. Control Array is nothing but, collection of similar controls. These
controls are the elements of the Control array, which share the common properties. There are three ways to
create control arrays in Visual Basic, are
Using CTRL+C, CTRL+V to copy an existing control from one place on the form to another
Using the same control name for the controls in the form, more than once while designing a
visual basic application.
Using the index property of the controls
Working with a Control Array
Change procedure of a control present in the control array is different from the change procedure of the
ordinary control. The Change procedure of the control Array will have index as parameter. This parameter is
the key to the smooth functioning of control arrays.
Adding and Removing Controls in a Control Array
We can inadvertently add a control to a control array at design time; we can also remove it by changing the
control name or deleting the control at design time. The nifty part is that once we‘ve created array at design
time, we can add controls while the application is running. To do this, we use a method called Load
The Syntax for Load method is
Load ControlArrayName (Index)
Suppose we want to add three textboxes in the control array at run time, where there is a textbox
already created at run time. We have to write the following code to the form_load event procedure toadd
three textboxes at runtime.
Private Sub Form_Load()
Dim I As Integer
Const Spacing = 10
Text1(0).Move 0, 0
Text1(0).Text = "Text box in control Array #0" Text1(0).Width =
TextWidth(" Text box in control Array # 0 ")For I = 1 To 3
Load Text1(I)
Text1(I).Text = "Text box in control Array #" + Str(I) Text1(I).Width =
TextWidth(" Text box in control Array # " + Str(I))Text1(I).Move 0,
Text1(I - 1).Top + Text1(I - 1).Height + Spacing Text1(I).Visible = True
Next
IEnd Sub
At run time, we have to set the Visible property of the new control to true or else the new elements will not
appear on the form. We should properly position the controls in the form using the Move method, this
means that the newly created controls in a control array default to being stacked one ontop of the other.
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 86
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
The UnLoad Method is used to remove the controls from the control Array at run time
The Syntax of the UnLoad method is
UnLoad ControlArrayName(Index)
The following code will remove the text boxes from the control array which are created during run
time.
Private Sub Form_Click()
Static J As Integer If
J < 3 Then
Unload Text1(J + 1)J
=J+1
Else
Exit Sub
End
IfEnd Sub
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 87
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 88
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 89
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Using ComboBox
A Combo Box combines the features of Textbox. This control enables the user to select either bytyping
text into combo box or by selecting an item from list.
There are three types of Combo Box styles that are given below.
1. Dropdown Combo (style 0)
2. Simple Combo (style 1)
3. Dropdown list (style 2)
We select which type we want with the combo box Style property
A combo box is a combination of a text box and list box, so that at design time, we can change thetext in
the text box part by changing the Text property.
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 90
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
At run time we add items in the combo box using AddItem method
Example:
Private Sub Form_Load()
cmb1.AddItem "test1"
cmb1.AddItem "test2"
cmb1.AddItem "test3"
End Sub
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 91
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
MENUS
Creating and managing menu at Design Time:
Visual Basic applications can be enhanced by adding menus to it. It offers a convenient and
consistent way to group commands and easy way for users to access them.
The menu bar appears appear below the title bar and it may contain one or more menu titles.
When a menu title is clicked it displays a set of menu items under that title. Each menu item corresponds
to a menu control that is defined in a menu editor and performs a specific action.
MENU EDITOR
A menu editor can be used to add new commands to the existing bars. A menu editor can be added only after
opening a project. To display a menu editor command is chosen from the Tools menu or menu editor button
is clicked in the tool bar.
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 92
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 93
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Shortcut Keys
Shortcut keys are similar to access key has a special meaning in menu design, but inside a opening menu,
they run a command when pressed. To assign a shortcut key to a menu command, dropdown the shortcut list
in the menu editor and select a keystroke.
Run the application by pressing F5. We can see that you can select a menu
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 94
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
MDI FORMS:
MDI stands for Multiple Document Interface.
The Multiple Document Interface (MDI) was designed to simplify the exchange of
information among documents.
Each document is displayed in its own window, and all document windows have the same
behavior.
The main Form, or MDI Form, isn't duplicated, but it acts as a container for all the windows,
and it is called the parent window.
The windows in which the individual documents are displayed are called Child windows.
An MDI application must have at least two Form, the parent Form and one or more child
Forms. Each of these Forms has certain properties.
There can be many child forms contained within the parent Form, but there can be only one
parent Form.
The parent Form may not contain any controls.
While the parent Form is open in design mode, the icons on the ToolBox are not displayed,
but can't place any controls on the Form.
The parent Form usually has its own menu.
To create an MDI application, follow these steps:
1. Start a new project and then choose Project >>> Add MDI Form to add the parent Form.
2. Set the Form's caption to MDI Window
3. Choose Project >>> Add Form to add a SDI Form.
4. Make this Form as child of MDI Form by setting the MDI Child property of the SDI Form to
True. Set the caption property to MDI Child window.
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 95
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
When we click MDI Open we can notice that the main menu of the MDI Form is replaced with theMenu of the
Child Form.
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 96
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
UNIT – V
Introduction to Database - Working with Data Control: The Data Control - The Bound Control – Coding
– Data Access Object: Functions of the Jet Database Engine – The DAO Object Model - Crystal and
Data Reports: Crystal Report - Data Report – Creating Multiple Reports
INTRODUCTION TO DATABASE
Definitions:
Database
"A set of data related to a particular topic or purpose. A database contains tables and can also
contain queries and table relationships, as well as table and column validationcriteria."
Table
"A table is a collection of data, arranged in rows and columns. For example, you might have a
table for author information called authors. Each column would contain a certain type of
information, such as the author's last name. Each row would contain all the information about a
specific author: first name, last name, address, and so on."
Recordset
A recordset is an object that contains a set of records from the database. There are mainly five
types of Recordset object.
1. Table-Type Recordset: The table type recordset object is a set of records that
represents a single table can be used to add, change or delete records. They are
fastest type of Recordset.
2. Dynaset-Type Recordset: The dynaset-type recordset object is a set of records
that represent a table, or attachment tables, or the results of queries containing
fields from one or more tables. A dynaset enables us to update data from more
than one table.
3. Snapshot-Type Recordset: the snapshot type recordset can refer any table,
attached table or query. A snapshot cannot be updated and does not reflect
changes to data made by the users.
4. Dynamic type Recordset: This recordset type represent a query result set from
one or more base tables in which we can add, change or delete records from a row
returning query. Further, records that other users add, delete, or edit in the base
tables also appear in our recordset. This type is only available in ODBCDirect
workspace, and corresponds to an ODBC dynamic cursor.
5. Forward Only Type recordset: This recordset type is identical to a snapshot
except that we can only scroll forward through its records. This improves
performance in situations where only need to make a single pass through a result
set. In an ODBCDirect workspace, this type corresponds to an ODBC forward-
only cursor.
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 97
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
VB Data Control:
VB provides two controls which makes the link to the database file and which creates the recordset that
is exposed to the rest of the controls in your application. The two are identical in concept but differ in the
flexibilty they offer to the programmer.
1. Data control:
This is the original, intrinsic version of the control. It supports the JET database engine and can
satisfy most beginners' needs.
2. ADO Data control:
This is the latest version of the data control, implemented as an ActiveX control.
4. Start by drawing a Data control at the bottom of the Form. The Data control is your
gateway to the database.
5. With the Data control selected, locate its DatabaseName property, and set the path to
st_detail database.
6. Locate the RecordSource property in the Properties window, and drop down the list of
available entries. You‘ll see a list of all the tables in the st_detail database. Select the
student table.
7. Place three textboxes on the Form.
8. Select the first textbox, and in the Properties window locate its DataSource property. Set
it to Data1.
9. Set the DataField property of the textbox to Name. The DataField property is a drop-
down list with the names of all fields in the student table.
10. Set the DataSource property of the other textboxes to Data1, and set the DataField
property to Roll No, and Class.
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 98
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
Now run the application. The textboxes will display the values of the corresponding fields of the student
table. Using the Data control‘s buttons, you can move through the records (rows) of the table. Clicking
the leftmost button displays the first record of the table, and clicking the button next to it displays the
previous record. Clicking the rightmost button displays the last record of the table, and clicking the
button next to it displays the next record.
• Picture boxes
• Labels
• Text boxes
• Checkboxes
• Image controls
• OLE controls
• List boxes
• Masked edit controls
• Rich text boxes
• Combo boxes
In addition, there are special controls that are designed to be used as bound controls:
• DBList
• DBCombo
• FlexGrid
• MSFlexGrid
Finally, a number of bound controls are specially built to be used with the ADO control only:
• DataList
• DataCombo
• DataGrid
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 99
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
DAO objects encapsulate Access's Jet functions. Through Jet functions, it can also access other Structured
Query Language (SQL) databases.
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 100
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
The DBEngine is the highest-level object in the DAO object model. It contains all other objects and
collections. The Database object is the member of the Databases collection of the default Workspace
object, which is a member of the Workspaces collection of the DBEngine object.
With DAO, objects you use to work with the data in the database are generally not saved but are created
every time you need them. Objects that represent the structure of the database are saved with the database.
When you create a new DAO object to be saved in the database, you have to append it to the appropriate
collection using the collection's Append method. Keep in mind that all DAO objects are indexed
beginning with zero.
Jet and ISAM data use the Microsoft Jet object model; however, with ODBC data, you can use either
Microsoft Jet or ODBCDirect. There are some limitations in accessing ODBC data using Jet, although
you can use it if you need to take advantage of a particular Jet feature. But ODBCDirect is more flexible,
allowing you to run queries or stored procedures against the backend server and perform batch updates
and asynchronous queries. It also makes your application run faster because it allows you to bypass
Microsoft Jet's middle layer.
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 101
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
databases. Each type of database such as dBase, FoxPro, and Paradox etc has its own translator.
These translators are to be available to access the particular type of database.
Jet Engine can also access ODBC data sources using ODBC drivers.
Jet Engine also has its own query engine, which is used to search, order and filter the data without
using the query engine of the database. This may be an advantage with small databases such as
MS-Access and FoxPro, but for large databases such as Oracle database, using Jet query engine
may be inefficient.
Also remember DAO and Jet Engine are not designed for Internet or Intranet. To access data in
either
Internet or Intranet use ADO (ActiveX data objects) with OLE DB.
The DBEngine object contains two collections: Workspaces and Errors. The Workspaces collection is the
default collection of the DBEngine, so you don't have to refer to it explicitly. When you don't specifically
create a new Workspace object, DAO will create one for you. The setting of the DefaultType property of
DBEngine determines what type of workspace is created for Microsoft Jet or ODBCDirect. The default
value of this property is dbUseJet, but you can explicitly set it to dbUseODBC as the type argument of the
CreateWorkspace method.
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 102
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
The Workspace object defines a session for a user based on users' permissions and allows managing of
the current session. It also contains open databases and offers mechanisms for simultaneous transactions
and for securing the application. The Fields collection is the default collection for TableDef, QueryDef,
Index, Relation, and Recordset objects. Recordset objects can be of the following types: Table, Dynaset,
Snapshot, or Forward-Only.
Click on the Custom button to display the Choose Report Type and Data Type frames.
Select the Custom Report and click on the Data File.
Specify the location of the BIBLIO.MDB Access database.
Select which tables from the database you want. For this example we will need the authors table
and the Title table.
Check that the joins are correct in the Linking Export.
Now we are ready to draw the report.
Drag and drop the fields you want on to the report. So that it looks like the report above.
Now if you run it by selecting Print Preview, you can see what the report looks like.
Now save the report and we have a template that now can be used in VB.
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 103
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
There are many options in the Crystal Reports and as this tutorial is more of an overview I will not be going
into it. But one important thing to do is to get specific data. This is done by a selection formula (i.e. the Where
clause of a SQL statement).
The above formula will only show Authors that have had their book published in 1984.
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 104
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
2. Data Reports
We can create a Data Report. We will drag things out of the Data Environment onto a form
created for the Data Report, so make sure your Data Environment window is still available.
On the Project menu, click Add Data Report and one will be added to your project. If this item is
not on the menu, click Components. Click the Designers tab, and choose Data Report and click
OK to add the designer to your menu.
Set the following properties for the report:
Name: rptPhone
Caption - Phone Directory
DataSource - denPhone (your phone data environment - choose, don‘t type)
DataMember - PhoneList (the table name - choose don‘t type)
Right-click the Data Report and click Retrieve Structure. This establishes a report format based on the
Data Environment.
Note there are five sections to the data report: a Report Header, a Page Header, a Detail section, a Page
Footer, and a Report Footer. The headers and footers contain information you want printed in the report
and on each page. To place information in one of these regions, right-click the selected region, click Add
Control, then choose the control you wish to place. These controls are called data report controls and
properties are established just like you do for usual controls. Try adding some headers.
The Detail section is used to layout the information you want printed for each record in your database.
We will place two field listings (Name, Phone) there. Click on the Name tab in the Data Environment
window and drag it to the Detail section of the Data Report. Two items should appear: a text box Name
and a text box Name (PhoneList). The first text box is heading information. Move this text box into the
Page Header section. The second text box is the actual value for Name from the PhoneList table. Line this
text box up under the Name header. Now, drag the Phone tab from the Data Environment to the Data
Report. Adjust the text boxes in the same manner. Our data report will have page headers Name and
Phone. Under these headers, these fields for each record in our database will be displayed. When done,
the form should look something like this:
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 105
ASSISTANT PROFESSOR OF CS
SEM: V CLASS: III-B.Com.CA
SOFTWARE DEVELOPMENT WITH VISUAL PROGRAMMING
In this form, I‘ve resized the labels a bit and added a Report Header. Also, make sure you close
up the Detail section to a single line. Any space left in this section will be inserted after each
entry.
Click File and Save rptPhone As. Save the environment in an appropriate folder. We will now
reopen our phone database manager and attach this and the data environment to that project and
add capabilities to display the report.
Accessing the Data Report
Reopen the phone directory project. Add a command button named cmdReport and give it a Caption of
Show Report. (There may be two tabs in your toolbox, one named General and one named DataReport.
Make sure you select from the General tools.)
We will now add the data environment and data report files to the project. Click the Project menu item,
then click Add File. Choose denPhone and click OK. Also add rptPhone. Look at your Project Window.
Those files should be listed under Designers.
Use this code in cmdReport_Click:
Private Sub cmdReport_Click()
rptPhone.Show
End Sub
This uses the Show method to display the data report.
Save the application and run it. Click the Show Report button and this should appear:
3. Multiple Report
To create a report
In Visual Studio, create or open a Report Server project. For more information, see Create a
Report Server Project for Visual Studio ALM.
On the Project menu, choose Add New Item.
o The Add New Item dialog box appears.
Choose Report Wizard, and then choose Add.
o The Report Wizard opens to the Select Data Source page.
Choose the Tfs2010OlapReportDS shared data source, and then choose Next.
o Even though you might have installed or upgraded to TFS 2013, these names, which were
assigned to the data sources for TFS 2010 are in use.
Mrs.S.PUNITHAVALLI.,MSc.SC(DA)., 106
ASSISTANT PROFESSOR OF CS