0% found this document useful (0 votes)
3 views

unit 3 vb

This document provides an overview of file handling in Visual Basic, detailing the steps for opening, processing, and closing files, along with different file access types. It also covers functions related to file operations, input/output statements, and graphics methods for drawing on forms and PictureBox controls. Additionally, it discusses graphic properties and methods for drawing points and lines, including examples of code usage.

Uploaded by

Nivya babu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

unit 3 vb

This document provides an overview of file handling in Visual Basic, detailing the steps for opening, processing, and closing files, along with different file access types. It also covers functions related to file operations, input/output statements, and graphics methods for drawing on forms and PictureBox controls. Additionally, it discusses graphic properties and methods for drawing points and lines, including examples of code usage.

Uploaded by

Nivya babu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

FILE HANDLING

A file is a collection of bytes stored on the disk with a given


name (called as filename). Every development tool provides
access to these files on the disk. In this chapter we will understand
how to access and manipulate files using Visual Basic.

There are three special controls, called as File controls,


which deal with files and directories. We will also understand
how to use these controls in this chapter.

File handling
The following are three important steps in handling a file.

• Opening the file

• Processing the file, i.e. either reading the content of the file or
writing the required data into file or both.

• Closing the file

File access types


Depending upon the requirement you can use any of the
three different file access types:

Sequential For reading and writing text files in continuous


blocks. Random For reading and writing text or binary files
structured as fixed- length records.

Binary For reading and writing arbitrarily structured files.

Opening or Creating the file using Open statement


A file is opened using OPEN statement in Visual Basic.
At the time of opening a file, you have to specify the following.

• Name of the file to be opened


• 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]

Option Meaning
Pathname Name of the file to be opened.

Mode Specifies the mode in which file is to be opened.

Valid modes: Append, Input, Output, Binary and Random. If


unspecified then Random is
taken. Access Specifies the operations that
are permitted on the open file.

Valid values: Read, Write, or


ReadWrite. Lock Specifies the operations restricted
on the file opened by other users.

Value , values: Shared, Lock Read, Lock Write, and Lock Read
Write. Filenumber A number in the range 1 to 511. This number
must be unique among open files. Use FreeFile function to
obtain the next available number. RecLength Specifies the size
of each record in random files. It should be <= 32767.

For sequential files, this is the number of characters


buffered. This is ignored, if mode is Binary. If the file is not
existing then a new file with the given name is created in
Append, Binary, Output and Random modes.

Examples:
 To open TEST.TXT file in input mode:
Open “TEST.TXT” for input as #1
 To open NUMBER.DAT file in Binary mode:
Open “NUMBER.DAT” for binary access write as #1
 To open STUDENTS.DAT in random mode with a record length
of 10:
Open “STUDENTS.DAT” for random as #1 len = 10
 To get next available file number and then use it: 'FreeFile
function returns the number that can be used as the file
'number while opening the file Fn = FreeFile Open
“TEST.TXT” for input as #fn Functions related to files The
following are the functions that are used with files. Function
Meaning Dir Returns the name of the file that matches the
given name. If file is not existing, then it returns "" (null
string).
 FileLen Returns the length of the file in bytes. LOF Returns
the length of an open file in bytes. EOF Returns true, if the
specified file has reached end-of-file marker. FreeFile Returns
the next available file number. Seek Sets or returns the
position at which file pointer is currently positioned. For
random files it returns the number of records read or written
so far.
 Filecopy Copies the given source file to target file.
 GetAttr Returns the attributes of the given path.
 SetAttr Changes the attributes of the specified file to the given
attributes. FileDateTime Returns the date and time when file was
last modified or created.
 Loc Returns the current position of file pointer of an open file.
Functions related to file
handling. Example:
To find out the length of file CHARS.TXT:

fl = FileLen("c:\vb60\chars.txt") To find out whether file with


the file number 1 has reached end-of-file:

if EOF(1) then … end if To check whether STUDENTS.DAT


file is existing or not:

If dir(“students.dat”) = “”
then MsgBox “File
students.dat is missing” Else
Process
the file
End if

Statement related to file Input and output


The following statements are used to perform input or
output to file and other operations such as opening and closing.
Statement Meaning Close Closes an open file Get Read a record
from the given position of the specified file.

READING FILE
Input( ) Returns the specified number of characters from
the given file. Input # Reads data into specified list of variables
from the given file. Line Input # Reads a complete line from the
given file.
Open Opens the given file in the specified mode.
Print # Prints the specified data to the given file.
Put Writes a record to the given position of the specified file.
Write # Writes the specified data to the given file.

Statements related to file handling. Not all statements are available


in all modes. So, the following table shows the availability of
each statement in each of the three access types.
Statement Sequential Random Binary Close X X X Get X X
Input( ) X X
Input # X Line Input # X Open X X X Print # X Put X X Write #
X.
BOF, EOF Properties

 BOF Indicates that the current record position is before the


first record in a Recordset object.
 EOF Indicates that the current record position is after the
last record in a Recordset object.

Return Value

The BOF and EOF properties return Boolean values.

Remarks
Use the BOF and EOF properties to
determine whether a Recordset object contains records or
whether you have gone beyond the limits of a Recordset object
when you move from record to record.

The BOF property returns True (-1) if the current record position
is before the first record and False(0) if the current record
position is on or after the first record.

The EOF property returns True if the current record position is


after the last record and False if the current record position is on
or before the last record.

If either the BOF or EOF property is True, there is no current record.

If you open a Recordset object containing


no records, the BOF and EOF properties are set to True(see
the RecordCount property for more information about this
state of a Recordset). When you open a Recordset object
that contains at least one record, the first record is the current
record and the BOF and EOF properties are False.

If you delete the last remaining record in the


Recordset object, the BOF and EOF properties may remain
False until you attempt to reposition the current record.

This table shows which Move methods are allowed with


different combinations of the BOF and EOFproperties.
MoveFirst, MovePrevio MoveNext,
us,
MoveLast Move Move > 0
Move < 0 0
BOF=True, Allowe Error Error Allowe
EOF=False d d
BOF=False, Allowe Allowed Error Error
EOF=True d
Both True Error Error Error Error

Both False Allowe Allowed Allowe Allowe


d d d
Allowing a Move method does not guarantee that the method will
successfully locate a record; it only means that calling
the specified Move method will not generate an error.

The following table shows what happens to the BOF and EOF
property settings when you call various Move methods but are unable
to successfully locate a record.
BOF EOF

MoveFirst, MoveLast Set to True Set to


True
Move 0 No change No
change
MovePrevious, Move < 0Set to True No
change
MoveNext, Move > 0 No change Set to
True
GRAPHICS METHODS
The graphic methods allow you to draw on the form and the
PictureBox control. In Visual Basic 6, graphic methods are only supported
by the form object and the PictureBox control.

 Graphics methods apply to forms and picture boxes (remember a


picture box is like a form within a form). With these methods, we can draw
lines, boxes, and circles. Before discussing the commands that actually
perform the graphics drawing, though, we need to look at two other topics:
screen management and screen coordinates.

 In single program environments (DOS, for example), when something


is drawn on the screen, it stays there. Windows is a multi-tasking
environment. If you switch from a Visual Basic application to some other
application, your Visual Basic form may become partially obscured. When
you return to your Visual Basic application, you would like the form to
appear like it did before being covered. All controls are automatically
restored to the screen. Graphics methods drawings may or may not be
restored - we need them to be, though. To accomplish this, we must use
proper screen management.

 The simplest way to maintain graphics is to set the form or picture


box's AutoRedraw property to True. In this case, Visual Basic always
maintains a copy of graphics output in memory (creates persistent
graphics). Another way to maintain drawn graphics is (with AutoRedraw set
to False) to put all graphics commands in the form or picture box's Paint
event. This event is called whenever an obscured object becomes
unobscured. There are advantages and disadvantages to both approaches
(beyond the scope of discussion here). For now, we will assume our forms
won't get obscured and, hence, beg off the question of persistent graphics
and using the AutoRedraw property and/or Paint event.

All graphics methods described here will use the default coordinate
system

Note the x (horizontal) coordinate runs from left to right, starting at 0


and extending to ScaleWidth - 1. The y (vertical) coordinate goes from top to
bottom, starting at 0 and ending at ScaleHeight - 1. Points in this coordinate
system will always be referred to by a Cartesian pair, (x, y). Later, we will
see how we can use any coordinate system we want.

ScaleWidth and ScaleHeight are object properties representing the


“graphics” dimensions of an object. Due to border space, they are not the
same as the Width and Height properties. For all measurements in twips
(default coordinates), ScaleWidth is less than Width and ScaleHeight is less
than Height. That is, we can’t draw to all points on the form.
 Print: Print is the simplest graphic method in Visual Basic 6. This
method has been used throughout the earlier versions of the
language. It prints some text on the form or on the PictureBox control.
It displays texts.
 Cls: The Cls method is another simple graphic method that is used to
clear the surface of the form or the PictureBox control. If some texts
are present, you can use the Cls method to remove the texts. It clears
any drawing created by the graphic methods.
 Point: The Point method returns the color value from an image for a
pixel at a particular point. This method is generally used to retrieve
color values from bitmaps.
 Refresh: The refresh method redraws a control or object. In other
words, it refreshes the control. Generally, controls are refreshed
automatically most of the times. But in some cases, you need to
refresh a control’s appearance manually by explicitly invoking the
Refresh method.
 PSet: The PSet method sets the color of a single pixel on the form.
This method is used to draw points.
 Line: The Line method draws a line. Using the Line method, you can
also draw other geometric shapes such as rectangle, triangle etc.
 Circle: The Circle method draws a circle. Using the Circle method, you
can also draw other geometric shapes such ellipses, arcs etc.
 PaintPicture: The PaintPicture method displays an image on the form
at run-time.
 TextHeight: The TextHeight method returns the height of a string on
the form at run-time.
 TextWidth: The TextWidth method returns the width of a string on
the form at run-time.

GRAPHIC PROPERTIES
The graphic properties are useful while working with the graphic
methods. Some of the form's properties and some of the PictureBox's
properties are the graphics properties.
The common graphic properties are discussed in this section. You’ll learn
more about them using code examples later in this tutorial.

Consider the following graphic properties.

 DrawMode: The DrawMode property sets the mode of drawing for the
appearance of output from the graphic methods. In the DrawMode
property, you can choose from a variety of values.
 DrawStyle: The DrawStyle property sets the line style of any drawing
from any graphic methods. It allows you to draw shapes of different
line styles such as solid, dotted, dashed shapes etc.
 DrawWidth: The DrawWidth property sets the line width of any
drawing from any graphic methods. While drawing shapes, you can
control the thickness of the lines using this property.
 FillColor: The FillColor property is used to fill any shapes with a
color. You may use the symbolic color constants to fill your shapes.
You may also use the color codes as well as the RGB function.
 FillStyle: The FillStyle property lets you fill shapes in a particular
filling style.
 ForeColor: The ForeColor property is used to set or return the
foreground color.
 AutoRedraw: Set the AutoRedraw property to True to get a persistent
graphics when you’re calling the graphic methods from any event, but
not from the Paint event.
 ClipControls: Set the ClipControls property to True to make the
graphic methods repaint an object.
 Picture: The Picture property is used to set a picture. Pictures can be
set both at design time and run-time.

Drawing points
This section shows you how to draw points using the PSet method and
how to use the Step keyword with the PSet method.

Drawing points using the PSet method


The Pset method allows you to draw a point. You need to specify the
coordinate i.e. the drawing position. You can also pass a color constant that
is an optional argument in the PSet method.
Private Sub cmdShow_Click()
DrawWidth = 10
PSet (100, 500)
End Sub
Relative positioning with the Step keyword
The Step keyword allows you to draw in a position relative to the
current position. See the example.
Example:
Code:

Private Sub
cmdShow_Click()
DrawWidth = 10
CurrentX = 500
CurrentY = 500
PSet Step(0,
0) End Sub

The above code draws a point in the (0, 0) position relative to the current
position that is (500, 500).

That means, the point is drawn in the (500, 500) position. But this is (0, 0)
position relative to the current position.

Output of code example:

Drawing lines
The Line method lets you draw lines in Visual Basic 6. You need to
specify the starting point and the finishing point of the line in the argument.
You may also specify the color of the line. This is optional, though.
A simple line
The following code example shows how to draw a simple line using
the Line method in Visual Basic 6.

Example:
Code:
Private Sub cmdShow_Click()
DrawWidth = 5
'A hyphen is required between the points
Line (0, 0)-(2000, 2000), vbBlue
End Sub
Output of code example:

\
A line with drawing styles
Form’s DrawStyle property lets you draw lines using a particular style.
The constant values of the DrawStyle property are 0 (vbSolid), 1 (vbDash), 2
(vbDot), 3 (vbDashDot, 4 (vbDashDotDot), 5 (vbTransparent) and 6
(vbInsideSolid). The default value is 0, vbSolid. You may use the numeric
constant or the symbolic constant such as vbSolid, vbDash etc to change
drawing styles in your code.

NOTE: The DrawStyle property does not work if the value of DrawWidth is
other than 1.

Example:
Code:
DrawWidth = 1
DrawStyle = 1
'A hyphen is required between the points
Line (0, 0)-(2000, 2000), vbBlue
DrawStyle = vbDashDot
Line (100, 900)-(2800, 2800), vbRed

Output:

Drawing circles
You can draw a circle using the Circle method in Visual Basic 6. You
may also use the Circle method to draw different geometric shapes such as
ellipses, arcs etc. You need to specify the circle’s center and radius values to
draw a circle using the Circle method.
A simple circle
The following code draws a simple circle using the Circle method in
Visual Basic 6.

Example:
Code:

Private Sub
cmdShow_Click()
DrawWidth = 3
Circle (1800, 1800), 1000,
vbRed End Sub
In the above code, (1800, 1800) is the circle’s center, and the radius value is
1000. The color constant ‘vbRed’ is an optional argument.
Output of code example 10:

A circle filled with color


The following code example shows how to fill a circle with color in
Visual Basic 6.
Example 11:
Code:
Private Sub
cmdShow_Click() FillStyle
= vbSolid FillColor =
&H80C0FF DrawWidth =
3
Circle (1800, 1800), 1000,
vbRed End Sub

Output:

Rectangle
The Line method can be used to draw different geometric shapes such
as rectangle, triangle etc. The following example shows you how to draw a
rectangle using the Line method in Visual Basic 6.
Example:
Code:

Private Sub
cmdShow_Click()
DrawWidth = 3
Line (300, 300)-Step(4000, 2000), vbBlue, B
End Sub
The B argument in the Line method lets you draw a rectangle.

Output:

Displaying an image
The LoadPicture function sets a picture to the PictureBox control or
the form object. It requires the file path as an argument. The following
example shows you how to use the LoadPicture function.

Example:
Code:
Private Sub cmdShow_Click()
Picture1 = LoadPicture("D:\pic.JPG")
End Sub
Output:

The Paint event


The Paint event fires automatically when the form is refreshed. For
instance, the Paint event fires when you uncover areas in a form or when
you resize the form. If the AutoRedraw property is set to True, this event
will not be invoked. And while resizing, if you shrink the form, this event
does not fire.
You may use the necessary graphic methods inside the Paint event
procedure so that whenever the form is refreshed, the graphic methods are
automatically called.

Example:
Code:

Private Sub Form_Paint()


DrawWidth = 5
Circle (Rnd * 3000, Rnd * 7000), Rnd * 800, vbYellow
End Sub

New circles are drawn automatically when you resize the form. New
circles are drawn in random positions and with random sizes.

USING COLORS
Notice that all the graphics methods can use a Color argument. If that
argument is omitted, the ForeColor property is used. Color is actually a
hexadecimal (long integer) representation of color - look in the Properties
Window at some of the values of color for various object properties. So, one
way to get color values is to cut and paste values from the Properties
Window. There are other ways, though.

SYMBOLIC CONSTANTS:
Visual Basic offers eight symbolic constants (see Appendix I) to
represent some basic colors. Any of these constants can be used as a Color
argument.

Constant Value Color


vbBlack 0x0 Black
vbRed 0xFF Red
vbGreen 0xFF00 Green
vbYellow 0xFFFF Yellow
vbBlue 0xFF0000 Blue
vbMagenta 0xFF00FF Magenta
vbCyan 0xFFFF00 Cyan
vbWhite 0xFFFFFF White

QBCOLOR FUNCTION:
For Microsoft QBasic, GW-Basic and QuickBasic programmers, Visual
Basic replicates the sixteen most used colors with the QBColor function. The
color is specified by QBColor(Index), where the colors corresponding to the
Index are:

Index Color Index Color


0 Black 8 Gray
1 Blue 9 Light blue
2 Green 10 Light green
3 Cyan 11 Light cyan
4 Red 12 Light red
5 Magenta 13 Light magenta
6 Brown 14 Yellow
7 White 15 Light (bright) white

RGB FUNCTION:
The RGB function can be used to produce one of 224 (over 16
million) colors!

The syntax for using RGB to specify the color property is:

RGB(Red, Green, Blue)

where Red, Green, and Blue are integer measures of intensity of the
corresponding primary colors. These measures can range from 0 (least
intensity) to 255 (greatest intensity). For example, RGB(255, 255, 0) will
produce yellow.

· Any of these four representations of color can be used anytime your Visual
Basic code requires a color value.

Color Examples:
Form1.BackColor = vbGreen
picExample.FillColor = QBColor(3)
label1.ForeColor = RGB(100, 100,
100)

You might also like