80
VISUAL BASIC 5.0 Introduction:- Visual Basic is an ideal programming language for developing professional application for windows. It makes powerful application. Things to care:- When programming in visual Basic Developer must decide how the application interacts with the user. The user may do any event in the application on various controls. Two types of programes. Linier programming and event driven programming . user interface with computer also differs. In linier programings user is guided to a linier path of excecertion and small set of operation. A graphical user interface method is a technology in which we can interfaced the system graphically. The word BASIC refers BIGNERS ALL PURPOSE SYMBOLIC INSTRUCTION CODE. All program Syntax in VB is similar to the BASIC Language. Event Driven Programming Forms and controls are the basic elements in the user interface of any visual Basic application. In VB these elements are called as objects. Each object has there own properties and react to external events. Starting Visual Basic V.B is a component of visual studio. Click Start Microsoft Visual Studio.

VB1

Embed Size (px)

Citation preview

Page 1: VB1

VISUAL BASIC 5.0

Introduction:- Visual Basic is an ideal programming language for developing professional application for windows. It makes powerful application.

Things to care:-When programming in visual Basic Developer must decide how the application interacts with the user. The user may do any event in the application on various controls.

Two types of programes.Linier programming and event driven programming . user interface with computer also differs. In linier programings user is guided to a linier path of excecertion and small set of operation.

A graphical user interface method is a technology in which we can interfaced the system graphically.

The word BASIC refers BIGNERS ALL PURPOSE SYMBOLIC INSTRUCTION CODE. All program Syntax in VB is similar to the BASIC Language.

Event Driven Programming

Forms and controls are the basic elements in the user interface of any visual Basic application. In VB these elements are called as objects. Each object has there own properties and react to external events.

Starting Visual Basic

V.B is a component of visual studio.

Click Start Microsoft Visual Studio. Click Start Microsoft Visual Studio 6.0 Microsoft Visual Basic 6.0 or Double click on the Vb6 icon if it is available.

A New Project dialog box will appear with following options.

New This table enables as to create a New project.

Existing This tab is enable as to selection of already existing project which is same as File Open.

Recent This tab lists the Visual Basic projects that are used recently.

Page 2: VB1

Whenever a project is opened or a new project is started Visual Basic 6.0. Integrated development Environment (IDE) appears.

A New project is created by select standard Exe in the project dialog box. This will open a new project named project1.

Components of project

Integrated Development Environment

The Visual Basic development environment includes menus, tool bars windows and other tools help to build an application quickly and easily. This group of elements collectively called as Integrated Development Environment.

The ToolboxTool box contain number of controls that can placed on a form when a mouse cursor is placed on the control a pop up tool tip will appear displaying a short description of the control.

Tool barsVisual Basic has four default tool bars that can be made to appear on the screen or hidden using .

View Tool bars in menu section.1. Standard It contain all preliminary icons2. Edit Editing VB code.3. Debug To Assist in finding errors in the coding.4. Form Editors To adjusting items on the form.

Form Window Form Window is used to design the different forms which is an application. Each form can have many controls that perform various functions.

Property WindowProperly Window enables us to change one or more properly for the currently selected object. The properties of an object can be viewed either in alphabetical order or by catalogs.When a new object is loaded the default properties are set. But we can change the properties manually in design true or run time.Properly window has a status bar in the bottom, which displays the brief note of selected properly.

Project Explorer Window

Page 3: VB1

The project explorer window is viewed is manage the various components or files of project Related items are listed together in a free listing. The three buttons on the project explorer window enables the display of code, object or toggle folders.

On line HelpWe can access the visual Basic help system from Help menu by setting.

Contents Index Search Or Favorites Which give help to user from MSDN(Microsoft Developer Network two very useful help related features that no longer wait for user)

Visual Basic includes fallowing helps1. Auto list members2. Auto quick info

Auto list members is a time saving option that display a list box which contains the members (Properties or methods) that are available in code window.

The Auto Quick info option displays the syntax of any functions or method. When one enters the name of procedure followed by period space or open parenthesis.

Application Projects

Application: An application is a program or set of programs that performs some useful task. In Visual Basic an application consists of a large number of objects and small section of code that control the objects.

Project: A Visual Basic project simply an organizational “box” that is used to hold all the different components required by an application and coding that are used to control that objects.

Developing An Application (Project)

Developing an application is creating a project. Writing a Visual Basic Project involves two steps.

Visual programming step Code Programming step

Visual programming step involves designing an application with various tools that come along with Visual Basic package

The code programming step involves writing programs using text editor.

Page 4: VB1

There are several ways to create a new project

1. A new Project can be created either by std-Exe from dialog box. That appears when V.B is launched.

2. Selecting new from the file menu and then selecting standard Exe.

After this a new project is created with the name project that contains single empty form named form1.

Opening an Existing Project There are numerous ways to open an existing project. The last four projects that were opened are available directly from the file Menu.

.File Open project A dialog box with three tabs for New, Existing, New.

From windows explorer by db click

Using Project Explorer To identify files contained in project ,the project explorer window is very helpful. It uses 3 view to list projects and their contents

i) Code Viewii) Object Viewiii) Toggle

We can able toi) Hide PE by clickii) Move PE click and drag title bariii) Resize PE

Save a Project Store the project permanently in order to retrieve later .Steps to save the project is File Save First save the forms in the project. The file extension is .Frm At last project is saved by the extension .Vbp

Running the project You can run your project using any of the following methods

o Press F5o Click the run button on the standard tool baro Choose start from run menu on the step tool bar

Page 5: VB1

Property Methods and EventsAll the controls except pointer in the toolbar are objects in visual basic. These object have associated with properties methods and eventsProgramming object has properties. A property is a named attribute of a programming object. Property is a named attribute of a programming object. Property define the characteristics of an object such as size, color etc.For example a text box accepts properties such as enabled font multilane text, visible width etc.

Enabled Enabled True/False run time Font Particular font ,size ,bold etc. Multiple Accept and display multiple line Text Particular text to display Visible Hide/Unhide in runtime Width Desired width in runtime

These properties can be set at design time by selecting properties windows. But certain property cannot set in design time. Eg(current x, Current y property of a box)In object oriented programming a method is connected or built in procedures .A block of code that can be invoked to instruct some action on a particular project

For eg move has no meaning in VB, but Text1.move 700,400 perform an action.

Some Methods Refresh Repaint of the control or form Set focus Move the control to that focus

Event Driven ProgrammingIn VB programs are built around events. Events are various actions that can happen in a program. In event driven programming the statements are executed only when a particular event calls a specific post of the code that is assigned to that event.Each and every control has their own events. For e.g. Textbox control has the following events Change Click Mouse Move

Working with forms

Form is the one of the most basic objects in which the application is developed. A form is a window that contains application code and other objects placed on it to create the user interface.Visual Basic initially includes a default form form1 file in each new project. You can change the forms name and caption to identify the purpose of the form.

Page 6: VB1

Setting Form propertiesBorder Style Forms can have variety of type borders. The borders that are available are as follows.

Option PurposeNone

Fixed single

Sizable

Fixed Double

Fixed Tool Window

Sizable tool Window

No Border is shown. in addition maxima button, minima button, title bar and close button from view

A single fixed width border is shown around the form

This is the default setting. The border around the form’s left so we can’t resize.

A double-pixel border is placed around the form

This type of border is used for toolbars that might be floating in workspace only the title bar and close box are visible but in reduced size

Same as fixed Tool Window borders are resizable

Data Type and Control StructuresProperty-: Properties are variables or memory locations that VB uses to store the information it needs to properly handle the different objects and commands in the application.

Modules-:Code in VB is stored in the form of modules. Three kinds of modules are

i) Form Modulesii) Standard Modulesiii) Class Modules

A simple application may contain a single form and the code resides inside the form only as application grows additional forms are added and there may be a common code to be executed in several forms. To avoid duplication of code a separate module containing procedure is created that implements the common code. This is a standard module.

Page 7: VB1

Class Module Class modules are the foundation of object oriented programming in VB. New objects can be created by writing code in class module. Class has an extension .cls. Each module contain

Declaration -: May include constant, type, variable and procedure declaration

Data TypesBy default VB variables are variant data type. The variant data type can store numeric date/time or string data. The fundamental data data types in VB are

Data Type Description Declaration Character RangeByte 1 Byte None 0 to 255Boolean 2 Bytes None True or FalseInteger 2-byte integer % -32,768 to 32,768Long 4-byte integer & 2,147,483,648 to –

2,147,483,648Single 4-byte floating

Point number! 3.402823E38 to –

3.402823E38Double 8-byte floating

Point number# 1.79769313486232D308

to –1.79769313486232D308

Currency 8-byte number with fixed decimal

@ 922,337,203,685,477.5808 to –922,337,203,685,477.5808

Object 4 bytes None Any object referenceDate8 bytes

None 1/1/100 to 12/31/9999

String

String String of characters

$ Through characters 65,500

Variant Date/Time floating-point numbers of strings

None Can contain numeric data in the range as a double, or any string character

Variant is the most flexible type of variable that can be used. It can be used to work with most of the other data types, except for fixed-length strings.

1. Integer2. Long3. Single4. Double5. Date6. String

Page 8: VB1

7. Currency8. Byte9. Boolean

VariableVariable is an identifier which hold data temporally. Variable must begin with a alphabet. Maximum length not exceed 255 char. It should not contain any special characters There are many way of declaring variable in VB

a) Explicit Declarationb) Using option explicit statementc) Scope of variable

Explicit Declaration On declaring variable in Vb reserve space in memory .It is not must declaring variable before we use automatically. Whenever VB encounters a new variable it assign default variable type and value. This is called implicit declaration.

To have more control over the variable .We can use explicit declaration. These variable are declared within a Dim statement allows to define the datatype or objecttype of variableSyntax Dim variable [As type] For example Dim name as string Dim count as integerUsing Option Explicit On declare variables implicit implicitly, but it leads to errors. If the variables are not recognized in run time. To prevent error of this nature we can declare a variable by adding the following statement to the general declaration section of the form.

Dimensioning Variables DIM statement is used to declare a variable. It specifies the name and data type of a new variable.

Option Explicit StatementThe option explicit statement will instruct VB to display an error for any variable that was not explicitly dimensioned in the program. To ensure the setting always turned on the option in VB can be set so that every form or module that is added to the project will automatically have this option added to it. This can be done by

Tools Options Required variable declaration

The scope of a VariableThe scope of a variable refers how long it can be used and which routines can see itThree different type of scopes a variable can have

1. Global2. Module3. Local

Page 9: VB1

Local ScopeWhenever a variable is declared inside a function subroutine or event routine. Only the code within the procedure can see variable .This is referred to as local scope.Eg Sub Routine() Dim var1 as integer Dim var2 as string Var1=6 Var2=”This is a demo” Sub routine2() Dim var1 as string Dim var2 as integer Var1=”This is a demo” Var2=65

End sub

As it can be seen the same variables name can be used in separate routines because they are local to each routine and not known by the other routine.

Module ScopeA variable can be declared with module scope by using the private declaration statement. The syntax of the private statement is same as Dim statement except for the keyword private. Any variable declared as private can be seen in any routine within the module or form. Where it was declared Private var1 as integer Private var2 as string Sub Routine() Var1=6 Var2=”This is a demo” End sub

Sub Routine() Var1=”This is a demo” Var2=6

End sub As seen in the above program the variables are declared outside the routine the same variable cannot be used for different data types.

Global Scope

Page 10: VB1

Most powerful of the scope .To define a variable as global .the public declaration statement is used. The syntax of the public statement is same as Dim except the keyword public

Private var1 as integer Private var2 as string Sub Routine1() Var1=6 Var2=”This is a demo” End sub

Sub Routine2() Var1=”This is a demo” Var2=6 End sub

Control structuresWhen designing a new application the developer needs to execute section of codes conditionally. The program should respond for condition or test if the condition is true then the code will be processed. 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, Do… Loop while and for … Next method.

If…Then…Else statementThe If… Then block is used for conditional execution of one or more statements.

If Condition Then StatementsEnd If

The statement is executed only if the condition is true. The condition is usually a comparison, but it can be any expression that evaluates the numeric value. If Then…. Else block is used to define several blocks of statements in order to execute one block. The following block of statement illustrates If…Else…End if statements.

If A=1 Then StatementsElse StatementsEnd if

The following example illustrates the If…Then …Else statement.

Page 11: VB1

Example 1.4

Illustrate an example to check for the number of digits in a number and display a message indicating the number of digits in it within 1000.

o A new Standard EXE project is opened and a Textbox and Command Button is added to the form. The following code is entered in the Command1_Click( ) procedure.

Private Sub Command1_Click( ) If val (Text1. Text)<10 Ten MsgBox “It is a Single Digit Number”

ElseIf Val (Text1. Text)< 100 Then MsgBox “It is a Two Digit Number”ElseIf val (Text1.Text)<1000 Then MsgBox “It is a Three Digit Number”

Else MsgBox “ The value is more than Three Digits”

End IfEnd Sub

The program is executed by pressing F5. When a number is entered in the Text box, it displays a message accordingly.

Select… Case statementSelect…Case structure is an alternative to If. Then…Else If for selectively executing a single block of statements from among multiple blocks of statements. Select… Case is more convenient to use than the If…Else…End If. The following program block illustrates the working of Select…Case.

Select case IndexCase 0

Statements

Case1Statements

End select

Select…Case structure evaluates an expression once at the top of the structure, where as If..Then…Else If structure evaluates different expressions for each Else If statement.

Do While..Loop statement

Page 12: VB1

The Do While…Loop is used to execute statements until a certain condition is met. The following Do loop counts from 1 to 100

Counter =1Do while counter <101Counter =counter <1Loop

The variable counter is initialized to 1 and then the Do while loop starts.

Do…Loop While statement

The Do…Loop While statement first executes the statements and then tests the condition after each execution. The following program block illustrates the structure.Counter=300

DoText1.Text =str (counter)Counter = counter +1Loop while counter < 501

The program executes the statements between Do and Loop. While structure in any case. Then it determines whether the counter is less than 501.If so, the program again executes the statements between Do and Loop While else exits the loop.

Do…Loop Until statement

The Do… loop Until structure executes the statements until the condition is satisfied. It is an infinite loop if the text fails and to get released from this infinite loop we can use the CTRL + BREAK combination or End from the Rum menu. The following code entered in the Form_Load( ) procedure illustrates the structure.

Example 1.5

Private Sub Form_Load( )DoX$ = Inputbox$ (“Password Please ?”)Loop Until X$ = “Vanilla Orange”

End Sub

The above example checks for the password set to open the format runtime. At run time it asks for the password and until it is entered as “Vanilla Orange” the loop remains infinite. Once the correct password is typed in the input box and clicked OK, the form is opened.

The For…Next Loop statement

Page 13: VB1

The For…Next Loop is another way to make loops in Visual Basic. The following loop counts from 1 to 50.

For I=1 to 50 step 1Text1.Text = Str (I)Next

In order to count from 1 to 50 in steps of 2, the following loop can be used.

For I =1 to 50 step 2Text1. text =Str (I)Next

The loop counts as 1,3,5,. Etc.

Exit For and Exit Do statement

A For…Next loop can be terminated by an Exit For statement. Consider the following statement block:

For I=1 to 100 Text1.Text = str (I) If I = 50 Then Exit for End If

Next

The preceding code increments the value of 1 by 1 unit it reaches the condition 1 = 50.The Exit For statement is executed and it terminates the For….Next loop. The following statement block- containing Do…While loop is terminated using Exit Do statement.

I = 1Do while I < 1001Text 1. Text = Str ( I ) I = I + 2 If I >500 then Exit no End If

Loop

With - End Statement

Page 14: VB1

When properties are set for objects or methods are called, a lot of coding is included that acts on the same object. It is easier to read the code by implementing the With-End With statement.Multiple properties can be set and multiple methods can be called by using the With-End With statement. The code is executed more quickly and efficiently as the object is evaluated only once. This concept can be clearly understood with the following example. With text price .font. size=16 .font. italic=true .height=235 .text=”Welcome to Visual Basic 6.0” end with

Introduction to Data Access

All applications use structured information of one kind or another. Data access in Microsoft Visual Basic gives you the tools to create and use structured database systems to manage your application's data.

These tools include the Microsoft Jet database engine, the Data control, and the data access objects (DAO) programming interface.

Using data access objects, you can create databases and build full-featured applications that access existing databases in many popular formats, including Microsoft Access, Bereave, dBase, Microsoft FoxPro, and Paradox, as well as Open Database Connectivity (ODBC) client/server databases like Microsoft SQL Server.

The ability to create and access structured database systems gives you many programming advantages:

· It lets you write programs that use existing databases.

· It allows your application to share data with other programs.

· It simplifies your programming, since you do not need to handle low-level file accessing and searching.

Data Access Object (DAO)

Visual Basic provides two methods of interfacing with the Jet database engine: the Data control and data access objects. The Data control gives you limited ability to access existing databases without programming; the DAO model is a complete

Page 15: VB1

programming interface that gives you total control of the database. These two methods are not mutually exclusive; in fact, there are many situations where you will want to use both of them together.

The DAO model is a collection of object classes that model the structure of a relational database system. They provide properties and methods that allow you to accomplish all of the operations necessary to manage such a system, including facilities for creating databases, defining tables, fields and indexes, establishing relations between tables, navigating and querying the database, and so on.

The Jet database engine translates these operations on data access objects into physical operations on the database files themselves, handling all the mechanics of interfacing with the different supported databases.

Database programming in Visual Basic consists of creating data access objects, such as Database, Table Def, Field, and Index objects, that correspond to the various parts of the physical database you want to access. You use the properties and methods of these objects to perform operations on the database. You can display the results of these operations and accept input from the user on Visual Basic forms, using both bound and unbound controls.

This approach simplifies the code you need to write and insulates you from the underlying structure and mechanics of retrieving and updating data. It gives you great flexibility, because you can use the same objects, properties, and methods to work with a wide variety of supported database formats. Also, if you change from one database format to another (for example, porting a local Microsoft Access database to a SQL Server database on a network), you'll need to make few changes in your code to accommodate the change. You can even create applications that join tables from two or more different databases in a single query or report.

There are three categories of databases that Visual Basic recognizes through DAO and the Jet engine:

· Visual Basic Databases

Also called native databases, these database files use the same format as Microsoft Access. These databases are created and manipulated directly by the Jet engine and provide maximum flexibility and speed.

· External Databases

These are Indexed Sequential Access Method (ISAM) databases in several popular formats, including Btrieve, dBASE III, dBASE IV, Microsoft FoxPro versions 2.0 and 2.5, and Paradox versions 3.x and 4.0. You can create or manipulate all of these database formats in Visual Basic. You can also access text file databases and Microsoft Excel or Lotus 1-2-3 worksheets.

· ODBC Databases

These include client-server databases that conform to the ODBC standard, such as Microsoft SQL Server. To create true client-server applications in Visual Basic, you can use ODBC Direct to pass commands directly to the external server for processing.

Page 16: VB1

Remote Data Object (RDO)

Remote Data objects and collections provide a framework for using code to create and manipulate components of a remote ODBC database system. Objects and collections have properties that describe the characteristics of database components and methods that you use to manipulate them. Using the containment framework, you create relationships among objects and collections, and these relationships represent the logical structure of your database system.

Objects and collections provide different types of containment relationships: Objects contain zero or more collections, all of different types; and collections contain zero or more objects, all of the same type. Although objects and collections are similar entities, the distinction differentiates the two types of relationships.

Intrinsic Controls

The following table summarizes the intrinsic controls found in the Visual Basic toolbox.

Icon Control nameClass name Description

o Check box CheckBox Displays a True/False or Yes/No option. You can check any number of check boxes on a form at one time.

o Combo box ComboBox Combines a text box with a list box. Allows a user to type in a selection or select an item from a drop-down list.

o Command button CommandButton Carries out a command or action when a user chooses it.

o Data Data Enables you to connect to an existing database and display information from it on your forms.

o Directory list box DirListBox Displays and allows a user to select directories and paths.

o Drive list box DriveListBox Displays and allows a user to select valid disk drives.

o File list box FileListBox Displays and allows a user to select from a list of files.

Frame Frame Provides a visual and functional container for controls. Horizontal and vertical scroll bars HScrollBar and VScrollBar Allow

a user to add scroll bars to controls that do not automatically provide them. (These are not the same as the built-in scroll bars found with many controls.)

Image Image Displays bitmaps, icons, or Windows metafiles, JPEG, or GIF files; acts like a command button when clicked.

Label Label Displays text a user cannot interact with or modify.Line Line Adds a straight-line segment to a form. List box ListBox Displays a list of items that a user can choose from.OLE containerOLE Embeds data into a Visual Basic application.

Page 17: VB1

Option button OptionButton The Option Button control, as part of an option group with other option buttons, displays multiple choices, from which a user can choose only one.

Picture box PictureBox Displays bitmaps, icons, or Windows metafiles, JPEG, or GIF files. It also displays text or acts as a visual container for other controls.

Shape Shape Adds a rectangle, square, ellipse, or circle to a form, frame, or picture box.

Text box TextBox Provides an area to enter or display text.Timer Timer Executes timer events at specified time intervals.

ActiveX

Several other standard controls are included in the Visual Basic toolbox. Some controls are useful for working with large amounts of data contained in an external database. Other controls can be used to access the Windows file system. Still other controls defy categorization, but are useful nonetheless.

You can also use ActiveX controls, previously called custom or OLE controls, in a Visual Basic application in the same way that you use the standard controls. The Professional and Enterprise editions of Visual Basic include several ActiveX controls as well as the capability to build your own controls. Additional ActiveX controls for just about any purpose imaginable are available for purchase from numerous vendors.

MS Flex Grid Controls

. The MSFlexGrid control displays and operates on tabular data. It allows complete flexibility to sort, merge, and format tables containing strings and pictures. When bound to a Data control, MsFlexGrid displays read-only data.

You can put text, a picture, or both in any cell of a MSFlexGrid. The Row and Col properties specify the current cell in a MSFlexGrid. You can specify the current cell in code, or the user can change it at run time using the mouse or the arrow keys. The Text property references the contents of the current cell.

If a cell's text is too long to be displayed in the cell, and the Word Wrap property is set to True, the text wraps to the next line within the same cell. To display the wrapped text, you may need to increase the cell's column width (ColWidth property) or row height (RowHeight property).

Use the Cols and Rows properties to determine the number of columns and rows in a MSFlexGrid control.

Distribution Note Before you can use a MSFlexGrid control in your application, you must add the MSFlxGrd.ocx file to your project. To automatically include the file in your project, put it in the Autoload file. When distributing your application, you should install the MSFlxGrd.ocx file in the user's Microsoft Windows System

Page 18: VB1

directory. For more information about adding an ActiveX control to a project, see the Programmer's Guide.

DB Grid Control

Displays and enables data manipulation of a series of rows and columns representing records and fields from a Recordset object.

The data-aware DBGrid control appears similar to the Grid control; however, you can set the DBGrid control's DataSource property to a Data control so that the control is automatically filled and its column headers set automatically from a Data control's Recordset object. The DBGrid control is really a fixed collection of columns, each with an indeterminate number of rows.

Each cell of a DBGrid control can hold text values, but not linked or embedded objects. You can specify the current cell in code, or the user can change it at run time using the mouse or the arrow keys. Cells can be edited interactively, by typing into the cell, or programmatically. Cells can be selected individually or by row.

If a cell's text is too long to be displayed in the cell, the text wraps to the next line within the same cell. To display the wrapped text, you must increase the cell's Column object's Width property and/or the DBGrid control's RowHeight property. At design time, you can change the column width interactively by resizing the column or by changing the column's width in the Column object's property page.

Use the DBGrid control's Columns collection's Count property and the Recordset object's RecordCount property to determine the number of columns and rows in the control. A DBGrid control can have as many rows as the system resources can support and about 1700 columns.

When you select a cell, the ColIndex property is set, thus selecting one of the Column objects in the DBGrid object's Columns collection. The Text and Value properties of the Column object reference the contents of the current cell. The data in the current row can be accessed using the Bookmark property, which provides access to the underlying Recordset object's record. Each column of the DBGrid control has its own font, border, word wrap, color and other attributes that can be set without regard to other columns. At design time, you can set the column width and row height and establish columns that are not visible to the user. You can also prevent users from changing the formatting at run time.

ActiveX Control Overview

An ActiveX control is an extension to the Visual Basic Toolbox. You use ActiveX controls just as you would any of the standard built-in controls, such as the CheckBox control. When you add an ActiveX control to a program, it becomes part of the development and run-time environment and provides new functionality for your application.

Page 19: VB1

ActiveX controls leverage your capabilities as a Visual Basic programmer by retaining some familiar properties, events, and methods, such as the Name property, which behave as you would expect. Then, however, the ActiveX controls feature methods and properties that greatly increase your flexibility and capability as a Visual Basic programmer.

ActiveX ControlsSeveral other standard controls are included in the Visual Basic toolbox. Some controls are useful for working with large amounts of data contained in an external database. Other controls can be used to access the Windows file system. Still other controls defy categorization, but are useful nonetheless.

Types of ActiveX control

ActiveX components give you the power to put together sophisticated applications from pieces that already exist. Your Visual Basic applications can include several types of ActiveX components:

Applications that support ActiveX technology, such as Microsoft Excel, Microsoft Word, and Microsoft Access, provide objects that you can manipulate programmatically from within your Visual Basic application. For example, you can use the properties, methods, and events of a Microsoft Excel spreadsheet, Microsoft Word document, or Microsoft Access database in your application.

Code components provide libraries of programmable objects. For example, a code component could include a library of specialized financial functions for spreadsheet users, or user-interface elements, such as dialog boxes, that are common to multiple applications. Unlike an object in an ActiveX-enabled application, an object in a code component can run in the same process as your application, allowing faster access to the object.

You can add features without having to create them yourself by using ActiveX controls as components. ActiveX controls are available from a variety of vendors to provide many specialized features, such as displaying a calendar on a form or reading data in a particular format.

ActiveX documents let you create interactive Internet applications. You can create forms that can be contained within Internet Explorer. ActiveX documents can show message boxes and secondary forms and contain ActiveX controls. ActiveX documents can also function as code components. For a step-by-step introduction to ActiveX documents, see "Creating an ActiveX Document" in the Component Tools Guide, available in the Professional and Enterprise editions.

Page 20: VB1

Some ActiveX components run in the same process as your application, while others run in a separate process. For more information, see "In-Process and Out-of-Process Servers."

In addition to components in existing ActiveX-enabled applications, code component libraries, ActiveX controls, and ActiveX documents, you can create your own components. For more information on creating your own ActiveX components, see "Creating ActiveX Components" in the Component Tools Guide, available in the Professional and Enterprise editions.

Data control

Data control Provides access to data stored in databases using any one of three types of Recordset objects. The Data control enables you to move from record to record and to display and manipulate data from the records in bound controls. Without a Data control or an equivalent data source control like the RemoteData control, data-aware (bound) controls on a form can't automatically access data.

Syntax

Data

Remarks

You can perform most data access operations using the Data control without writing any code at all. Data-aware controls bound to a Data control automatically display data from one or more fields for the current record or, in some cases, for a set of records on either side of the current record. The Data control performs all operations on the current record.

If the Data control is instructed to move to a different record, all bound controls automatically pass any changes to the Data control to be saved in the database. The Data control then moves to the requested record and passes back data from the current record to the bound controls where it's displayed.

The Data control automatically handles a number of contingencies including empty recordsets, adding new records, editing and updating existing records, and handling some

Page 21: VB1

types of errors. However, in more sophisticated applications, you need to trap some error conditions that the Data control can't handle. For example, if the Microsoft Jet database engine has a problem accessing the database file, doesn't have permission, or can't execute the query as coded, a trappable error results. If the error occurs before your application procedures start or due to some internal errors, the Error event is triggered.

Bound Controls

The DBList, DBCombo, DBGrid, and MSFlexGrid controls are all capable of managing sets of records when bound to a Data control. All of these controls permit several records to be displayed or manipulated at once.

The intrinsic Picture, Label, TextBox, CheckBox, Image, OLE, ListBox and ComboBox controls are also data-aware and can be bound to a single field of a Recordset managed by the Data control. Additional data-aware controls like the MaskedEdit and RichTextBox controls are available in the Professional and Enterprise Editions and from third-party vendors.

Operation

Once the application begins, Visual Basic uses Data control properties to open the selected database, create a Database object and create a Recordset object. The Data control's Database and Recordset properties refer to the newly created Database and Recordset objects which may be manipulated independently of the Data control — with or without bound controls. The Data control is initialized before the initial Form_Load event for the form on which it is placed. If any errors occur during this initialization step a non-trappable error results.

When Visual Basic uses the Jet database engine to create a Recordset, no other Visual Basic operations or events can occur until the operation is complete. However, other Windows-based applications are permitted to continue executing while the Recordset is being created. If the user presses CTRL+BREAK while the Jet engine is building a Recordset, the operation is terminated, a trappable error results, and the Recordset property of the Data control is set to Nothing. In design time, a second CTRL+BREAK causes Visual Basic to display the Debug window.

When you use a Data control to create a Recordset object or when you create a Recordset object in code and assign it to the Data control, the Microsoft Jet database engine automatically populates the Recordset object. As a result, bookmarks (and for snapshot-type Recordset objects, recordset data) are saved in local memory; the user doesn't need to manipulate the Data control, and you don't need to invoke the MoveLast method in code. Page locks used to create the Recordset are released more quickly, making it possible for other Recordset objects to access the same data. Recordset objects created in code but not assigned to the Data control aren't automatically populated by the Jet engine. Populate these objects through code. Because of the way that the Data control populates its Recordset in the background, an additional cloned Recordset might be created.

Page 22: VB1

You can manipulate the Data control with the mouse, moving from record to record or to the beginning or end of the Recordset. The EOF Action and BOF Action properties determine what happens when the user moves to the beginning or end of a Recordset with the mouse. You can't set focus to the Data control.

Validation

Use the Validate event and the DataChanged property to perform last minute checks on the records being written to the database.

Data Access Objects

You can use the Database and Recordset data access objects created by the Data control in your procedures. The Database and Recordset objects each have properties and methods of their own, and you can write procedures that use these properties and methods to manipulate your data.

For example, the MoveNext method of a Recordset object moves the current record to the next record in the Recordset. To invoke this method, you could use this code:

Data1.Recordset.MoveNext

The Data control is capable of accessing any of the three types of Jet engine Version 3.0 Recordset objects. If you don't select a recordset type, a dynaset-type Recordset is created.

In many cases, the default type and configuration of the Recordset object created is extremely inefficient. That is, you might not need an updatable, fully-scrollable, keyset-type cursor to access your data. For example, a read-only, forward-only, snapshot-type Recordset might be far faster to create than the default cursor. Be sure to choose the most efficient Type, Exclusive, Options and ReadOnly properties possible for your situation.

Note The constants used to request a specific Recordset type when using the Data control are different than the constants used to determine the type of Recordset created or to create a Recordset using the OpenRecordset method.

To select a specific type of Recordset, set the Data control's RecordsetType property to:

Recordset Type Value ConstantTable 0 vbRSTypeTableDynaset 1 (Default) vbRSTypeDynasetSnapshot 2 vbRSTypeSnapshotImportant The Data control cannot be used to access Recordset objects created with the dbForwardOnly option bit set.

Page 23: VB1

Stored Queries

Another important option when using the Data control is the ability to execute stored queries. If you create a QueryDef object beforehand, the Data control can execute it and create a Recordset using the QueryDef object's stored SQL, Connect and other properties. To execute a QueryDef, set the Data control's RecordSource property to the QueryDef name and use the Refresh method.

If the stored QueryDef contains parameters, you need to create the Recordset and pass it to the Data control.

BOF/EOF Handling

The Data control can also manage what happens when you encounter a Recordset with no records. By changing the EOFAction property, you can program the Data control to enter AddNew mode automatically.You can program the Data control to automatically snap to the top or bottom of its parent form by using the Align property. In either case, the Data control is resized horizontally to fill the width of its parent form whenever the parent form is resized. This property allows a Data control to be placed on an MDI form without requiring an enclosing Picture control.

DLLs and Windows Functions The Windows system is the foundation code of the entire windows environment. Calls to procedures in the windows system are actually calls to the windows API (application programming interface). The windows API provides hundreds of functions and subroutines that programs can call to create windows, menus, and controls, to do drawing, and so on. Any windows program calls a number of these functions and subroutines. Visual Basic programs you write call these subroutines and functions indirectly. For example, Visual Basic’s line command is converted in to a call to the Windows API line To command, which draws lines inside a window. All these windows API functions are provided through a mechanism Known as a dynamic link library that’s loaded in to memory and connected to your program on demand. Windows comes with a number of DLLs to provide all the subroutines and functions windows programs can call. One powerful feature of Visual Basic is the ability to call almost any or someone else might write. Visual Basic provides only a subset of the

Page 24: VB1

total functions of the Windows API. Using the DLLs, you can make direct calls to any functions not included in Visual Basic.

Crystal Reports

Working with the Crystal Reports About this Chapter: This chapter gives us a brief introduction to Crystal Reports and the various ways of generating reports using it. It also discusses the crystal Custom Control and the properties and methods associated with them.ObjectivesIntroduction to Crystal Reports.Creating Crystal Reports.Crystal Report Control.More an crystal Reports.Introduction The Crystal Reports package contains two separate elements that is the Crystal Reports, and the Crystal Custom Control. Used together, these two elements provides us with the ability of generating custom reports, transparently, via our application. Crystal reports is a powerful windows report writer that can be used to design an endless variety of custom reports. Using Crystal Reports we can design the reports that can be called from the user a application.The crystal custom control is a set of tools that makes the building of the connection between our application and the print engine easier. Using these tools we can generate. Reports in a very short time.

Introduction to Crystal ReportsCrystal Reports is a powerful program for creating custom reports, lists and from letters. Make calculations and comparisons of data values. Calculate grand totals and subtotals of values. Test for the presence of specific values. Present data only if specific conditions are met. Evaluate logical relationship between values, Convert data from one type to another, Merge text with other text or data field’s data, Calculate group averages, count the records in a group and test for minimum

and maximum values. The data can be placed at the required spot on the report, with special fonts and font sizes. once a report has been designed it can be used as a template for creating other similar reports, which saves a lot of time creating new reports from scratch Need for Crystal ReportsTechnical and non-technical users can generate custom reports is using Crystal Reports in a quicker and easier way. Crystal Reports is designed

Page 25: VB1

to be by anybody, and they do not require extensive knowledge of database. It prepares reports by reading data in the database files that has been selected and making that data available for use in the report. Reports can be created from a single data file as from multiple data files. The following are some example of reports that can be generated using Crystal Reports:

Simple columnar lists from a single database or a report that includes data from different sources.

Cross-tab reports that enables comparisons. Mailing labels can be created with the available data and rotary file cards, disk

labels and other similar label type items. Customized from letters that simple draw data from a database for address and

salutation, or sophisticated letters that includes different blocks of text depending on the relationships found in the data.

Reports that print directly on the preprinted forms Reports that generate personalized job description based on job number to

which a person is assigned. Mountains of data in multiple database can be analyzed and we can assign

priority numbers to alternatives or flag the items of greater interest.

Databases that work with Reports

Crystal Reports can build reports with the standard data files generated by Microsoft Access, dBASE, Paradox, Clipper and Brief. The program also supports SQL Server via ODBC. In this chapter reports are generated from the SQL server database using ODBC.

.We are familiar to curtail extent about Crystal Reports, hence let us understand the way in which reports can be generated.

Creating Crystal Reports

To start crystal reports from Visual Basic, Report Designer item is selected from the Add-Ins menu. Fig 7.1. Represents a Crystal Reports window from which new reports can be generated. Let us consider an example to generate a simple report.

Fig (fig)

Example 7.1 The new item is clicked in the Crystal Reports Pro window that displays Create

New Report dialog box (Fig 7.2)

Fig 7.2

Page 26: VB1

Custom button is clicked for generating custom reports. Selecting the desired option (Standard) results in displaying the Create Report Expert dialog box as in Fig. 7.3

Fig 7.3

On choosing the SQL/ODBC item, the Log on Server dialog box appears. Select the Datasource name as XYZCompany from the list provided on click OK.

Fig 7.4

The SQL/Table dialog box appears as shown in Fig 7.5 select the database table known as emp_details and click add. It returns to the Crystal Report Expert dialog box.

Fig 7.5

A title section is generally used for entering report title. Title section appears only in the first page of the report. Page header section is generally used for the report title, field headings, range of values included, and other information that needs to appear at the top of each page. By default, the Page header section has room for three lines. Detail section is the body of the report. The bulk of the report data will generally appear in this section. By default, the Details section has room for one line.Page footer section usually contains the page number and any other information that needs to appear at the bottom of each page. By default, the Page footer section has room for three lines. Each section is separated by a section marker, which displays the section name. A report is built by inserting data fields, formulas, and other report elements (record counts, record numbers, etc.) in the Details section of the Designer. The insert menu can be used, in most cases, to select or create the elements to be inserted in the report. The Report Designer uses rectangular field boxes to indicate the size, position, and data type of the fields and formulas that have been inserted.The Insert Database Field appears on the screen with the report Designer. The dialog box appears automatically, as it is almost certain that the database field has to be inserted for creating a new report. All the tables and their respective fields are listed in the dialog box and are available for building the report.

Page 27: VB1

DBGrid Control

The DBGrid control is a spreadsheet-like bound control that displays a series of rows and columns representing rows and fields from a recordset object. The DBGrid control’s Data Source property can be set to a Data control so that the control is automatically filled and its column headers are set automatically from a Data control’s Recordset object.Each cell of a DBGrid control can hold either text or picture values, but not linked or embedded objects. The user can specify the current cell in the code, or the user can change it at run time using the mouse or the arrow keys. Cells can be edited interactively, by typing into the cell, or Programmatically. If a cell’s text is too long to be displayed in the cell, the text wraps to the next line within the same cell. To display the wrapped text, the DBGrid control’s Row Height property has to be increased.ADBGrid control can have as many rows as the system resources can support about 1700 columns. When a cell is selected, the Collndex property is set, thus selecting one of the Column objects in the DBGrid object’s Columns collection. The Text and Value properties of the Column object reference the contents of the current cell. The data in the current now can be accessed using the Bookmark property. Which provides access to the underlying Recordset object’s record. Each column of the DBGrid control has its own font, border, word wrap, color and other attributes that can be set without regard to other columns.

The Control Selection window, which is the last but one window of this wizard, is used to select the necessary database functionality the user wants.

In the Finished window, name the form that is the name of the Visual Basic project and save the settings to run the form whenever required. Lastly press the Finish button to generate the form.

Fig. 14.8 When creating an Active X control, we would probably want to create some properties,, events and methods that are unique to the control. Earlier this had to be done by writing a code for each element we wanted to add. The origin of ActiveX Control wizard has solved this problem for us. This allows us to create events, properties and methods in a graphical, wizard-based environment and generates the Visual Basic code for us. This wizard can also be used to edit the existing elements that have already been configured for our control.Process involved in creating an Active X Control using this wizard is to select the Active X control that the user wishes to operate on in the Select a Control window of the Active X Control Interface wizard.The next window is the Select Interface Members Window, which allows us to select properties, methods, and events that we would like to add to our control. Interface elements contained in our control are listed in the Selected

Page 28: VB1

Names list box. Some elements would be added already to the selected Names list box. These are default elements that most Active X controls contain. We may choose not to include them in our control. The arrow buttons to the left of the list box are used to add or remove elements.The Create Custom Interface Members window, which follows the above, will be used to create our control’s custom interface. The New button is pressed to create a new interface element and is also named suitably. The name provided to the interface element must be a valid variable or procedure name in out Visual Basic program.The Set Mapping window allows us to map our Active X control’s properties, events, and methods to constituent controls contained within our Active X control. To do this, choose an element from the Public Name list box, then choose a control from the Control Combo box to map it to. Below the Control combo box, the member combo box will be filled with the properties, events or methods of the control that we choose in the control combo. The list that appears in the Member combo depends on whether we have selected a property, event, or method from the Public name.The Set Attributes window which is the last but one window is used to set attributes such as return values and data types of the members that are not mapped by the user in the Set Mapping window. For methods, we can specify an optional argument list that will appear as the formal parameter list in our Visual Basic code. An example of an argument list is Item as string Optional Index as Variant.The process is complete and lastly we move on to the finished window. Here the View Summary Report checkbox is clicked if we have to see the TODO Statements where the user needs to add coding. Active X Document Migration Wizard Add – In

The Visual Basic forms can sometimes be used as documentation rather than as programming components. The Active X Document Migration wizard Add- in allows us to perform such documentation. By using this wizard provided by windows, we can create an Active X document from a Visual Basic form.The various steps involved in creating an Active X Document Migration wizard Add-In the are as elucidated in the steps given below.The first form selection window is as shown in the fig 14.9 from which the required forms are selected. This can be done by checking the check boxes next to the form. The listed form names are pulled form our current project in the Visual Basic IDE.

IIS and DHTML applications

An IIS (Internet Information Server) application is a combination of Visual Basic code and HTML in a browser based application. An IIS application works in conjunction with Microsoft Internet Information Server. It is installed on an IIS web server where it processes data requests using the Visual Basic code and serves up the associated HTML

Page 29: VB1

Web pages. Visual Basic even provides a project template to begin the creation of such an application: File New Project (IIS Application).Once the server hands the client request via the browser to the IIS application, the embedded code can manipulate data sources or other objects as required by thee processing. This code can then dynamically generate HTML pages, adding appropriate content, before handling the page back to the server to be forwarded to the browser.A DHTML application is a Visual Basic code with Dynamic HTML to create a browser-based application. Unlike an IIS application, which resides on the server and provides HTML pages, a DHTML application resides entirely on the client or the browser. The purpose of a DHTML application is to interact with a user at the browser level. Typically, any interaction with a Web page requires a complete roundtrip to the server and back. First, the browser (after processing the script on the web page) prepares a request: then the request is sent to the server, which processes it an finally, the response is sent back to the browser, which redraws the page. These end-to-end interactions are time-consuming, expensive and resource-hungry. DHTML solves this problem by providing a way to interact locally with a user.A DHTML application and an IIS application are not mutually exclusive-they complement each other in several ways. It is possible to create an IIS application that provides the overall framework for the application and one or more DHTML applications to provide user interaction.DHTML is not a new language. All of the traditional HTML elements are present, such as element headings and list tags. Moreover, DHTML is a set of enhancements that allow elements of a page to be changed or manipulated by the browser.Besides the dynamic nature of the language. DHTML can also be used to maintain state in the Web application. We can maintain state in the page itself instead of having to rely on the server, cookies or hidden data in the page. The browser itself becomes the state manager and it provides information to the currently loaded page and to the server to determine what action has to be done next.How is DHTML related to Visual BasicDHTML is based on the Document Object Model, which is a hierarchy of Web page elements. Elements are related to DHTML in the same manner in which controls are related to Visual Basic applications,. In addition, a page in a DHTML application corresponds to a Form object in Visual Basic. This development paradigm makes it relatively simple to use Visual Basic knowledge to develop smart Web pages. It is possible to write Visual Basic code inside the events of DHTML elements, just like writing any other even-driven code.A DHTML application is a new entry in the New Project dialog in Visual Basic. To create a simple DHTML application, follow the steps given below:

Page 30: VB1

Click on the DHTML application icon in the New Project dialog and press OK. We can see the standard Visual Basic environment that has been slightly modified. The Project Explorer window appears as shown in Fig 15.2.

Fig 15.2 Whenever a DHTML application is created, VB automatically builds a DHTML

designer module along with the code module. This code allows users to retrieve properties that can be used in the code for the user’s own purposes.Example 15.2Let us build an application that displays a page with different text formats and levels of headings.

Create a new project by selecting File> New project from the Visual Basic menu.

Select DHTML Application from the new project dialog box and click OK to create the project. Change the Name property of the project of DBF Start.The DHTML page I designer entry in the project Explorer’s is started and the designer window displayed. As seen in the figure, the designer is split into two panes. The pane on the left shows the list of components. Called elements in DTHML. The pane on the right is the browser’s representation of the page. It is possible to add complex elements such as command buttons and text boxes, apart from text.

Click the right pane of the designer window and add the following text. DBF Finance limited (heading)The salient features are listed below. (Definition)Excellent Deposit Schemes Offered. (Definition)Fixed Deposit (Heading 6)Recurring Deposit (Heading 6)Cumulative Deposit (Heading 6)DBF Family Deposit Scheme (Heading 6)DBF Students Education loan scheme (Heading 6)Safety Deposit Lockers Provided (Heading 2)All categories of depositors entertained (Heading 2)Insurance policies Undertaken (Heading 2)Health Care Policies offered (Heading 2)

Fig 15.3

The drop-Down list on the far-left portion of the upper tool bar contains common HTML paragraph styles. Which are shown in Table 15.2 next to their corresponding HTML tags.List Entry HTML tagNormal NoneFormatted >PREAddress < ADDRESS>Heading 1 <HI>Heading 2 < H2>Heading 3 <H3>

Page 31: VB1

Heading 4 < H4>Heading 5 <H5>Heading 6 <H6>Numbered List <OL>Bulleted List <UL>Definition <DL>Menu List <MENU>Definition Term <DT>Definition <DD>Paragraph <P>Table 15.2.The drop-down list box to the right shows any classes that have been defined in the style sheet. Classes are broken down versions of the way in which styles are defined in a cascading style sheet. Father to the right, another drop-drown list shows the fonts installed on the system. The final drop-down list on the right shows the relative point sizes for the chosen font, which translate to the SIZE attribute as in <FONT SIZE = 4>.

After including the different levels of headings, Save and Run the project. The output will be as shown in Fig 15.4.

Fig 15.4.

The DHTML controls

A major difference that can be found in the DHTML projects is the change in the Toolbox. In a new and separate HTML category, new controls have been added, as shown in Fig 15.5.

Fig 15.5.

These new controls are restricted for use within the DHTML designer, and will be unavailable if we try to open a standard form. Likewise, the standard controls, while still accessible on the Toolbox, cannot be used with DHTML Designers.Each control maps to a particular type of HTML element, mainly dealing with forms. The following sections give brief descriptions about these controls.ButtonThe buttons common to a standard HTML form either submit the data or clear the form.This new button does not correspond to either of those: instead, it can be used for any purpose. Since the events generated by it will be received by DHTML, this control will become much more valuable.Submit Button

Page 32: VB1

This button submits data to the URL specified at the beginning of the <FORM> tag. As this button has a single function and is specified differently in HTML/DHTML, it is a separate control, in VB. This button translates to <INPUT type = submit > in HTML.Reset buttonThis control clears any data in the form in which it is placed. If there is any data entry form in DHTML, it is always good to have a reset button so that any data typed in can be cleared. This button translates to <INPUT type=reset>in HTML.Text fieldThis control is used as a standard text box in to which user can type a line of data. It cannot accept data for more than one line.Text AreaThis control is used for accepting multiple lines of standard text with a scroll bar attached. Similar to the standard VB list box. It allows users to place unformatted text between the <TextTarea> and < TextTarea> tags.Password FieldThis type of text box has a few extra features. It echoes each character of the text that is typed with an asterisk. The control is always cleared if the users leave the page and then use the back button to return to the page. This helps ensure that the data the data is not read or copied accidentally. This control translates to <INPUT type=password>in HTML.OptionThis control places a radio button (also known as option Button in Visual Basic) on the form. All option controls with the same Name property operate as a group.Check boxThis control shows a check box on the DHTML form. Each Checkbox operates independently form any other Check box control on the page. This control translates to using an <INPUT type=checkbox>in HTML.SelectThe select control is used to create a drop-down list box. Visual Basic has separated this control form a standard list box. Even though the two are actually created with the same HTML tag.ImageThe image control shows an image on the page. Normally, this translates to an <IMG> tag, which works well both within or outside of a <FORM> element.HyperlinkThis control shows a hyperlink on the page. This translates to the <A HREF> tag in HTML.FileUploadSince the latest Web specification includes a way to let users upload files to a serve, this feature is supported in DHTML also.

Page 33: VB1

HiddenFieldThis type of field is used to send data to the server without the user having to type it in. This type of data transfer is not secure as anyone who looks at the source of the page can see the data. This translates to an <INPUT type = hidden> tag.ListThis control displays a standard list box, which translates to a <SELECT> control whose HEIGHT attribute is set to a value above 1.Example 15.3Let us create a DHTML page that acts as a start page for any Web site say, for example, IndRail.com. The following steps are followed

Create a new DHTML application from the New Project dialog box and change the Name property of the Project to MyStartPage.

Double-click the designer. The ID property of DHTMLPage 1 is set a htm MyStartPage.

Click in the right pane and type the following text : Start Page (Heading 1)

“ Welcome to the world of Indian Railways. It is a mater of pride that we have been serving the nation for more than 50 years. While celebrating the Golden Jubilee of Indian Independence, we reaffirm our commitment to words serving our customers with great interest and dedication. For more information regarding arrival and departure of trains, reservations and cancellations, inquiries, click the START button”.

Highlight the text and set its ID property to welcome. Type to reserve tickers in advance and double-click the Hyperlink element in

the toolbox. This will add a hyperlink after the text. Type over the world Hyperlink I and change it to clickHere. Set its id as hypReserve.

Double- Click the button element in the Toolbox to add it to the page. Set the ID property to cmdstart and its Value property to click here to start.

When all the elements are added to the page, it should look like fig 15.4. All of the elements’ properties can be seen in the left pane. The elements that are in bold are programmable, since there ID property has been set.

Double- clicks the page to open its code window. Add the following code to the onload ( ) event of the Base window object to

configure the page before it is rendered in the browser. Private sub Basewindow_ onload ( ) With Document . Bgcolor = “pink” . Linkcolor = “ blue” . Vlinkcolor = “blue” . Alinkcolor = “ blue” End with Pwelcome. Style. Color = “violet” End sub

Page 34: VB1

Type the following code in the on click () event of the Cmdstart button and the onclick () event of the hypReserve control respectively.

Private function cmdstart_onclick () As Boolean Basewindow. Navigate “c\My Document\Traindet.xls End function Private function hypReserve_ onclick Boolean Base window. Navigate “c:\DHTML Examples \ Train. Vbp” End function

Multiple Document Interface(MDI)

MDI stands for multiple document interface.A multiple document interface is used for opening many windows at the same time.All the document windows are contained in a parent window,which provides a workspace in a applicationI .Visual Basic applications can have only one MDI form which contains all the child form.A child form is an ordinary form that has it’s child property set to true.Chile forms are displayed with in the internal area of the MDI form at runtime.

Creating an MDI Application

The multiple Document Interface can be designed for document centered application. This application allows the user to open many similar documents at the same time. To create a document- centered application in Visual Basic, we require atleast two forms, the MDI form and a child form. This application is designed similar to the Notepad application in Microsoft Windows. Each time, the user clicks New form the file menu, a new child window is created and displayed.Example 4.1 A new Standard EXE project is opened. The MDI form is inserted by selecting

Add MDI form. The project menu. The project now contains a standard form and a MDI form. The project is saved as mdi.vbp. The form is saved as child frm and the MDI form as parent.frm.

A text Box is added in the standard from. The two forms are designed as per the following specifications.Object Property Setting MDIForm1 Caption Parent FormForm1 Caption Child Form MDI child TrueText1 Multi line True Text (Empty) Left 0 Top 0 Height 2295 Width 3015

Page 35: VB1

Scroll Bars 3-BothMenu items are added to the MDI form as per the following specifications. The designed forms resembled the one shown in fig 4.3

fig 4.3

Caption Name& File mn File…& New mn New…E&xit mn Exit…&Window mn Window…&Cascade mn Cascade…&Tile mn Tile

Fig 4.3

The following code is entered in the mn New_click( ) procedure of the MDIForm. Private sub mn New_click ( ) Dim New Form AS New form1New form. ShowEnd sub

The first Statement in the above procedure declares a variable called New Form as a copy of the child form form1. This implies that, for all-purpose, the form can be referred to as a instance of the form1 with the same properties as form1 that was designed at design time. The second statement in the procedure causes the newly form to pop up. Every time the menu item New is clicked in the MDI form a new form pops up.The following code is entered in the mn Tile_click () procedure of the MDI form.Private sub mnTile_click () MDIForm. Arrange vbTileHorizontalEnd sub

The code in the mnTile_click () procedure uses the Arrange method with vbTile horizontal as the argument to tile the child forms.Fig4.4 represents the forms in tile arrangement. The procedure is executed when the menu item Tile is clicked.

fig 4.4

The following code is entered in the mn Cascade_Click procedure of the MDIForm.Private sub mncascade_Click ()

Page 36: VB1

MDIform1.Arrange vbCascadeEnd subThe code in the mncascade_Click () procedure uses the Arrange method with vbCascade as the argument to cascade the child forms. Fig 4.5 represents the cascaded forms.

Fig 4.5

The following code is entered in the mnExit_click () procedure.Private sub mnExit_click ()EndEnd subWhen the menu item Exit is clicked, the application terminates.

Adjusting the textbox

The text box in the child form can be adjusted to the same size of the child form Foem1.This can be incorporated in resize event. The resize event is fired whenever the size of the form is changed. Therefore, the Form_Resize () procedure is a focal point that is executed whenever the size of the form changes. The following code is entered in the Form_Resize () procedure of the form1 child form.Private sub Form_Resize ()Me. Text1. Width = Me. ScaleHeightMe. Text.Width = Me. ScaleWidthEnd subThe first statement of the above procedure assign the ScaleHeight property of the current form to the Height property of the Textbox and the second statement assigns the scale width of the form to the width of the text box. Hence, the Textbox has the size of the current forms as represented in the fig 4.6.

Fig 4.6

The Me reserved word used in the Form_Resize ( ) procedure is a variable containing the name of tee form where the code is currently executed. The Me keyword in Visual Basic behaves like an implicitly declared variable. For example, in the above program, there may be several instance of the child form in the parent form. When the size of one of these forms is changed the Form_Resize ( ) procedure is executed and automatically updates the Me variable with the instance that was resized.Creating a ToolbarMost of the windows programs include a Toolbar, which is an area containing control to provide quick access to the most commonly used

Page 37: VB1

operations. Toolbars are also called ribbon bar or control in the Toolbar. In order to add a toolbar Item, the MDI form is selected and the picture control in the toolbox is double clicked. Visual Basic responds by displaying a picture box control in the form as shown in fig 4.7.

Fi4.7

The picture box control, which has been drawn in the MDI form, cannot be dragged to another location in the form. Now, the Toolbar are placed in the picturebox control this, the Image icon in the Toolbox is clicked (not double clicked0 and the mouse cursor is placed in the toolbar area. The left mouse button is clicked and moved in the Toolbar. Visual Basic responds by displaying an Image control. The stretch property of the Image control is set to true, which permits the stretching of the image to the desired size. The picture property is set to the respective directory path C:\programFiles\Devstudio\vb\samples\…ico. Another Image control is placed in the Toolbar and the picture property is set to C:\program Files\Devstudio\vb\samples\…. ico. Fig 4.8 represents the MDI form with Toolbar.

fig 4.8

The following code is entered in the image1_Click () procedure.Private sub Image1_Click () MDI Form1 WindowState = 1End SubThe WindowState property setting I in the procedure Image1_Click () displays the procedure.Private Sub Image2_Click () Form1.WindowState = 1End SubThe WindowState property setting I in the procedure Image2_Click () displays the Form 1 in a minimized form. The default WindowState property setting is always Normal (0). This is reflected in the Height, Left, ScaleHeigtht, ScaleWidth, Top, and Width property settings. When these Toolbars are selected at run time, two forms are minimized.Displaying a Status barStatus bars are similar to the toolbars except that the status bar appears at the bottom of an MDI form. The PictureBox can be displayed at the bottom of the Form by setting the Align property to 2-Align Bottom. A status bar may display information about the currently selected object or the state of an application.

Page 38: VB1

Visual Data Manager Add-In

This is one of the Add-Ins provided by Visual Basic. Before the Visual Data Manager, If we have to create an open database connectivity (ODBC) type database, we needed application software such as Access of FoxPro. We know that Visual Basic makes ODBC calls to access databases and their entities. This means that the same function calls are made to any ODBC complaint database. The Visual Data Manager uses the same ODBC calls to create, query and edit databases of any ODBC-complaint format. It allows us to attach database of different formats and supports in-program transactions.Transaction: Once a transaction is started on a database, all the changes may be recalled by using a rollback operation. Similarly changes may be saved permanently by using a commit operation. On using a commit statement, even a rollback will not undo the changes. The Visual data Manager has three buttons to implement the transaction operations. They are Begin Transaction, Rollback current Transaction and commit current Transaction. These transaction buttons are the last buttons on the right of the Visual Data Manager. Transaction ensures that the changes are complete always, i.e. they are either completely saved or completely rolled back.Data Form Generation: Visual Data Manager will automatically create a Visual Basic form based on table or query results and inserts it into our current Visual Basic project. It draws the data bound controls and even labels them. To create a data form automatically with Visual Data Manager, choose the utility Data Form Designer menu item. In the Data Form Designer window that appears, the record source is selected from the Record source combo box. This list contains existing database tables and queries. On selecting from the record source, field names will appear in the Available Fields list box. The arrow buttons are used for including fields in the data form. The Build Form button is used to run the wizard.Query Builder: When we are working with databases, we need a way to extract a subset of information because the database may contain millions of records. Structured query language is the language used to write queries. Query Builder allows us to build a query in a graphical user interface without having to learn SQL.Query Builder can be accessed from the Utility/Query Builder menu item. To build a query in query Builder, select a table name from the Tables list. Then choose a field name from the field Name combo box. Once the field name is selected, we must choose an operator to compare the contents of the table field to with the contents entered in the value combo box. After the field Name, operator and value boxes are field, the fields to be displayed are selected. To view the SQL for the query, the

Page 39: VB1

show button is pressed at the bottom of the window. Then the run button is pressed to run the query.Joining one are or more tables: Sometimes it is necessary to merge tables from two different databases. Visual data manager allows us to attach tables from other databases to the current databases. Once attached, the external database table looks and acts as if it is in our current database. To attach anexternal table to the current database from within Visual Data manager, select the Utility/Attachment menu item and press New in the Attachments window. In their Attachment Name field, a name for the attachment is entered. This can be any external database of the type chosen in the connect string. The type of database we chosen in the connect string should be the same as the type of database we are going to connect to.

MENU EDITORSVisual Basic enables the creation of menus and toolbars with

very little programming. By using the tools included with Visual Basic, one can design and create the menu and toolbar quickly and concentrate on the code that is needed to be added to provide the required functions in the application. This section will illustrate how to add both a simple menu and the related toolbar buttons to a form.

The Menu Editor assists in designing and creating menus. A menu can appear on any or all the forms that are used in the application. However, a menu appears only at the top of the form.

Starting the Menu Editor

(fig)

To start the Menu Editor (figure 13.2) pulls down the Tools menu and choose Menu Editor.

The top half of the Editor, called the Menu Control Properties area, lets the user to set the properties for a given menu item and the overall menu bar.

Page 40: VB1

The large empty area at the bottom of the editor is known as Menu control list box and displays the current menu structure as it is created. Although there are several properties that can be modified for a menu, there are only two items that must be entered each time.

Caption - The menu item name that the user wants to see on the menu bar.

Name - The control name that is assigned to each menu that will be used in the program code.

Fig. 13.1 using both standard and customized menu groupings in an application.

(fig)

Fig 13.2 Creating menu using the Menu Editor.

(fig)

Adding the Menus

After knowing the menus that are to be added, the user can start creating them. Following steps are used for creating the various menus shown in table 13.1.

1. The form is selected.2. The menu editor is obtained using the procedure explained

in 13.2.3. In the caption text box the text for the first menu (File) is

typed. The menu title text is displayed in the menu control list box.4. In the name text box the name that will be used to refer

the menu control in the code is typed.5. Next is chosen to create another menu control.6. Repeat the steps 1 to 5 till all the seven menus appear in

the menu control list box.If the OK button is pressed, the seven items that are added

would be displayed as a top-level option, as shown in figure 13.3.

Caption NameFile mnuFileOpen mnuFile OpenSave mnuFileSaveExit mnuFileExitEdit mnuEditCut mnuEditCut

Page 41: VB1

Copy mnuEditCopyTable the items of the Menu

Displaying every item of the menu at the top levelTo modify this, the items that are contained within a group must

be specified. To do this, the item of the menu in the list at the bottom of the editor is selected and the right arrow on the editor is clicked. This will indent that item of the menu, signifying that it is a child of the item above it that is not indented as shown in figure 13.4. Figure 13.5 shows the same items of the menu with the appropriate indentations.Appropriate indentations.

Fig 13.4 The Menu Editor window.

(fig)

Fig 13.5 The Final menu.

(fig)

Inserting the Program Code

After the Menu Editor is closed, the menu is displayed on the form. The last step in the process of using a menu is to add the code to the menu item's Click event rountine that executes the related process. This can be done using a call to another rountine, or the program code can be directly placed in the Click rountine. If now a click is made on the items of the menu that are created, a Click rountine for a given menu is displayed in Design mode in the code editor asd shown in figure 13.6. At this point the required code can be added.

Fig 13.6 adding the required program code13.5 Using ToolbarOnce the menu is added to the form, adding a toolbar to the

application is easier. The hardest part of adding a toolbar is actually including it on the form and inserting the required buttons and images. Once again, Visual Basic provides a tool that assists in this process. By adding the Application Wizard in the Add-Ins menu one can get a Toolbar Wizard that helps through the various steps needed to add a toolbar.Check Boxes and Option Buttons

A check box offers an option for the user. It might appear by itself as shown in figure

Page 42: VB1

(fig)

In that figure if the check box is clicked there will bee a display of checkmark. If it is again clicked, the check mark wills disappear. If the check mark is present the feature denoted by the caption of that box is assumed to present; if the check mark is not present, the feature is assumed to absent. Sometimes in a form a number of check boxes are grouped together as shown in figure. The check box, when clicked, will display a check mark, meaning that it is selected and the check mark will go away if the user clicks the check box again.

As seen in figure many of the most common Window’s applications use check boxes to ask simple Yes/No questions.

Fig 14.1 Using the check box to ask a simple question.Fig 14.2 Using the check box to allow multiple selections by the

user.The check box property that determines the current state of the

check box is the Value property. If the Value property is True, the check box is selected and the check mark will appear; but if the Value is False, the check box is not selected and the check box is empty.

Changing the Appearance of a Standard Check Box

When using the standard check box style, there are several properties that can be modified to change its appearance.* Changing the font properties for the caption* Modify both the ForeColor and the BackColor.* Create either a flat or 3D look with the Appearance property.* Choose the side of the box where the caption is to be displayed.* The standard check box can be disabled by setting the Enabled Property of the control to false.

Page 43: VB1

Disabled Checkbox - This is the appearance of the disabled checkbox.

Using these properties allows customizing the look of any form that uses check boxes.

Working with Option Buttons

Besides using check boxes to interact with the user for the selection of options, Visual Basic also comes with the Option Button Control. This control lets the user select from one of several choices. However, unlike the check box, the user can select only one option at a time. This type of interaction is the same as a multiple-choice test. Figure 14.5 shows four option buttons with only one selected. The way this control works, if the user selects another option button, the one that was selected will be dislocated, and the new button will be selected.Fig 14.5 selecting one choice from a group.

Visual Basic automatically takes care of deselecting the first button and selecting the new one.WORKING WITH FILES AND DATABASES

Introduction to the File System Object Object Model

A new feature for Visual Basic is the File System Object (FSO) object model, which provides an object-based tool for working with folders and files. This allows one to use the familiar object method syntax with a rich set of properties, methods, and events to process folders and files, in addition to using the traditional Visual Basic statements and commands.

The FSO object model gives the Visual Basic applications the ability to create, alter, move, and delete folders, or to detect if particular folders exist, and if so, where. It also enables the user to gain information about folders, such as their names, the date they were created or last modified, and so forth.

The FSO object model makes processing files much easier as well. When processing files, the primary goal would be to store data in a space-and resource-efficient, easy-to-access format. The user also need to be able to create files, insert and change the data, and output (read) the data. While data can be easily stored in a database, such as SQL, it adds a significant amount of overhead to the application. For many reasons, one may not want to have such an overhead, or the data access requirements may not require all the extra features associated with a full-featured database. In thiscase, storing the data in a binary or text file is the most efficient solution.

Page 44: VB1

The FSO object model, which is contained in the Scripting type library (Screen. DII), supports text file creation and manipulation through the Text Stream object. It does not as yet, however, support the creation or manipulation of binary files. Programming in the FSO Object Model

Programming in the FSO object model involves three main tasks:* Using the Create Object method, or dimension a variable

as a File System Object object to create a File System Object object.* Using the appropriate method on the newly created object.* Accessing the object's properties.The FSO object model is contained in a type library called

Scripting, which is located in the file Scrrun.DII. If you don't already have a reference to it, check "Microsoft Scripting Runtime" in the References dialog available from the Project menu. You can then use the Objects, collection, properties, methods and events, as well as its constants.20.21 Creating a FileSystemObject Object

The first step is to create a FileSystemObject object to work with. You can do this in two ways:

* Dimension a variable as type FileSystemObject object:Dim Fso as New FileSysteObject* Use the CreateObject method to create a FileSystemObject

object.Set Fso = CreateObjecst ("Scripting. FileSystemObject")In the above syntax, Scripting is the name of the type library, and FileSystemObject is the name of the object, which you want to create an instance of.Note: The first method works only in Visual Basic, while the second method works either in Visual Basic or VBScript.

Using the Appropriate Method

The next step is to use the appropriate method of the FileSystemObject object. For example, if one wants to create a new object, either CreaterFolder or Create TextFile can be used. (The FSO object model doesn't support the creation or deletion of drives.)

If it is desired to delete objects, one can use the DeleteFile and DeleteFolder methods of the FileSystemObject object, or the Delete method of the File and Folder objects.

Using the appropriate methods, it is also possible to copy and move files and folders.

Note that some functionality in the FileSystemObject object model is redunNote that some functionality in the FileSystemObject objects model is redundant. For example, one can copy a file using

Page 45: VB1

either the CopyFile method of the FileSystemObject object, or one can use the Copy method of the File object. The methods work the same. Both exist to give maximum programming flexibility to the users.20.2.3 Accessing Existing Drives, Files and Folders

To gain access to an existing drive, file, or folder, the appropriate "get" method of the FileSystem Object object should be used:

* GetDrive* GetFolder"* GetFile

For example:Dim Fso as New FileSystemObject, fill As FileSet fil = Fso. GetFile ("c:/test.txt")

Note, however, that one need not use the "get" methods for newly-created objects, since the "create" functions already return a handle to the newly-created object. For example, if a new folder is created using the CreateFolder method, then there is no need to use the GetFolder method to access its properties, such as Name, Path, Size, and so forth. Just a variable is set to the CreateFolder function to gain a handle to the newly-created folder, then access its properties, methods, and events. The following example code illustrates the above point.Private sub Create Folder ()

Dim Fso as New File SystemObject, folder As Folder Set fldr = Fso. CreateFolder ("C:\MyTest")MsgBox "Created folder: " fldr.Name

End Sub

Accessing the Object's Properties

Once a handle to an object is available, its properties can be easily accessed. Example, to obtain the name of a particular folder, first an instance of the objects is created. Then a handler to it is obtained with the appropriate method (in his case, the GetFolder method, since the folder already exists):Set fldr = Fso. GetFolder ("C:\")Now that a handle to a Folder object is available, its Name property can be easily checked using the following code:Debug. Print” Folder name is”; flder. NameIf you want to find out the last time a five was modified, use the following syntax:Dim Fso as New FileSystemObject, fil As FileSet fil = Fso. GetFile ("C\detlog. txt") ' Get a File object to query.Debug. Print " File last modified: " fil. Debug. Print "File last modified: "; fil. Detelast Modified ' print info.

One can work with files in Visual Basic by using the new object-oriented FSO objects such as Copy, Delete, Move, and Open As

Page 46: VB1

TextStream, among others, or by using the older existing functions such as Open, Close, FileCopy, GetAttr, and so forth. The files can be moved, copied, or deleted regardless of there regardless of their file type.There are two major categories of file manipulation:

Creating, adding, or removing data and reading files.Moving, Copying, and deleting files.

Creating Files with File System Objects

There are three ways to create a sequential text file (sometimes referred to as a "text stream"). One way is to use the create TextFile method.To create an empty text file the following code is used:Dim Fso As New FileSystemObject, fil As File Set fil = Fso CreateTextFile("C\testfile.txt", True)Another way is to use either the open TextFile method of the FileSystemObject object with the ForWritting flag set:Dim Fso As New FileSystemObject, Ts As New TextStream set Ts = Fso. OpenTextFile ("C\test. Txt", ForWriting)Or the OpenAs TextStream method can be used with the ForWritting flag set:Or the OpenAs TextStream method can be used with the ForWritting flag set:Dim Fso as New FileSystemObject, fil As File, Ts As TextStreamSet Fso = Create object ("Scripting. FileSystemObject")Fso. CreateTextFile ("test1. Txt")Set fil = Fso. GetFile ("test1. Txt")Set Ts = fil. OpenAsRextStream ( ForWriting) Adding Data to the File with file System objects

Once the text file is created, data can bar added to it in three steps:1. Open the text file for the writing of data.2. Write the data.3. Close the file.

To open the file, either of the following Two methods can be used:1. The Open as TextStream method of the file objects2. The open TextFile method of the FileSystemObjects

Objects.To write data to the open text file, either the write or writeline methods of the RextStream objects can be used. The only difference between write and Writeline is that write line adds newline characters to the end of the specified string. If a newline is to be added to the text file, the write BlankLines method can be used. To close an open file, the close method of the TextStream object can be used. Here's an example of

Page 47: VB1

how to open a file, using all the three write methods to add data to the file, then close the file.Sub Create _ File ()

Dim Fso, txtfileSet Fso =

Create object ("Scripting. File SystemObject")Set txtfile =

Fso. CreateTextFile ("C\testfile. Txt", True)Txtfile. Write ("This is a test. ") ' Write a line.Write a line with a newline character.Txtfile. Writeline ("Testing 1,2,3.")' Write three newline characters to the file.Txtfile. WriteBlankLines(3)Txtfile. Close

End sub Reading files with file system objectsTo read data from a text file, the Read line, or methods of the TextStream objects are is used. This is illustrated in table

Task MethodRead a specified number of characters from a file ReadRead an entire line (up to, but not including, theNew line character) RedlineRead the entire contents of a text file ReadAll

Table Reading from a fileIf it is desired to skip to a particular portion, then the Skip or Skipline method is used.The resulting text of the read methods in a string which can be displayed in a control, parsed by string operators (such as Left, Right, and Mid), concatenated and so forth.Note: The VB newline constant contains a character or characters (depending on the operating system) to advance the cursor to the beginning of the next line (carriage return/linefeed). It should also be noted that the ends of some strings may have such nonprinting characters.ExampleSub Read_ Files ()

Dim Fso As New FileSystemObjects, txtfile, - fill As File, Ts as TextStream

Set txtfile =Fso. CreateTextFile ("C\testfile. Txt’, True) Msg. Box "Writing file"

' Write a line.

Page 48: VB1

' Write a line.Set txt file =

Fso. CreateTextFile ("C:\testfile. Txt", True)MsgBox "Writing file"' Write a line.Set fill = Fso. GetFile ("C:\tstfile. Txt")Set Ts = fill. OpenAsTextStream (ForWriting)Ts. write: Hello world"Ts close' Read the contents of the file.S Ts = fill. OpenTextStream (ForReading)S = Ts. RedlineMsgBox sTs. close

End sub Moving, copying, and deleting files

The FSO objects model has two methods each for moving, copying, and deleting files as shown in table

Task MethodMove a file File. Move or

Files System Objects. Move fileCopy a file File.Copyor

File SystemObjects. Copy FileDelete a file File.Delete or

FileSystemObject.Delete File

Table 20.2 Moving, copying and deleting filesExampleThis example creates a text file in the root directory of drive C, writes some information to it, moves it to a directory called\tmp, makes a copy of it in a directory called \tmp, then deletes the copies from the copies from both directories.To run this example, it should be ensured that the directory named tmp and reap are available in the root directory of drive C.Sub Mainp_Files ()

Dim Fso as New FileSystemObject, txtfile, fill,Fil2

Set txtfile =Fso. CreateTextFile ("C:\ testify. Txt", True)

Page 49: VB1

MsgBox "Writing file"' Write a line.Txtfile. Write (" This is a test.")' Close the file to writing.Txtfile. CloseMsgBox "Moving file to C:\tmp"' Get a handle to the file in root of c:\.Set fill = Fso. GetFile ("C:\testfile. Txt")' Move the file to \tmp directory.Fill. Move ("c:\tmp\ testfile.txt")MsgBox "Copying file to c:\temp"' Copy the file to temp.Fill. Copy ("c:\temp\testfile.txt") MsgBox "Deleting files"' Get handles to files' current location.Set fill = Fso. GetFile ("C:\tmp\testfile.txt')Set fil2 = Fso. GetFile (C:\temp\testfile.txt")' Delete the filesFlii. DeleteFlii. DeleteFil2. DeleteMsgBox "All done!"End subWorking with Files using older file I/O Statements

The use of File System Objects is recommended to create text files. But this information is provided in case one needs to use the older text file creation methods. Using Sequential File Access

Sequential access works best when it is desired to process files consisting only for text, such as the files created with a typical text editor - that is, files in which data is not divided into a series of records. Sequential access may not be well suited for storing long series of numbers, because each number is stored as a character string. A four-digit number would require 4 bytes of storage instead of the 2 bytes it requires to store the same number as an integer.20.3.1 Using Sequential File Access Opening Files for Sequential AccessWhen a file is opened for sequential access, it is opened to perform one of the following operations:

Input Characters from a file (Input)Output characters to a file 9Output)Append characters to a file (Append)

To open a file for sequential access, the following syntax is used for the open statement:Open pathname for (Input / output / Append) As filenumber (ken = buffersize)

Page 50: VB1

When a sequential file is opened for input, the file must already exist; otherwise, an error occurs. When an attempt is made to open a nonexistent file for Output or Append, however, the open statement creates the file first and then opens it.The optional Len argument specifies the number of characters to buffer when copying data between the file and your program.For instance the statement to open a text file might lookalike this: Open " Testfile.txt' As #1The above line will open a file named testify .txt and assigned the file Number1 to it.Example:

1. Open an new standard EXE project and add a textbox and Command Button to the form. The Multilane property of the textbox should be set to True.

2. Save the Form as SEQ.frm and the project file as SEQ.vbp.3. Add the following code in the command _ Click ()

procedure.Private sub command _ click ()Filename = freefileOpen: C:\sample. Txt" For output as filenamePrint #filenum, Text1. TextClose filenum

End sub4. Run the application by clicking F5 and enter some text in

the textbox. Now Click the CommandButton.5. The entered text appears in the file sample. Txtfile. This

can be viewed by opening the file in the notepad and terminating the application.

After opening a file for an Input, Output, or Append operation, it must be closed using the Close statement, before reopening it for another type of operation.20.3.1.2. Opening a Sequential Access File for Append

When a file is opened for append, it is not erased if the file already exists. Intend the subsequent output commands append new lines to the opened file.Example:

Let us assume that the file sample. Taxt already exists and it contains the following names.

1. Rajaram2. Sarojini

2. Sarojini3. PatelOne more CommandButton control namely Command2 is added

to the SEQ. frm.The following code will append one more name to the list if the

Command2 Button is clicked.

Page 51: VB1

Private Sub Command2_Click ()Filenum = freefileOpen "C:/sample. Txt" For Append As filenumPrint #filenum, "Thilagar"Close filemi,End Sub

Opening a Sequential Access File for InputIn order to open the sequential file for input, the Input statement

can be used. Once the file is opened for Input, the Input () function can be used to read the entire contents of the file into the textbox or a string variable.Example:

Create one more CommandButton control namely Command3 and a textbox control namely Text2 and add it to the Form SEQ.FRM. The multilane property of the textbox should be set to True.The following code is entered in the Command3_Click () Procedure.

Private Sub Command3_Click ()Filenum = freefileOpen "C:/sample.txt" For Input as filenumFilelength = LOF (1)Text1. Text = FilelengthText2. Text = Input (LOF (filenum), filenum)Close filenumEnd SubOnce the code is executed and the CommandButton is clicked,

the Text displays the file length and the Text2 displays the contents of the file. The Input () function takes two parameters. The first parameter specifies the number of bytes to be read from the file and the second parameter specifies the file number. The LOF () function returns the length of the file in bytes.

If you want to edit a file, first read its contents to program variables, then change the variables, and finally, write the variable back to the file. The following sections discuss how to edit records opened for sequential access.Using Random File Access

The File System Object model does not provide random file creation or access methods. If you need to create or read random files, this information will help you do so.

The bytes in random-access files form identical records, each contain one or more fields. A record with one field corresponds to any standard type, such as an integer or fixed-length string. A record with more than one field correspond to a user-defined type. For example, the Worker Type defined below creates 19-byte records that consist of three fields:Type Worker

LastName As String * 10

Page 52: VB1

Title As String * 7Rank As String * 2

End Type Declaring Variables

Before your application opens a file for random access, it should declare all variables required to handle data from the file. This includes user-defined types, which correspond to records in the file, as well as standard types for other variables that hold data related to processing a file opened for random access.Ables that hold data related to processing a file opened for random access. Defining Record Types

Before opening a file for random access, define a type that corresponds to the records the file does or will contain. For example, and Employee Records file could declare a user-defined data type called person as follows:Type Person As Integer

IDMonthly Salary As CurrencyFirstName As String * 15LastName As String * 15Title Name As String * 15ReviewComments As String * 150

End Type Declaring Field Variables in a Type Definition

Because all records in a random-access file must have the same length, it is often useful for string elements in a user-defined type to have a fixed length, as shown in the Person type declaration above, where, for instance, FirstName and LastName have a fixed length of 15 characters.

If the actual string contains fewer characters than the fixed length of the string element to which it is written, Visual Basic fills the trailing spaces in the record with blanks (character code 32). Also, if the string is longer than the field size, it is truncated. If you use variable-length strings, the total size of any record with Put or retrieved with Get must not exceed the record length specified in the Open statement's Len clause. Declaring other variablesAfter defining a type that corresponding to a typical record, declare any other variables that your application needs to process a file opened for random access. For example:' Record variable.Public Employee As record.' Tracks the current record.Public position as long' The number of the last record in the file.

Page 53: VB1

Public LastRecorded As long20.3.2.5 Opening Files for Random AccessTo open a file for random access, use the following syntax for the open statement:Open pathname [For Random] As filenumber Len = reclength

Because Random is the default access type, the For Random keywords are optional.

The expression Len=recength specifies the size of each record in bytes. Note that every string variable in Visual Basic stores a Unicode string and that you must specify the byte length of that Unicode string. If reclength is less than the actual length of the record written to the file, an error is generated. If reclength isgreater than the actual length of the record, the record is written, although some disk space may be wasted.

You could use the following code to open a file:Dim filenum As Integer, reclength As Long, Employee as Person' Calculate the length of each record.RecLength = LenB (Employee)' Get the next available file number.Filenum = freefile' Open the new file with the Open statement.Open "MYFILE.FIL" For Random As filenum Len = RecLength

20.3.2.6 Editing Files Opened for Random AccessIf you want to edit a random access file, first read records from

the file into program variables, then change the values in the variables, and finally, writed the variables back into the file. The following sections discuss how to edit files opened for random access.20.3.2.7 Reading Records into Variables

Use the Get statement to copy records into variables. For instance, to copy a record from the Employee Records file into the Employee variable, you could use the following code:The following code:Get filenum, Position, Employee

In this line of code, filenum contains the number that the Open statement used to open the file; Position contains the record number of the record copy; and Employee, declared as user- defined type person, receives the contents of the20.3.2.8 Writing Variables to RecordsUse the Put statement to add or replace records in to files opened for random access.20.3.2.9 Replacing Records

To replace records, use a Put statement, specifying the position of the record you want to replace; for example:Put #filenum, Position, Employee

This code will replace the record number specified by Position, with the data in the Employee variable.

Page 54: VB1

20.3.2.10 Adding RecordsTo add new records to the end of a file opened for random

access, use the Put statement shown in the preceding code fragment. Set the value of the Position variable equal to one more than the number of records in the file. For example, to add a record to a file that contains five records, set position equal to 6.The following statement adds a record to the end of the file:LastRecord = LastRecord + 1Put #filenum, LastRecord, Employee20.3.2.11 Deleting Records

You could delete a record by clearing its fields, but the record would still exist in the file. Usually you don't want empty records in your file, because they waste space and interfere with sequential operations. It is better to copy the remaining record to a new file, and then delete the old file.To remove a deleted record in a random-access file the following steps are used:

1. Create a new file.2. Copy all the valid records from the original file into the new

file.3. Close the original file and use the Kill statement to delete

it.4. Use the Name statement to rename the new file with the

name of the original file.Fore More Information: For additional information on random file access, see "Open Statement".20.3.3. Using Binary File Access

The File System Object model does not provide binary file creation or access methods. If you need to create or read binary files, this information will help you do so.

Binary accesses gives you complete control over a file, because the bytes in the file can represent anything. For example, you can conserve disk space by building variable-length records. Use binary access when it is important to keep file size small.Note: When writing binary data to a file, use a variable that is an array of the Byte data type, instead of a String variable. Strings are assumed to contain characters, and binary data may not be properly stored in String variables.20.3.3.1 Opening a File for Binary Access

To open a file for binary access, use the following syntax for the Open statement:Open pathname For Binary as filenumber

As you can see, Open for binary access differs from Open for random access in that Len = reclength is not specified. If you include a record length in a binary-access Open statement, it is ignored.20.3.3.2 Storing Information in Variable-Length Fields

Page 55: VB1

To best appreciate binary access, consider a hypothetical Employee Records file. This file uses fixed-length records and fields to store information about employees.Type Person

ID As IntegerMonthlySalary As CurrencyLastReviewDate As LongFirstName As String * 15LastName As String * 15Title As String * 15ReviewComments As String * 150

End TypeRegardless of the actual contents of the fields, every record in that file takes 209 bytes.

You can minimize the use of disk space by using binary access. Because this doesn't require fixed-length fields, the type declaration can omit the string length parameters.Type Person

ID As IntegerMonthlySalary As CurrencyLastReviewDate As LongFirstName As StringLastName As StringTitle As StringReviewComments As String

End TypePublic Empl As Person' Defines a record.

Each employee record in the Employee Records file now stores only the exact number of bytes required because the fields are variable-length. The drawback to binary input/output with variable-length fields is that you can't access records randomly-you must access records sequentially to learn the length of each record. You can seek directly to a specified byte position in a file, but there is not direct way to know which record is at which byte position if the records are of variable length.

Page 56: VB1