VB CS-Final Notes
VB CS-Final Notes
INTRODUCTION
Visual Basic is a third-generation event-driven programming language first released by
Microsoft in 1991.
The final version was Visual Basic 6.0 before the release of Visual Basic.NET.
Visual Basic is a user-friendly programming language designed for beginners, and it
enables anyone to develop GUI window applications easily.
Features such as easier comprehension, user-friendliness, faster application
development and many other aspects such as introduction to ActiveX technology and
internet features make visual basic an interesting tool to work with.
2
Integrated Development Environment
It is commonly used in the programming world to describe the interface and environment that
we used to create our applications. it is called integrated because we can access virtually all
of the development tools that we need from one screen called an interface. It is commonly
referred to as the design environment or the program.
MENU BAR
Menu bar displays the command that is required to build an application. The main
menu items have sub menu items that can be chosen when needed, selecting one of the
choices (File, Edit, view, Project, Format,… Help) causes one of Visual Basic’s drop-down
menus to appear. The menus present logical groupings of Visual Basic’s individual features.
The toolbars in the menu bar provide quick
access to the commonly used commands and a button in
the toolbar is clicked one ton carry out the action
represented by it.
TOOL BOX
The Toolbox contains icons that represent
commonly used controls, such as label, text box,
command button, picture box, frame, picture box,
option button, file list box, and so on.
The user can select a control from a toolbox and
place it in the current form design window by double clicking on the control icon, or by
clicking once the control icon, then clicking on the desired location within the Form design
Window and dragging the mouse so that the control has the desired size.
Select Objects
Select Objects is the only item in the Toolbox that doesn't draw a control.
3
Label - Allows to have text that do not want the user to change, such as a caption
under a graphic.
Text Box - Holds text that the user can either enter or change.
Combo Box - Allows to draw a combination list box and text box. The user can either
choose an item from the list or enter a value in the text box.
List Box - Use to display a list of items from which the user can choose. The list can be
scrolled if it has more items than can be displayed at one time.
Check Box - Creates a box that the user can easily choose to indicate if something is
true or false, or to display multiple choices when the user can choose more than one.
Option Button - Allows displaying multiple choices from which the user can choose
only one.
Command Button - Creates a button the user can choose to carry out a command.
Tab Strip - Allows defining multiple pages for the same area of a window or dialoging
box in application.
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.
Spin Button - A spinner control can use with another control to increment and
decrement numbers. It can also use it to scroll back and forth through a range of values or a
list of items.
Image - Displays a graphical image from a bitmap, icon, or metafile on the form.
Images displayed in an Image control can only be decorative and use fewer resources than
a Picture Box.
4
Project Explorer Window
The project window displays a hierarchical list of the files associated with a given
project. These files represent individual forms and modules. The user can display a form or
module within the Project Container Window by double-clicking on the corresponding icon
within the Project Window. The user can select either the Object View or the Code view by
clicking on one of the two leftmost icons within the toolbar at the top of the Project Window.
Properties Window
Every object has properties associated with it. Each object has its unique list of
Properties. The properties window allows the user to assign or change the properties
associated with a particular object.
Active the object by clicking on it; then choose from the corresponding list of properties
shown in the left column of the properties window.
Object Browser
The Object Browser allows to browse through all
available objects in the project and see
their properties, methods and events. In addition,
the procedures and constants that are available
from object libraries in the project. It can easily
display online Help as browse. It can use
the Object Browser to find and the use created
objects, as well as objects from other applications. Get help for the Object Browser by
searching for Object Browser in Help.
2. From the View menu, choose Object Browser (F2), or use the toolbar shortcut: .
3. Select the name of the project or library to view in the Project/Library list.
4. Use the Class list to select the class; use the Member list to select specific members
of class or project.
5. View information about the class or member selected in the Details section at the
bottom of the window.
6. Use the Help button to display the Help topic for the class or member selected.
5
Object Related Concepts
Objects: Forms and controls are collectively referred to as objects. Objects are also
associated with their own properties and method.
Forms: In VB a window is called a form. Each form includes a title bar at the top. A
form may also include a menu bar, a status bar, one or more tools bars, slide
bars, etc. A user area occupies the remaining space with in the form.
Controls: The icons with which the user interacts are called controls. The user will
typically activate a control to produce an event.
Properties: Objects includes properties that generally define the appearances and
behaviors. For eg. Name, caption, height, back ground color.
Methods: Some objects also include special program statements called methods. A
method brings about some user predefined action affecting the associated
objects.
Events and Event Procedures
VB is based up on an event driven paradigm, in which each feature included within
the program is activated only when the user responds to a corresponding object within the
user interface. Event: The programs responds to an action taken by the user is referred to as
an event. Event Procedure: The group of basic commands that brings out about this
response is called an event procedure.
6
Restore: Restores a maximized Form to the size it was before it was maximized;
available only if the Form has been maximized.
Move : Lets the user moves the Form around with the mouse
Size : Lets the user resizes the control with the mouse
Minimize: Minimizes the Form
Maximize : Maximizes the Form
Close : Closes the Form
Form Properties
7
3 Font This property specify font type, style, size
6 MinimumSize This specifies the minimum height and width of the window
can minimize.
7 MaximumSize This specifies the maximum height and width of the window
maximize.
9 StartPosition This property determines the initial position of the form when
it's first displayed. It will have any of the following values:
CenterOwner: The form should be shown in the
center of the form that owns it.
CenterScreen: The form is center of the user screen.
Manual: The location and size of the form will
determine its starting position.
Windows Default: It lets windows decide where the
form should be shown.
10 Text The text, which will appear at the title bar of the form.
8
Hiding Forms
The Hide method is used to hide a Form. The following is the syntax of the Hide Method.
FormName.Hide
To hide a Form from within its own code, the following code can be used.
Me.Hide
9
Creating an Executable File
User can create an executable file in Visual Basic by choosing Make EXE file command
from the File menu. A Make EXE dialog box appears. Now the File is saved as calculate.exe
in the required directory or hard disk and the ok button is clicked. As the application is
converted into an executable file the user can run it on any other windows program.
Ending an application
The End statement is used to terminate the execution of the application. It unloads all forms
from memory.
MODULES
Code in Visual Basic is stored in the form of modules. The three kinds of modules are
1. Form Modules,
2. Standard Modules and
3. Class Modules.
A simple application may contain a single Form, and the code resides in that Form
module itself. As the application grows, additional Forms are added and there may be a
common code to be executed in several Forms.
To avoid the duplication of code, a separate module containing a procedure is created
that implements the common code. This is a standard Module.
10
Class module (.CLS filename extension) is the foundation of the object oriented
programming in Visual Basic. New objects can be created by writing code in class modules.
Each module can contain:
Declarations: May include constant, type, variable and DLL procedure declarations.
Procedures: A sub function, or property procedure that contain pieces of code that can be
executed as a unit.
DATA TYPES
By default Visual Basic variables are of variant data types. The variant data type can
store numeric, date/time or string data. 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, byte and boolean. A list of Visual Basic's simple data types are
given below.
1. Numeric
Double Store large floating value which exceeding the single data type value
2. String
Use to store alphanumeric values. A variable length string can store approximately 4 billion
characters
3. Date
Use to store date and time values. A variable declared as date type can store both date and
time values and it can store date values 01/01/0100 up to 12/31/9999
11
4. Boolean
Boolean data types hold either a true or false value. These are not stored as numeric values
and cannot be used as such. Values are internally stored as -1 (True) and 0 (False) and any
non-zero value is considered as true.
5. Variant
Stores any type of data and is the default Visual Basic data type. In Visual Basic if we declare
a variable without any data type by default the data type is assigned as default.
VARIABLES
Variables are the memory locations which are used to store values temporarily. A
defined naming strategy has to be followed while naming a variable. A variable name must
begin with an alphabet letter and should not exceed 255 characters. It must be unique within
the same scope. It should not contain any special character like %, &, !, #, @ or $. Must not
be a reserved word (that is part of the code, like Option, for example). The different ways of
declaring variables in Visual Basic are listed below
Explicit Declaration
Using Option Explicit statement
Scope of Variables
Explicit Declaration
Declaring a variable tells Visual Basic to reserve space in memory. It is not must that
a variable should be declared before using it. Automatically whenever Visual Basic
encounters a new variable, it assigns the default variable type and value. This is called
implicit declaration.. The variables are declared with a Dim statement to name the variable
and its type. The As type clause in the Dim statement allows to define the data type or object
type of the variable. This is called explicit declaration.
Syntax
Dim variable [As Type]
For example,
Dim strName As String
Dim intCounter As Integer
12
Using Option Explicit statement
It may be convenient to declare variables implicitly, but it can lead to errors that may
not be recognized at run time. Say, for example a variable by name intcount is used implicitly
and is assigned to a value. In the next step, this field is incremented by 1 by the following
statement
Intcount = Intcount + 1
This calculation will result in intcount yielding a value of 1 as intcount would have
been initialized to zero. In Visual Basic, to prevent errors of this nature, we can declare a
variable by adding the following statement to the general declaration section of the Form.
Option Explicit
This forces the user to declare all the variables. The Option Explicit statement checks
in the module for usage of any undeclared variables and reports an error to the user. The
Option Explicit statement can be explicitly placed in the general declaration section of each
module using the following steps.
Click Options item in the Tools menu
Click the Editor tab in the Options dialog box
Check Require Variable Declaration option and then click the OK button
Scope of Variables
A variable is scoped to a procedure-level (local) or module-level variable depending
on how it is declared. The scope of a variable, procedure or object determines which part of
the code in our application is aware of the variable's existence.
Local Variables
A local variable is one that is declared inside a procedure. This variable is only available to
the code inside the procedure and can be declared using the Dim statements as given below.
Dim sum As Integer
The local variables exist as long as the procedure in which they are declared, is
executing. Variables that are declared with keyword Dim exist only as long as the procedure
is being executed.
Static Variables
Static variables are not reinitialized each time Visual Invokes a procedure and
therefore retain or preserve value even when a procedure ends. In case we need to keep track
of the number of times a command button in an application is clicked, a static counter
13
variable has to be declared. These static variables are also ideal for making controls
alternately visible or invisible. A static variable is declared as given below.
Static intPermanent As Integer
Variables have a lifetime in addition to scope. The values in a module-level and
public variables are preserved for the lifetime of an application whereas local variables
declared with Dim exist only while the procedure in which they are declared is still being
executed.
Example
The following is an example of an event procedure for a CommandButton that counts
and displays the number of clicks made.
Private Sub Command1_Click ( )
Static Counter As Integer
Counter = Counter + 1
Print Counter
End Sub
The first time we click the CommandButton, the Counter starts with its default value
of zero. Visual Basic then adds 1 to it and prints the result.
14
1.6 PROCEDURES AND CONTROL STRUCTURES
Visual Basic offers different types of procedures to execute small sections of coding
in applications. Visual Basic programs can be broken into smaller logical components called
Procedures. Procedures are useful for condensing repeated operations such as the frequently
used calculations, text and control manipulation etc. The benefits of using procedures in
programming are:
It is easier to debug a program a program with procedures, which breaks a program
into discrete logical limits.
Procedures used in one program can act as building blocks for other programs with
slight modifications.
A Procedure can be Sub, Function or Property Procedure.
Sub Procedures
A sub procedure can be placed in standard, class and form modules. Each time the
procedure is called, the statements between Sub and End Sub are executed. The syntax for a
sub procedure is as follows:
[Private | Public] [Static] Sub Procedurename [( arglist)]
[ statements]
End Sub
arglist is a list of argument names separated by commas. Each argument acts like a variable
in the procedure. There are two types of Sub Procedures namely general procedures and
event procedures.
Event Procedures
An event procedure is a procedure block that contains the control's actual name, an
underscore(_), and the event name. The following syntax represents the event procedure for a
Form_Load event.
Private Sub Form_Load()
....statement block..
End Sub
Event Procedures acquire the declarations as Private by default.
General Procedures
A general procedure is declared when several event procedures perform the same
actions. It is a good programming practice to write common statements in a separate
procedure (general procedure) and then call them in the event procedure.
15
In order to add General procedure
The Code window is opened for the module to which the procedure is to be added.
The Add Procedure option is chosen from the Tools menu, which opens an Add
Procedure dialog box as shown in the figure given below.
The name of the procedure is typed in the Name textbox
Under Type, Sub is selected to create a Sub procedure, Function to create a
Function procedure or Property to create a Property procedure.
Under Scope, Public is selected to create a procedure that can be invoked outside
the module, or Private to create a procedure that can be invoked only from within
the module.
Function Procedures
Functions are like sub procedures, except they return a value to the calling procedure.
They are especially useful for taking one or more pieces of data, called arguments and
performing some tasks with them. Then the function returns a value that indicates the results
of the tasks complete within the function.
16
CONTROL STRUCTURES
Control Statements are used to control the flow of program's execution. Visual Basic
supports control structures such as if... Then, if...Then ...Else, Select...Case, and Loop
structures such as Do While...Loop, While...Wend, For...Next etc method.
Branching Explanation Syntax Example
If...Then It performs an indicated If <condition> Then If average>75 Then
statement action only when the statement txtGrade.Text = "A"
condition is True; End If End If
otherwise the action is
skipped.
Nested This selection structures If < condition 1 > If average > 75 Then
If...Then...Else test for multiple cases by Then txtGrade.Text = "A"
statement placing If...Then...Else statements ElseIf average > 65 Then
Selection structures ElseIf < condition 2 > txtGrade.Text = "B"
inside If...Then...Else stru Then Else
ctures. statements txtGrade.Text = "F"
Else End If
Statements
End If
17
than the If...Else...End If. Case 1 Case 100 To 75
Statements txtGrade.Text ="A"
End Select
Case 74 To 65
txtGrade.Text ="B"
Case Else
MsgBox "Invalid average
marks"
End Select
18
Do Statements in the body of Do Until<condition> Dim number As Long
Until...Loop a Do Until...Loop are Statements number=0
Statement executed repeatedly as long Loop Do Until number > 1000
as the loop-continuation test number = number + 1
evaluates to False. Print number
Loop
Exit For The Exit For statement is For < condition > Dim x As Integer
statement executed and it terminates Statements For x = 1 To 10
the For...Next loop. If < condition > Print x
Then If x = 5 Then
Statements Print "The program exited at
Exit For x=5"
End If Exit For
Next End If
Next
Exit Do Do...While loop is Do While < Dim x As Integer
statement terminated using Exit Do condition > Do While x < 10
statement Statements Print x
If < condition > x=x+1
Then If x = 5 Then
Statements Print "The program is exited
Exit Do at x=5"
End If Exit Do
Loop End If
Loop
19
With...End Multiple properties can be With Text1
With set and multiple methods can .Font.Size = 14
statement be called by using .Font.Bold = True
the With...End .ForeColor = vbRed
With statement. .Height = 230
.Text = "Hello World"
End With
ARRAYS
An array is a consecutive group of memory locations that all have the same name and
the same type.
To refer to a particular location or element in the array, we specify the array name and
the array element position number.
The Individual elements of an array are identified using an index.
Arrays have upper and lower bounds and the elements have to lie within those
bounds.
We can declare an array of any of the basic data types including variant, user-defined
types and object variables.
The individual elements of an array are all of the same data type.
Declaring arrays
Arrays may be declared as Public (in a code module), module or local. Module arrays are
declared in the general declarations using keyword Dim or Private. Local arrays are declared
in a procedure using Dim or Static. Array must be declared explicitly with keyword "As".
There are two types of arrays in Visual Basic namely:
Fixed-size array: The size of array always remains the same-size doesn't change
during the program execution.
Dynamic array: The size of the array can be changed at the run time- size changes
during the program execution.
Fixed-sized Arrays
When an upper bound is specified in the declaration, a Fixed-array is created. The
upper limit should always be within the range of long data type.
Declaring a fixed-array
Dim numbers(5) As Integer
20
In the above illustration, numbers is the name of the array, and the number 6 included
in the parentheses is the upper limit of the array. The above declaration creates an array with
6 elements, with index numbers running from 0 to 5.
If we want to specify the lower limit, then the parentheses should include both the
lower and upper limit along with the To keyword. An example for this is given below.
Dim numbers (1 To 6 ) As Integer
A public array can be declared using the keyword Public instead of Dim as shown
below.
Public numbers(5) As Integer
Multidimensional Arrays
A common use of multidimensional arrays is to represent tables of values consisting
of information arranged in rows and columns.
To identify a particular table element, we must specify two indexes: The first (by
convention) identifies the element's row and the second (by convention) identifies the
element's column.
Note that multidimensional arrays can have more than two dimensions. Visual Basic
supports at least 60 array dimensions.
The following statement declares a two-dimensional array 50 by 50 array within a
procedure.
Dim AvgMarks ( 50, 50)
It is also possible to define the lower limits for one or both the dimensions as for fixed
size arrays. An example for this is given here.
Dim Marks ( 101 To 200, 1 To 100)
An example for three dimensional-array with defined lower limits is given below.
Dim Details( 101 To 200, 1 To 100, 1 To 100)
Classification of Controls
Visual Basic controls are broadly classified as standard controls, ActiveX controls and
insertable objects.
Standard controls such as CommandButton, Label and Frame controls are contained
inside .EXE file and are always included in the ToolBox which cannot be removed.
ActiveX controls exist as separate files with either .VBX or .OCX extension. They
include specialized controls such as;
1) MSChart control
2) The Communications control
3) The Animation control
4) The ListView control
5) An ImageList control
6) The Multimedia control
7) The Internet Transfer control
8) The WinSock control
9) The TreeView control
10) The SysInfo control
11) The Picture Clip control
Some of these objects support OLE Automation, which allow programming another
application's object from within Visual Basic application.
23
By default, Visual Basic assigns a tab order to control as we draw the controls on the
Form, except for Menu, Timer, Data, Image, Line and Shape controls, which are not
included in tab order. Setting the Tab Index property of controls is compulsory in
development environment.
TEXTBOX CONTROL
A Text Box control, sometimes called an edit field or edit control, displays
information entered at design time.
Enabled Specifies whether user can interact with this control or not
Using this we can set the shape of the mouse pointer when over a
MousePointer
TextBox
GotFocus Action happens when the TextBox receives the active 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
LABEL CONTROL
The Label control represents a standard Windows label. It is generally used to display
some informative text on the GUI which is not changed during runtime. Let's create
a label by dragging a Label control from the Toolbox and dropping it on the form.
3 Font Gets or sets the font of the text displayed by the control.
25
7 TextAlign Gets or sets the alignment of text in the label.
26
Assigning the value property to True in code like
Optional.value=true
Using the shortcut keys specified in the Caption of a
label.
To disable the option button at run time, its Enabled property is
set to false.
LIST BOX
ListBox and ComboBox controls present a set of choices that are displayed vertically
in a column. If the number of items exceed the value that be displayed, scroll bars will
automatically appear on the control. These scroll bars can be scrolled up and down or left to
right through the list. The following Fig lists some of the common ComboBox properties and
methods.
Property/Method Description
Index Specifies the Control array index
String array. Contains the strings displayed in the drop-down
List
list. Starting array index is 0.
ListCount Integer. Contains the number of drop-down list items
Integer. Contains the index of the selected ComboBox item. If
ListIndex
an item is not selected, ListIndex is -1
Style Integer. Specifies the style of the ComboBox's appearance
Boolean. Specifies whether ComboBox receives the focus or
TabStop
not.
Text String. Specifies the selected item in the ComboBox
27
Combo1.AddItem 1
Combo1.AddItem 2
Combo1.AddItem 3
Combo1.AddItem 4
Combo1.AddItem 5
Combo1.AddItem 6
End Sub
28
can select an item from the list or type an item in the edit box portion of the combo
box.
2. The Dropdown Combo box first appears as
only an edit area with a down arrow button at
the right. The list portion stays hidden until the
user clicks the down-arrow button to drop
down the list portion.
3. The Dropdown list combo box turns the combo
box into a Dropdown list box. At run time , the
control looks like the Dropdown combo box. The user could click the down arrow to
view the list.
4. The difference between Dropdown combo & Dropdown list combo is that the edit
area in the Dropdown list combo is disabled.
Example
This example is to Add , Remove, Clear the list of items and finally close the
application. Open a new Standard EXE project is opened an named the Form as Listbox.frm
and save the project as Listbox.vbp. Design the application as shown below.
29
The click event of the Add button adds the text to the list box that was typed in the
Text box. Then the text box is cleared and the focus is got to the text box. The number of
entered values will is increased according to the number of items added to the listbox.
Private Sub cmdClear_Click()
lstName.Clear
lblDisplay.Caption = lstName.ListCount
End Sub
Private Sub cmdExit_Click()
Unload Me
End Sub
Private Sub cmdRemove_Click()
Dim remove As Integer
remove = lstName.ListIndex 'Getting the index
If remove >= 0 Then 'make sure an item is selected
'in the list box
lstName.RemoveItem remove 'Remove item from the list box
lblDisplay.Caption = lstName.ListCount 'Display the number of items
'in the listbox
End If
End Sub
SCROLLBAR
The ScrollBar is a commonly used control, which enables the user to select a value by
positioning it at the desired location. It represents a set of values.
The Min and Max property represents the minimum and maximum value.
The value property of the ScrollBar represents its current value, that may be any
integer between minimum and maximum values assigned.
The HScrollBar and the VScrollBar controls are perfectly identical, apart from their
different orientation.
eg:
Private Sub Text1_GotFocus()
' Pass the focus to the scroll bar.
HScroll1.SetFocus
End Sub
Private Sub HScroll1_Change()
30
' Scroll bar controls the text box value.
Text1.Text = HScroll1.Value
End Sub
33
UNIT II
2.1 MENUS
Menus are intrinsic controls, and as such they deserve a place
in this chapter. On the other hand, menus behave differently
from other controls
Visual Basic provides an easy way to create menus with the
modal Menu Editor dialog. The below dialog is displayed
when the Menu Editor is selected in the Tool Menu.
Basically, each menu item has a Caption property (possibly with an embedded &
character to create an access key) and a Name. Each item also exposes three Boolean
properties, Enabled, Visible, and Checked, set both at design time and at run time.
MENU INTERFACE
Visual Basic applications can be enhanced by adding menus to it. It offers a
convenient and consistent way to group commands and an easy way for users to access them.
The menu bar appears below the title bar and it may contain one or more menu titles.
An expanded Menu Editor window
An expanded menu
34
Checked: This is unchecked by default and allows the programmer the option of creating a
checked menu item( a menu item that act as a toggle and displays a check mark when
selected. The following is a Check Menu items.
Enabled: specifies whether a menu is disabled or not. If a disabled command in a menu that
means that feature is not available. The Visible checkbox specifies whether the menu is
visible or not.
Creating Menus
Open a new Project and save the form as
menu.frm and save the project as menu.vbp.
Choose Tools ››› Menu Editor and type the
menu items as shown below.
Caption Name
File mnuFile
Open mnuOpen
Save mnuSave
Exit mnuExit
Edit mnuEdit
Copy mnuCopy
Cut mnuCut
Paste mnuPaste
35
-------Mnu1a -------Mnu1a -------Mnu1a
---Mnu3 -------Mnu1b
---Mnu2
---Mnu3
36
Positioning a control
Mouse Down is the commonly used event and it is combined with the move method
to move an Image control to different locations in a Form. The following application
illustrates the movement of objects responding to move events. It makes use of two Option
Button Controls, two image controls and a Command Button. The application is designed in
such a way that when an Option Button is selected, the corresponding image control is placed
anywhere in the form whenever it is clicked. Open a new standard EXE project and save the
Form as Move.frm and save the project as Move.vbp Design the Form as shown below.
The following code is entered in the general declarations section of the Form.
Option Explicit
37
If optCredit = True Then
imgCredit.Move X, Y
Else
imgCash.Move X, Y
End If
End Sub
Run the application by keying in F5. when the mouse is clicked on the form
somewhere, the selected image moves to that clicked location. This is shown in the below
figure.
38
End If
End Sub
Button value 1 indicates that the left
mouse button is clicked. The code written in the
Mouse Down event changes the Current X and
Current Y to the coordinates where the mouse
button was just clicked.
Run the application. The mouse is
clicked and moved in the Form a line is drawn
corresponding to the mouse movement.
Following figure illustrates the combined action of Mouse Down and Mouse Move.
The program uses two graphics related Visual Basic concepts, the Line method and
the CurrentX and CurrentY properties. Line method is preferred to draw a line in a Form. The
following statement draws a line from the coordinates
X = 2500, Y = 2000, X = 5000, Y = 5500
Line (2500, 2000) - (5000, 5500)
39
The above procedure simply draws small circles at the mouse's current location using
the Circle method. The parameter x, y represent the centre of the circle, and the second
parameter represent the radius of the circle.
41
Modal and Modeless dialog boxes
Modal dialog box is the dialog box in which user response is required before
continuing with the program. The Paragraph dialog box of WordPad is a good example of it
when it is displaying, the user cannot use any other part of WordPad unless he or she closes
this object first.
Modeless dialog box is the dialog box in which the screen remain stable and available
to all the user for use at any time but it doesn’t stop there and allow other user work to be
carried out without any interference. For example The Find dialog box of WordPad.
Syntax :
memory_variable = InputBox (prompt[,title][,default])
memory_variable 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, separate the lines using the vbCrLf constant
Title - String expression displayed in the title bar of the dialog box. If 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.
42
Following is an expanded MessageBox
Syntax :
MsgBox ( Prompt [,icons+buttons ] [,title ] )
memory_variable = MsgBox ( prompt [, icons+ buttons] [,title] )
Prompt : String expressions displayed as the message in the dialog box. If prompt
consist of more than one line, separate the lines using the vbrCrLf constant.
Icons + Buttons : Numeric expression that is the sum of values specifying the
number and type of buttons and icon to display.
Title : String expression displayed in the title bar of the dialog box. If omit title, the
application name is placed in the title bar.
Icons
Buttons
Constant Value Description
vbOkOnly 0 Display OK button only
Display OK and Cancel
vbOkCancel 1
buttons
Display Abort, Retry and
vbAbortRetryIgnore 2
Ignore buttons
Display Yes, No and Cancel
vbYesNoCancel 3
buttons
vbYesNo 4 Display Yes and No buttons
Display Retry and Cancel
vbRetryCancel 5
buttons
43
Return Values
Constant Value Description
vbOk 1 Ok Button
vbCancel 2 Cancel Button
vbAbort 3 Abort Button
vbRetry 4 Retry Button
vbIgnore 5 Ignore Button
vbYes 6 Yes Button
vbNo 7 No Button
44
Any six of the different dialog boxes can be displayed with just one Common Dialog
control.
A particular dialog box is displayed by using one of the six "Show..." methods of the
Common Dialog control:
ShowOpen, ShowSave, ShowPrinter, ShowColor, ShowFont, or ShowHelp.
The sample program for this topic will be presented shortly, but first, two properties
of the Common Dialog control, Flags and CancelError, will be discussed briefly.
2.4 MDI
The Multiple Document Interface (MDI) was designed to simplify the exchange of
information among documents, all under the same roof.
With the main application, maintain multiple open windows, but not multiple copies
of the application.
Data exchange is easier when user can view and compare many documents
simultaneously
45
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.
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.
Visual Basic automatically associates this new Form with the parent Form. This child
Form can't exist outside the parent Form; in the words, it can only be opened within the
parent Form.
Parent and Child Menus
MDI Form cannot contain objects other than child Forms, but MDI Forms can have
their own menus.
However, because most of the operations of the application have meaning only if
there is at least one child Form open, there's a peculiarity about the MDI Forms.
The MDI Form usually has a menu with two commands to load a new child Form and
to quit the application.
The child Form can have any number of commands in its menu, according to the
application. When the child Form is loaded, the child Form's menu replaces the
original menu on the MDI Form
Following example illustrates the above explanation.
* Open a new Project and name the Form as Menu.frm and save the Project as Menu.vbp
* Design a menu that has the following structure.
<> MDIMenu Menu caption
MDIOpen opens a new child Form
46
MDIExit terminates the application
* Then design the following menu for the child Form
<> ChildMenu Menu caption
Child Open opens a new child Form
Child Save saves the document in the active child Form
Child Close Closes the active child Form
At design time double click on MDI Open and add the following code in the click
event of the open menu.Form1.Show
And so double click on MDI Exit and add the following code in the click event End
Double click on Child Close and enter the following code in the click event Unload
Me
Before run the application in the project properties set MDI Form as the start-up
Form. Save and run the application. Following output will be displayed.
47
Unit – III
48
JDBC vs. ODBC
The Java Database Connectivity (JDBC) API uses the Java programming language to
access a database. When writing programs in the Java language using JDBC APIs, users can
employ software that includes a JDBC-ODBC Bridge to access ODBC-supported databases.
The JDBC-ODBC Bridge (or JDBC type 1 driver) should be viewed as a transitional
approach, as it creates performance overhead because API calls must pass through the JDBC
bridge to the ODBC driver, then to the native database connectivity interface. In addition, it
was removed in Java Development Kit (JDK) 8, and Oracle does not support the JDBC-
ODBC Bridge. The use of JDBC drivers provided by database vendors, rather than the
JDBC-ODBC Bridge, is the recommended approach.
52
Remote Data Objects (RDO)
These objects are only used to access ODBC data sources such as Oracle. These
objects access databases that are on remote machine (database server). This object model has
less number of objects compared with DAO and more suitable for accessing remote
databases.
53
Properties of Data control
Following are important properties of data control.
S.No Properties Explanation
1 Database name Contains the name of the database that is to be
accessed.
2 Record source Contains the name of the table that is to be accessed. It
may also contain SELECT command.
3 Read only If set to true, doesn’t allow the data to be updated.
4 Exclusive If set to true, doesn’t allow any other application to
open the database until user close the database.
5 BOF Action Specifies the action data control takes when BOF
property of the underlying record set is true.
6 EOF Action Specifies the action data control takes when EOF
property of the underlying record set is true.
7 Connect Specifies the type of database accessed.
8 Default Cursor Type Specifies the type of cursor driver used by data control.
Applicable only when ODBC Direct is used.
9 Default Type Specifies whether Jet Engine is to be used or ODBC
Direct is to be used.
10 Record set Type Specifies the type of record set to be used.
54
Properties and Methods of Record Set object
Record Set object contains the set of records retrieved from database.
S.No Properties Explanation
1 EOF EOF Returns true if record pointer reaches end of record set. End of
record set mark is the position that is after the last record of the
record set .
2 BOF Returns true if record pointer reaches beginning of the record set.
The position before the first record is called as beginning of the
record set.
3 Absolute Returns or sets the relative record number of the record set object’s
Position current record.
4 Sets or returns a bookmark that uniquely identifies the current
Book record in a Record Set object.
Mark
5 Edit Mode Returns the editing state of the record set. The valid options are
none, editing in progress and addition is in progress.
6 Filter Contains the condition that is to be used to filter records when
record set is subsequently reopened using Open Record Set method.
7 Last Returns the bookmarks of the most recently edited or added record.
Modified
8 Lock Edit Specifies whether optimistic lock (where records are locked when
user used Edit method) is to be used or pessimistic locking (where
records are locked only when Update method is used). Setting it to
true chooses pessimistic lock and setting it to false choose optimistic
lock.
9 No Match Returns true if one of the most recently used Find methods (Find
first, Find next, Find Last, Find Previous) or Seek method failed.
10 Record Returns the number of records accessed in the record set. If the
Count record set is of Table-type record set then returns the number of
records in the record set. To get accurate count, prior to using this
use Move Last method.
11 Sort Contains the order in which records are to be arranged if record set
is reopened.
55
Methods of Record Set Object
S.No Properties Explanation
1 Add New Adds a new record at the end of the record set.
Cancels any pending updates that were made after Edit or Add
2 Cancel Update
New methods but before Update method.
3 Close Closes record set.
4 Delete Deletes the current record in the record set.
5 Edit Makes the current record ready for editing.
Searches for the given criteria from the beginning of the record
6 Find First
set.
Searches for the given criteria from the current record of the
7 Find Next
record set.
Searches for the given criteria from the end of the record set in
8 Find Last
backward direction.
Searches for the given criteria from the current record of the
9 Find Previous
record set in backward direction.
Moves the record pointer in the record set by the given number
10 Move
of records. The movement is relative to the current record.
11 Move First Moves to first record.
12 Move Next Moves to next record.
13 Move Last Moves to last record.
14 Move Previous Moves to previous record
Open Record Opens a record set with the information given, such as source
15
Set and type of record set.
Updates the record set by re executing the query on which the
16 Requery
record set is based.
Used to search for a value in the current index. Applicable only
17 Seek for record sets of type table-type and an index is defined for the
underlying table.
Makes the changes made to underlying tables permanent
18 Update
56
Displaying data using Data bound controls
Data bound controls are controls that are bound to columns of a table via data control.
Data bound controls are used to display and modify the data of the database. For instance, a
text box could be used to display and change the data of the corresponding column in the
table. Data bound controls have Data Source and Data Field properties that allow
programmer to bind them to database.
Characteristics of ActiveX
Reusability
Interoperability means only compiled components are reusable and NOT source code.
ActiveX Components
ActiveX Applications (ActiveX .EXE)
An ActiveX application is a standalone application, such as MS-Word, MS-Excel etc.
These applications provide objects that can access and manipulate programmatically from
an application written in Visual Basic or any application development tool that supports
ActiveX.
Note: Each component has a collection of properties, methods and events that can be
accessed from outside. These properties, methods and events are collectively called as
interface of the component.
In-Process Server
An in-process server is an ActiveX .DLL. It runs in the address space of the client
application. It cannot be run as a separate process. The communication between client
(application) and server (code component) will be faster as both of them (client & server)
reside in the same address space. And more importantly there is no context switch
(switching from one process to another). An example for in-process server is ActiveX Data
Objects library.
Out-of-Process Server
An ActiveX code component that is implemented as .EXE is an out-of-process server.
It runs in its own address space. When a client invokes a method of the server, control
switches from client process to server process (context switch occurs). An out-of-process
application can also be run as a standalone application.
Difference
An ActiveX DLL's code is executed within the main program's address space. It
behaves as if the class was created within the main program's code. Because the code lies
inside the program's address space, calling methods is very fast.
An ActiveX EXE's code is run in a separate process. The main program calls an
ActiveX EXE's method, the system marshals’ the call to translate the parameters into the
ActiveX EXE's address space, calls the method, translates the results back into the main
program's address space, and returns the result. This is slower than running an ActiveX
DLL's method inside the main program's address space.
58
Because of the difference in speed, an ActiveX DLL is almost always preferable. The
reason ActiveX EXEs are useful is they can run on a different computer than the main
program while an ActiveX DLL must run on the same computer as the main program. The
EXE can sit on a central computer and work directly with that computer's resources.
Instancing
Set the classes' Instancing properties to determine how the object can be created.
Private
Code outside the DLL/EXE cannot create this object type. Other classes in the
DLL/EXE can use this type of class as a helper but the main program cannot use it.
Single Use
The main program can create the object. Every time create a new object, the system
makes a new ActiveX EXE. Among other things, if the EXE contains global variables then
different objects are creating get different copies of the variables. This option is allowed for
ActiveX EXEs only.
Test Projects
After creating ActiveX DLL project, add a test application. Open the File menu, select
Add Project, and add a Standard EXE. That project can act as the main program to test the
DLL. After the DLL code working, compile it into a DLL file. Then create independent
applications to use it.
Binding
Bind the DLL or EXE either at runtime (late binding) or at design time (early
binding). It is also faster than late binding.
Early Binding
To use early binding, load the main program, open the Project menu, and select
References. Find DLL in the list and select it. If the DLL project's name is Billing Objects,
then look for an entry named Billing Objects. If the project in different locations, it appears as
more than one entry. Click on one and look at the location displayed near the bottom of the
dialog. After that click the Browse button and find the DLL and then selected the DLL, click
OK. Now the program can explicitly refer to the classes in the DLL. For example, it could
declare and create a Customer object like this:
Dim customer1 As Customer
Set customer1 = New Customer
Class does not support Automation or does not support expected interface.
To fix this, load the main program, open the Project menu, and select References.
Deselect the DLL and click OK. Then open the References dialog again and reselect the
DLL.
Type mismatch: To fix this, recompile the main program.
Late Binding
To use late binding, declare references to DLL objects to have type Object. Then use
the Create Object statement to instantiate the objects like this:
Dim customer1 As Object
Set customer1 = CreateObject("BillingObjects.Customer")
61
This code creates an instance of the Customers class that is defined by the DLL
project named Billing Objects. After this the program can use the Public properties and
methods of the customer1 object just as if it had declared it using early binding.
63
Creating .EXE file
1. Select File menu and choose Make aexetimeserver.exe option.
2. Visual Basic creates aexetimeserver.exe in the specified directory and also registers it
in system registry.
Running ActiveX Server as Standalone application
Let us run aexetimerserver.exe as a standalone application. In this case it should
display frmTime, which contains running digital clock.
65
8. Again select New->Method from popup menu and enter SetTime as the name of the
method and “Changes the time to the given time. Time must be given in HH: MM: SS
format” as description.
9. Then click on + sign on the right of Arguments list box and enter the following
details.
Name NewTime
Type String
ByVal Checked
Note: if optional checkbox is checked then the argument is optional. If no value is passed to
the argument then the given default value will be stored in that.
1. Create one more method with the name GetTime and specify the Return Data Type as
String.
2. Select New->Event from popup menu of Time class
3. Enter Invalid Time as the name of the event and “Fired when an given hour, min or
second is invalid” as the description
Note: add property, method and event using icons in toolbar also.
Note: Select tab “All” it displays all the attributes of the class.
Otherwise select one of the three tabs (Properties, Methods, and Events) to display the
specific members. To update project with changes made in class builder:
1. Select File-> Update Project option. Class builder updates the class module with
the details furnished so far.
2. Exit Class builder with File-> Exit.
If the Time class module is open, the code contains three properties, two methods and
one event.
67
Unit IV
OLE Server
This is an application that can provide objects to other applications. This is also
called as OLE Source application.
OLE Client
This is an application that uses objects provided by OLE Server. This is also called as
OLE Container as it contains objects provided by OLE Server. Not every application is an
OLE Server. Only a few applications are capable of providing objects. In the same way not
all applications are capable of receiving objects. However, there are applications, such as
MS-Word and MS-Excel that are capable of being OLE source as well as OLE Container.
68
1. A collection of cells from a spreadsheet of MS-Excel is copied to clipboard. As MS-
Excel is an OLE Server, it copies the data in the form of an object.
2. Paste the data (now in the form of an object) from Clipboard to a document in Ms-
Word.
3. Now the data is embedded into MS-World document as an object. Ms-Word
document contains its own copy of the data.
4. If double click on the object in MS-Word, then an instance of MS-Excel is invoked
and data from MS-Word is copied into MS-Excel.
5. User can edit embedded data using MS-Excel.
6. If user saves changes and exits MS-Excel then modified data is placed in MS-Word
document.
In the above example, once an object is embedded into MS-Word, do not have to
invoke source application manually, instead just double click on the object and that will
invoke source application automatically. However, if data is changed in the original
worksheet of MS-Excel then those changes are not copied to the data in MS-Word. This is
because in Object Embedding, source and container applications maintain two different
copies of the data.
69
Fig. Topology of OLE DB applications.
The primary focus of the ODBC is to provide a consistent interface to database
data sources. OLE DB is designed with an even broader goal in mind; to provide a
methodology to access data regardless of the data source. OLE DB becomes the data
access bridge for documents, e-mail systems, file systems, spreadsheets, and database
sources using ODBC drivers.
70
4.3. OLE CONTAINER CONTROL
In Visual Basic, embed or link an object using OLE container control. OLE control is
one of the standard set of controls. This allows the user to either embed or link an object
either at design time or at run time thorough its properties and methods. OLE Container
control can be bound to database using a data control.
71
The followings are the other options available in Insert Object Dialog box.
S.No Option Explanation
1 Create From File Allows an object to be embedded or linked from a file.
2 Create New Allows creating a new file and then embedding an object
from newly created file.
3 Display As Icon Displays an icon instead of the content of the object.
4 Browse Displays a dialog box from which user can select a file.
5 Link If turn on this checkbox, then object is linked, otherwise
it is embedded..
73
Sample Application
Scode Text(5) Subject code.
Sdes Text(20) Subject description.
Duration Integer Number of hours.
Syllabus Binary Contains the syllabus of the subject in Word document.
The user interface of the data entry screen
The following table will summarize the role played by each control on the form.
Control Meaning
txtScode Bound to Scode column of SUBJECT table.
txtSdes Bound to Sdec column of SUBJECTS table.
txtDur Bound to Duration column of SUBJECTS table.
Data1 Data control that is bound to SUBJECTS table of COURSE.MDB.
OLE Bound to Syllabus column of SUBJECTS table.
Add New Subject command button adds a new blank record to SUBJECTS table by
using AddNew method of Recordset.
Quit Is used to terminate the program.
75
4.5. OLE DRAG AND DROP
OLE Drag and Drop allows to drag data from one control and drop it on another
control. The most interesting of all is its ability to support drag and drop across
applications. That means it is possible to drag some text form a document in MS-Word and
drop it in a textbox in Visual Basic.
76
Properties related to OLE Drag and Drop.
The settings for these two properties will be, None, Manual, and Automatic. The
actual options depend upon the extent of OLE Drag and Drop support the control has.
OLEDrag Method
Starts OLE dragging. This is used to manually start OLE dragging. Dragging text
from MS-Word into a text box using OLE Drag and Drop
Let us now understand the process involved in dragging text entered in MS-Word into
a textbox that is placed on a form in Visual Basic.
1. Start a new project using File-> New Project -> Standard EXE.
2. Place a Textbox on the form.
3. Change OLEDrop Mode property of the textbox (Text1) to 1-Automatic.
4. Run Visual Basic project using F5.
5. Start MS-Word.
6. Type some text in word document
7. Arrange Visual Basic project and MS-Word
8. Select the text in word document and drag the text while holding down ctrl key
into text box of the form.
77
Sample Application for Manual OLE Drag and Drop
The sample application that we are going to develop has a simple form with two
textboxes. First textbox is used as the source and second textbox is used as the target. The
main purpose of the application is to understand the steps involved handling OLE Drag and
Drop manually.
First textbox's OLEDragMode is set to Manual and OLEDropMode property is set to
Automatic.
Second textbox's OLEDragMode is set to Automatic and OLEDropMode is set to
Manual.
Writing code
Private Sub txtsource_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As
Single)
txtsource.OLEDrag
End Sub
78
Private Sub txtsource_OLECompleteDrag(Effect As Long) If
(Effect and vbDropEffectMove)<>0 Then
txtsource.Text = ""
End If
End Sub
Private Sub txtsource_OLEStartDrag(Data As DataObject, AllowedEffects As Long)
AllowedEffects = vbDropEffectMove Or vbDropEffectCopy
Data.SetData UCase(txtsource.Text)
End Sub
Private Sub txtTarget_OLEDragDrop(Data As DataObject, Effect As Long, Button As
Integer, Shift As Integer, X As Single, Y As Single)
txtTarget.Text = Data.GetData(vbCFText)
Effect = vbDropEffectMove
End Sub
79
The file-system controls used together
File-system controls obtain all their information from the operating system
automatically; User can access this information or determine what is displayed by each
control through its properties. For example, the content of the current working directory is
displayed by default (that is, the directory from which the application was launched, or what
became the current directory as the result of a ChDir statement).
Application can also display a list of the files with names matching a pattern, such as
*.frm. Simply draw a file list box on the form and set its Pattern property to *.frm. Here
specify the Pattern property at run time with the following code:
File1.Pattern = "*.FRM"
The file-system controls give the flexibility that is not available with the common
dialog control.
80
property to change drives at the operating system level by specifying it as an argument to the
ChDrive method:
ChDrive Drive1.Drive
81
Dir1.Path = Drive1.Drive
This assignment is executed; the directory list box displays all the available
directories and subdirectories on that drive. By default, the directory list box also displays all
directories above, and any subdirectories immediately below, the current directory of a drive
assigned to the Dir1.Path property. The directory list box doesn't set the current directory at
the operating system level; it merely highlights the directory and gives it the ListIndex value
of – 1.
To set the current working directory, use the ChDir statement. For example, the
following statement changes the current directory to the one displayed in the directory list
box: ChDir Dir1.Path
In an application that uses file controls, set the current directory to the directory where
the application's executable (.exe) file is located with the Application object:
ChDrive App.Path ' Set the drive.
ChDir App.Path ' Set the directory.
The Path property is available only at run time, not at design time.
83
The user selects a drive in the Drive1 list box.
A Drive1_Change event is generated, and the display in Drive1 is updated to
reflect the new drive.
Code in the Drive1_Change event procedure assigns the new selection (the
Drive1.Drive property) to the Path property of the Dir1 list box with the following
statements:
Private Sub Drive1_Change ()
Dir1.Path = Drive1.Drive
End Sub
The assignment to the Path property generates a Dir1_Change event and updates
the display in Dir1 to reflect the current directory of the new drive.
Code in the Dir1_Change event procedure assigns the new path (the Dir1.Path
property) to the File1.Path property of the File1 list box:
Private Sub Dir1_Change ()
File1.Path = Dir1.Path
End Sub
The assignment to the File1.Path property causes the display in the File1 list box to
reflect the Dir1 path specification.
To change the event procedures and the properties depend on the application uses the
combination of file-system controls.
84
The following table summarizes the controls in Seek.frm from the WinSeek application.
Control Property Setting
Drive list box Name drvList
Directory list box Name dirList
File list box Name Pattern filList *.*
First command button NameCaption cmdSearch
Default &Search True
Secondcommand button Name Caption cmdExit E&xit
List box Name lstFoundFiles
When users want to change directories without using a mouse, they typically use the
arrow keys to select the desired directory and then press the ENTER key. Because ENTER is
commonly associated with the default command button control, WinSeek must recognize
when the user simply wants to change directories rather than conduct a search for files.
The WinSeek application resolves this ambiguity by determining if the path of the
dirList box differs from the currently highlighted directory. This situation can occur when the
user single-clicks an item in the directory list box or navigates the directory list box using the
arrow keys. The following code determines whether the dirList.Path is different from the path
of the highlighted directory. If the paths are different, the dirList.Path is updated. If the paths
are the same, the search is performed.
Private Sub cmdSearch_Click()
' If the dirList.Path is different from the currently
' selected directory, update it; otherwise perform the
search.
If dirList.Path <> dirList.List(dirList.ListIndex) Then
dirList.Path = dirList.List(dirList.ListIndex)
Exit Sub
End If
' Continue with search.
End Sub
85
The WinSeek application uses the following procedures to handle significant events:
The DrvList_Change procedure
The DirList_Change procedure
The CmdSearch_Click procedure
86
The Command Button's Click Event
This event procedure determines whether the highlighted item in the dirList list box is
the same as the dirList.Path. If the items are different, then dirList.Path is updated. If the
items are the same, then the search is performed.
Private Sub cmdSearch_Click ()
' If the dirList.Path is different from the
' currently selected directory, update it;
' otherwise perform the search.
If dirList.Path <> dirList.List _
(dirList.ListIndex) Then
dirList.Path = dirList.List(dirList.ListIndex)
Exit Sub
End If
' Continue with search.
End Sub
DragDrop Event
Occurs when a drag-and-drop operation is completed as a result of dragging a control
over an object and releasing the mouse button or using the Drag method with its action
argument set to 2 (Drop).
Syntax
Private Sub Form_DragDrop(source As Control, x As Single, y As Single)
Private Sub object_DragDrop([index As Integer,]source As Control, x As Single, y As Single)
87
Remarks
Use a DragDrop event procedure to control what happens after a drag operation is
completed. For example, it moves the source control to a new location or copy a file from one
location to another.
When multiple controls can potentially be used in a source argument:
Use the Type Of keyword with the If statement to determine the type of control used
with source.
Use the control's Tag property to identify a control, and then use a Drag Drop event
procedure.
Note Use the Drag Mode property and Drag method to specify the way dragging is initiated.
Once dragging has been initiated, it handles events that precede a Drag Drop event with a
Drag over event procedure
88
The mode in which file is to be opened. The mode specifies which operations are
allowed on the file.
File number. Each open file contains a file number. This file number is used to access
the file once the file is opened. The file number must be unique.
Open pathname For mode [Access access] [lock] As [#] filenumber [Len=reclength]
The first step in working with files in Visual Basic is to open the file. This is achieved
using the Visual Basic FileStream class. The FileStreamconstructor accepts the file name to
be opened as the first parameter, followed by a number of other parameters defining the mode
in which the file is to be opened.
These fall into the categories of FileMode, FileAccess and FileShare. The options
available as listed in the following tables:
FileMode Options
<google>ADSDAQBOX_FLOW</google>
Mode Description
If the file exists it is opened. Any writes are appended to the end of the file.
Append
Requires FileAccess.Write mode
Create Creates a new file, removing old file if it already exists
CreateNew Creates a new file and returns error if file already exists
Open Opens an existing file. Returns error if file does not exist
OpenOrCreate If file already exists it is opened, otherwise a new file is created
Truncate Opens an existing file and deletes all existing content
FileAccess Options
Mode Description
Read Opens the file for reading only.
ReadWrite Opens the file for both reading and writing
Write Opens the file to writing only
89
FileShare Options
Mode Description
The file cannot be opened by any other program until it is closed by the
None
current program
Other programs may simultaneously open and read from the file, but not
Read
write to it.
Other programs may simultaneously open and read and write from/to the
ReadWrite
file.
Other programs may simultaneously open and write to the file, but not read
Write
from it.
90
Reading from a File using VB
Now that we have created and written to a file the next step is to read some data from
the file. This is achieved using the Visual Basic StreamReader object.
The StreamReader ReadLine() method can be used to read the next line from the file stream
including the new line. The Read() method reads a line from the file but removes the new
line. The ReadToEnd() method can be used to read from the current line in the file to the end
of the file. The following example reads the data back from the file after it has been written
and display the contents in a MessageBox:
Dim textFileStream As New IO.FileStream("C:\Temp\test.txt",
IO.FileMode.OpenOrCreate,IO.FileAccess.ReadWrite, IO.FileShare.None)
Dim myFileWriter As New IO.StreamWriter(textFileStream)
Dim myFileReader As New IO.StreamReader(textFileStream)
Dim intCounter As Integer
Dim strFileContents As String
For intCounter = 0 To 10
myFileWriter.WriteLine("This is line " & CStr(intCounter))
Next intCounter
strFileContents = myFileReader.ReadToEnd
MessageBox.Show(strFileContents)
myFileWriter.Close()
myFileReader.Close()
textFileStream.Close()
Detecting a Change to a File
A Visual Basic can monitor a file and receive notification from the OS when the file
is changed by any program. This is achieved using the FileSystemWatcher class. Start Visual
Studio and create a new Windows Application project. Access the Toolbox and double click
on the FileSystemWatchercontrol from the Components section of the list. The new object
will appear beneath the Form design area with the name FileSystemWatcher1. Select the
object and use the Properties panel to change the Path to C:\Temp and the Filter property
to test.txt. Double click on the FileSystemWatcher1 object to access the event procedure code
and modify the changed event as follows:
Private Sub FileSystemWatcher1_Changed(ByVal sender As System.Object,
ByVal e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Changed
MessageBox.Show("File changed")
End Sub
91
Unit V
Miscellaneous Controls
The timer control can be used to create an event in their application at a
recurring interval. This is useful for executing code without the need for user
interaction.
The OLE container control is an easy way to add capabilities like linking and
embedding to the application. Through the OLE container control, It can
provide access to the functionality of any OLE-enabled application such as
Microsoft Excel, Word and many others.
The common dialog control adds built-in dialog boxes to the application for the
selection of files, colors, fonts, and printing functions.
93
SSTab control using the Style, ShowFocusRect, TabOrientation, and WordWrap
properties.
94
Datatype
Required if Option Strict is On. Data type of the value parameter. The data type specified
must be the same as the data type of the property where this Set statement is declared.
Statements
Optional. One or more statements that run when the Set property procedure is called.
End Set Required. Terminates the definition of the Set property procedure.
Remarks
Every property must have a Set property procedure unless the property is marked ReadOnly.
The Set procedure is used to set the value of the property.
Visual Basic automatically calls a property's Set procedure when an assignment statement
provides a value to be stored in the property.
The Set procedure defaults to the access level of its containing property unless user
use access modifier in the Set statement.
Behavior
Returning from a Property Procedure. The Set procedure returns to the calling code,
execution continues following the statement that provided the value to be stored. Set property
procedures can return using either the Return Statement or the Exit Statement. The Exit
Property and Return statements cause an immediate exit from a property procedure. Any
number of Exit Property and Return statements can appear anywhere in the procedure, and
mix Exit Property and Return statements.
Example
The following example uses the Set statement to set the value of a property.
Class propClass
Private propVal As Integer
Property prop1() As Integer
Get
Return propVal
End Get
Set(ByVal value As Integer)
propVal = value
End Set
End Property
End Class
95
5.4. LIST BOXES AND COMBO BOXES
List boxes and combo boxes present a list of choices to the user. By default, the
choices are displayed vertically in a single column, although user can also set up multiple
columns. If the number of items exceeds it can be displayed in the combo box or list box,
scroll bars automatically appear on the control. The user can then scroll up and down or left
to right through the list.
Single-column list box
A combo box control combines the features of a text box and a list box. This control
allows the user to select either by typing text into the combo box or by selecting an item
from its list.
Combo box
In contrast to some other controls that contain a single value; for example the label's
Caption property or the text box's Text property, list boxes and combo boxes contain
multiple values or a collection of values. They have built-in methods for adding, removing
and retrieving values from their collections at run time. To add several items to a list box
named List1, write the following code .
List1.AddItem "Paris"
List1.AddItem "New York"
List1.AddItem "San Francisco"
List boxes and combo boxes are an effective way to present a large number of choices to
the user in a limited amount of space.
96
5.5. THE TabStrip CONTROL
A TabStrip control is like the dividers in a notebook or the labels on a group of file
folders. By using a TabStrip control, user can define multiple pages for the same area of a
window or dialog box in application.
The control consists of one or more Tab objects in a Tabs collection. At both design
time and run time, user can affect the Tab object's appearance by setting properties. User can
also add and remove tabs using the Properties Page of the TabStrip control at design time, or
add and remove Tab objects at run time using methods.
The Style property determines whether the TabStrip control looks like push buttons
(Buttons) or notebook tabs (Tabs). At design time put a TabStrip control on a form, it has one
notebook tab. If the Style property is set to tabTabs, then there will be a border around the
TabStrip control's internal area. The Style property is set to tabButtons, no border is
displayed around the internal area of the control, however, that area still exists.
To set the overall size of the TabStrip control, use its drag handles and/or set the Top,
Left, Height, and Width properties. Based on the control's overall size at run time, Visual
Basic automatically determines the size and position of the internal area and returns the
Client-coordinate properties – ClientLeft, ClientTop, ClientHeight, and ClientWidth. The
MultiRow property determines whether the control can have more than one row of tabs, the
TabWidthStyle property determines the appearance of each row, and, if TabWidthStyle is set
to tabFixed, use the TabFixedHeight and TabFixedWidth properties to set the same height
and width for all tabs in the TabStrip control.
98
Basic Properties
The address of a cell is given by its Row and Col properties, whose values start at
0. Row 0 is the fixed title row, and column 0 is the fixed title column.
Grid.Row= 1
Grid.Col = 1
After specify the cell’s address, examine its contents with a statement like:
Cell Value = Grid.Text .
or set its contents with a statement like:
Grid.Text = “January”
This method of reading or setting cell values requires too many statements for such a
simple task, and it’s probably available to be compatible with the old Grid control. The
simplest way to address a cell on the grid is by means of the TextMatrix property, which has
the following syntax :
Grid.TextMatrix(row, col)
The row and col arguments are the cell’s coordinates in the grid. To extract the value of the
first editable cell, use’ a statement like:
Cell Value = Grid.TextMatrix(1, 1)
The names of the months and the corresponding profit figures of the grid shown in
Figure are assigned with the following loop, which is executed from within the Display Data
button’s event handler:
Using the Format String Property
Dim I row As Integer
For I row=1 to 12
Grid.TextMatrix(irow, 1)=MonthNames(irow)
Grid.TextMatrix(irow, 2)=Formats(profit97 (irow),”#, ###”)
Grid.TextMatrix(irow, 3)=Formats(profit96(irow),”#, ###”)
Grid.TextMatrix(irow, 4)=Formats(Grid.TextMatrix(irow, 3)- Grid.TextMatrix(irow, 2))
Grid.TextMatrix(irow, 5=Formats(100* (Grid.TextMatrix(irow, 3) -Grid.TextMatrix(irow,
2))/ Grid.TextMatrix(irow, 2)- ),”#, ###”)&”%”
Next
The array MonthNames holds the names of the months and the arrays Profit 96 and Profit
97 contain the numeric values. Notice that the contents of the last two columns (Gain and
Gain [%]) are calculated.
99
A third way to access the cells of the grid is by means of the TextArray
property, which is similar to the Text Matrix property, but it uses a single index to address
a cell. It has the following syntax: “
Grid.TextArray(cellindex)
To calculate the cellindex argument, which determines the location of the desired cell,
multiply the desired row by the Cols property and add the desired. The following statement
calculates the value of the cellindex arguments row (row) and column (001) number:
cellindex = row * cols + col
The Text Array property is less convenient than the Text Matrix property because to
convert the actual address of the desired cell to a single number, Use the Tex tArray property
to assign values to the grid’s cells if the values are already stored in a one-dimensional array.
“
Starting CRW
1. Click on Start button
100
2. Select Programs-> Microsoft Visual Studio 6.0 -> Crystal Reports. In which group
crystal reports are placed depends upon the group selection at the time of
installation.
3. If user prompted to enter registration details, cancel it or register and then click on
Ok.
4. The initial screen of Crystal Reports will be displayed.
Hiding/showing a Section
Each section can be hidden or displayed by selecting context menu (popup menu
invoked using right button) and then selecting Hide Section option, when section is
displayed or Show Section option, when section is hidden.
103
OLE DB Provider. Click Next to get to the Connection tab. Click the ellipsis
button. Find phone database (mdb) file. Click OK to close the dialog box.
4. Right-click the Connection1 tab and click Rename. Change the name of the tab to
Phone. Right-click this newly named tab and click Add Command to create a
Command1 tab. Right-click this tab and choose Properties. Assign the following
properties:
Command Name - PhoneList
Connection - Phone
DataBase Object - Table
ObjectName - PhoneList
5. Click OK. All this was needed just to connect the environment to our database.
6. Display the properties window and give the data environment a name property of
denPhone. Click File and Save denPhone As. Save the environment in an appropriate
folder. Add this file to our phone database management system. At this point, my data
environment window looks like this (I expanded the PhoneList tab by clicking the +
sign):
In this form, resized the labels a bit and added a Report Header. Any space left
in this section will be inserted after each entry.
6. Click File and Save rptPhone As. Save the environment in an appropriate folder.
Now reopen our phone database manager and attach this and the data environment to
that project and add capabilities to display the report.
105
Accessing the Data Report
1. Reopen the phone directory project. Add a command button named cmd Report and
give it a Caption of Show Report. (There may be two tabs in the toolbox, one named
General and one named Data Report.)
2. Now add the data environment and data report files to the project. Click the Project
menu item, and then click Add File. Choose denPhone and click OK. Also add
rptPhone. In Project Window files should be listed under Designers.
3. Use this code in cmdReport_Click:
Private Sub cmdReport_Click()
rptPhone.Show
End Sub
4. This uses the Show method to display the data report.
5. Save the application and run it. Click the Show Report button and this should appear:
106