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

Unit 2

Visual Basic is an event-driven programming language ideal for creating graphical user interface applications for Microsoft Windows. It uses a drag-and-drop interface that allows programmers to visually design forms and applications. Visual Basic has evolved from the BASIC language and now includes hundreds of statements, functions, and keywords to support developing Windows applications. It provides an integrated development environment for rapid application development.

Uploaded by

Jit Agg
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
106 views

Unit 2

Visual Basic is an event-driven programming language ideal for creating graphical user interface applications for Microsoft Windows. It uses a drag-and-drop interface that allows programmers to visually design forms and applications. Visual Basic has evolved from the BASIC language and now includes hundreds of statements, functions, and keywords to support developing Windows applications. It provides an integrated development environment for rapid application development.

Uploaded by

Jit Agg
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 40

Visual Programming UNIT II

2.0 Introduction
Visual Basic is an ideal programming language. It is called event-driven programming as the application does not determine the flow but the event caused by the user determines the flow of the application. Visual Basic is the easiest and fastest way to create applications for Microsoft Windows. The Visual part refers to the method used to create the graphical user interface (GUI). Rather than writing numerous lines of code to describe the appearance and location of interface elements, one can simply drag and drop pre-built objects into place on screen. The Basic part refers to BASIC language, a language used by more programmers than any other language in the history of computing. Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions, and keywords many of which relate directly to the Windows GUI Visual Basic, tool for developing Graphics User Interface applications is a product of Microsoft Corporation. It is simple, user-friendly, powerful and easy-to-learn. It has an excellent development environment to create the user interface. It falls in to the class known Rapid Application Development or RAD tools. It is object based with set of debugging tools. All the components such as Forms, Controls and other visible parts of the programs are objects. In addition there are hidden objects, which is present in the computer memory. It provides gradual transition from procedural to event-driven programming. Once the event processor detects an event, the code corresponding to that event is executed. Program control is then returned to the event processor. Event Processor Event Processor

Basic Code

Basic Code

Event Procedures

2.1 Objective
Supports 32 bit code. Full set of objects to design the application. Full array of mathematical, string handling and graphics functions. Can handle fixed, dynamic variable and control array. Sequential and random access file support. Powerful database enhancements.

Page 47

Visual Programming
Supports ActiveX controls and Windows Application Programming Interface. Supports Single Document and Multiple Document Interface. Supports Client/Server architecture. Additional Internet capabilities Enhanced Data Report Designer.

2.2 Content
2.2.1 Goals of user Interface design Visual basic 6.0 provides with a number of Custom Controls, some are data bound controls and some of them are Active X Controls. Since a majority of these controls happen to be Active X controls, these custom controls are also called as Active X Controls. The Integrated Development Environment is where you do your programming in Visual Basic. The Visual Basic IDE operates in three distinct modes: the Design Mode used to build applications, the Run Mode used to run the application and the Debug mode used to debug the application. The tools found in the application are the palettes for creating the application. Each provides a specific function for working with your application. The Visual Basic IDE consists of the following components: Form Window Code Window Menu Bar Tool Bar Tool Box Project Explorer Properties Window Form Layout Window

Page 48

Visual Programming
Visual Basic 6.0 Integrated Development Environment Form Window The center window in the IDE is the form designer window. This is where you will build the interface to your application. You add components, graphics and pictures to a form to create the look you want. Each form in your application had its own form designer window.

A Sample Form Window Menu Bar The menu bar contains dropdown menus from which you control the operations of the Visual Basic environment. Thirteen menus are available each focusing on specific purposes. Table 3.1 provides an overview of each. Menu File Description

Provides basic project management such as starting projects, saving projects, compiling projects and printing project code. Edit Provides the standard cut, copy and paste options; but, depending on the context, also provides searching, database editing and much more. View Controls the interface of the IDE. You can show and hide all of the development windows, debugging windows, database tools and various toolbars. Project Lets you manage your project. You can add forms, modules, controls, references, designers and set your project properties such as name, compile settings etc. Format Provides tools for formatting your user interfaces. Alignment options for controls, ordering of controls and spacing are provided. Debug Provides different debug mode settings and tools for debugging your project code. Run Gives you the option for running, breaking and stopping your application. Query Lets you work with database queries in your application. Diagram Goes along with the query menu. It is used for creating database diagrams of data you are working with in your project. You can include annotations and shoe relationships.

Page 49

Visual Programming
Tools Provides code creation tools, SourceSafe management tools and options for customizing the IDE. Add-Ins Provides functionality you can add to your application via custom-built add-ins. Examples include source control, Windows API Viewer, tools for building classes and much more. Window Provides window management tools for the IDE. Help Links to MSDN for providing Visual Basic documentation and help. Visual Basic Menus Toolbars There are six basic toolbars, including the menu, standard, edit, debug, form editor and shortcut menus. In most cases the toolbar buttons provide direct links to the menu options. You can extensively customize the toolbar by selecting the Toolbars options on the View menu. Toolbox The toolbox provides a set of tools like label, text box, command button and others that you use at design time to place controls on a form. The buttons in the toolbox are called controls. In addition to the default layout, you can create your own layouts by selecting the Add tab when you right-click on the toolbox. The multiple tabs allow you to logically organize your components.

Titlebar

Menubar

Toolbar

Start Menu editor Add form Add project Break Save project

Stop Project Explorer

Object Browser Form Layout

Form dimensions

Toolbox

Open project

Properties window

The Toolbar in Visual Basic

Page 50

Visual Programming
Project Explorer Project explorer lists the forms and modules in your current project in tree structure. A project is the collection of all the files you have created to build your application. From this window you can add and delete files in your project. A project file (.VBP) contains the list of names and disk locations of all files needed to the project. A project has at least one form.

A Project Explorer Window Properties Window The Properties window is where you set properties for your forms and components at design time. A property is a characteristic of on object, such as size, caption or color. The help window is part of the Properties window. If you select a property, help is displayed regarding that property.

A Sample Properties WindowForm Layout Window

Page 51

Visual Programming
The form layout allows you to position the forms in your application using a small graphical representation of your form on the screen during design time. This way you can define where on the screen your form will be launched when you run your program.

A Form Layout Window Debugging Three key windows are used in debugging applications. Fig 3.7 shows the Visual Basic IDE with the Immediate window, Locals window and Watches window. The Immediate window automatically opens when your application is in the break mode. You can type or paste a line of code and press ENTER to run it. This allows you to test different code options and see the results easily. The Watches window allows you to watch the value of the variables in your application that you place in the window. You can update the values of the variables at run time during a break to see the effect. The Locals window automatically displays all the declared variables in the current procedure and their values. This includes properties for any components, forms and so on

. The Visual Basic IDE with the Immediate window, Locals window and Watches window

Page 52

Visual Programming
2.2.2 Three Modules A key development tool is the use of code-encapsulating tools called modules. A project consists of Form modules, Standard modules and Class modules. Form modules (.FRM file name extension) can contain textual description of the form, its controls and property settings. They include form-level declarations of constants, variables, procedures that handle events and general procedures. Standard modules (.BAS file name extension) are containers for procedures and declarations commonly accessed by other modules within the application. They can contain global or module-level declarations of variables, constants, types, external procedures, and global procedures. The code you write in a standard module is not necessarily tied to a particular application. A standard module can be reused in many different applications if forms and controls are referenced by names. Class module (.CLS file name extension) are the foundation of object-oriented programming in Visual Basic. You can write code in the class module to create new objects. These new objects can include your own customized properties and methods. Actually, forms are just class modules that can have controls placed on them and can display from windows. Visual Interface design

2.2.3

Visual Data Manager The Visual Data Manager is a tool that is used to design and do different operations on databases. The Add-Ins of the Menu Bar in the Visual Basic contains the Visual Data Manager option. Once the Visual Data Manager is selected, the VisData screen is seen with 4 menu options and some icons, each of which has separate function. The Visual Data Manager is provided with some databases by default such as BIBLIO, NWIND etc. User Interface Design User needs : The user's conceptual model of a system is a mental image that each user subconsciously forms as he or she interacts with the system. People create mental models by putting together sets of perceived rules and patterns in a way that explains a situation. A typical person cannot draw or describe his or her mental models and in many situations the person is not even aware that these mental models exist. A mental model does not necessarily reflect a situation and its components accurately. Still, a mental model can help people predict what will happen next in a given situation, and it serves as a framework for analysis, understanding, and decision-making. The user's conceptual model is based on each user's expectations and understanding of what a system provides in terms of functions and objects, how the system responds when

Page 53

Visual Programming
the user interacts with it, and the goals the user wants to accomplish during that interaction. These expectations, understandings, and goals are influenced by the user's experiences, including interaction with other systems, such as typewriters, calculators, and video games. Because each user's conceptual model is influenced by different experiences, no two conceptual models are likely to be the same. Each user looks at a user interface from a slightly different perspective. The problem for the interface designer is to design an interface that users find predictable and intuitive when each user is approaching the interface from a different perspective. To come as close as possible to matching users' conceptual models, designers should find out as much as they can about users' skills, motivations, the tasks they perform, and their expectations. This process involves: 1. using resources such as task analysis, surveys, customer visits, and user requirements lists 2. incorporating information that users provide into the user interface design 3. conducting usability tests This is an iterative process that may require many cycles. As the design progresses, users may identify aspects of the interface that are difficult to learn, that are counterproductive, or aspects they simply do not like. Through interaction with the user interface, users' conceptual models may be expanded, which in turn may cause them to realize new requirements that they had not thought of before. As users provide this level of information to the designer, the picture of their conceptual models will become clearer. Conceptual models of an object-oriented user interface consist of the objects, properties, behaviors, and relationships of those objects, that are involved in the user's interaction with the system. When users first interact with a new interface, they are likely to attempt to understand its operation in terms of roles and relationships they already understand. In other words, we each carry with us a current conceptual model. Where existing models lead to correct expectations, the model is reinforced and the user will feel the interface is intuitive. When results are not as expected, the user may rationalize by inventing new roles and relationships in their model, in order to explain observed behavior. If the user-supplied extensions are accurate, they will be reinforced through interaction with similar aspects in different parts of the system. Otherwise, they are likely to cause confusion. Sometimes users develop superstitions about the interface. These superstitions result from incorrect rationalizations about how and why the interface appears to behave as it does. Superstitions are likely to cause unexpected results in response to the user's actions and further contradict the user's intuition. This can lead to a breakdown in

Page 54

Visual Programming
understanding and trust by the user. The use of metaphors and consistency by designers can help user's correct and extend their conceptual models. A new interface should resemble something familiar to help users get started, then allow them to explore new concepts. It is often said that a characteristic of a good user interface is that it is intuitive. Perhaps when used in this sense intuition can best be characterized as a good match between the user's conceptual model and the designer's model. By using metaphors, designers can take advantage of users' experience and allow a user to rely on intuition while expanding the user's conceptual model to take advantage of new capabilities provided by the interface. Interfaces that use metaphors and allow users to safely explore the computerized environment are popular for this reason. 2.2.4 File System Let us see the basic file type operations using built in Visual Basic functions. These techniques are considered old style by programmers familiar with Object Oriented programming who prefer to use the File System Object (FSO). We can categorize these operations in two ways: operations on files and operations on directories, or the newer term, folders. a. Copying Files When you copy a file you keep the existing file, and make a copy of the file with a new name. Visual Basic provides a statement for this called FileCopy. Here is the syntax for the FileCopy statement FileCopy source, destination where source is the name of the file to copy, and destination is the name of the copied file. The Current Drive and Current Directory As it turns out, Visual Basic has a function that can be used to determine the current directory called the CurDir function Does a file exist? There is no confirmation that the copy was successful, but you can determine if a file exists by using the Visual Basic Dir$ function. The Dir$ function requires just a single argument representing the file name (as was the case with the CopyFile statement, you can specify just the file name or the full path name). If the file is found, then Dir$ returns the file name (not the full path). If the file is not found,

Page 55

Visual Programming
then Dir$ returns an empty string. Let's see how we can use the Dir$ function to determine if a file exists before we copy it. Private Sub Command1_Click() Dim retval As String retval = Dir$("c:\vbfiles\b.txt") If retval = "b.txt" Then MsgBox "b.txt exists--no need to copy it..." Else FileCopy "c:\vbfiles\a.txt", "c:\vbfiles\b.txt" End If End Sub If we now run the program, and click on the command button

We receive a message saying that the file already exists---Dir$ has done its job. By the way, you will discover that there is a Dir function as well---Dir returns a variant return value and Dir$ returns a string. b. Renaming Files Renaming files is similar to copying them--this time we use the Visual Basic Name statement. Here is the syntax. Syntax Name oldpathname As newpathname c. Deleting Files The final file operation is that of deleting a file. Visual Basic provides us with the Kill statement, which will delete a file (and dangerously, a wildcard selection of files) of our choosing. Here's the syntax Syntax

Page 56

Visual Programming
Kill pathname d. Moving Files There is no explicit Visual Basic statement to move a file. To simulate a move of a file, all we need to do is combine the FileCopy and Kill statements that we've already seen. For instance, to move the file a.txt from C:\VBFILES to C:\VBILES\CHINA, we can execute this code Private Sub Command1_Click() FileCopy "c:\vbfiles\a.txt", "c:\vbfiles\china\a.txt" Kill "c:\vbfiles\a.txt" End Sub Again, do not expect any confirmation messages---only errors if the files you reference do not exist. That's it for Visual Basic (Primitive) actions that we can take against files 2.2.5 Storage and retrieval system

The storage and retrieval system in Visual Basic programming has both older concepts and new object oriented techniques. Storage system Sequential file access In the older concepts the file can be opened as a sequential file with the help of open statement Open filename for [Input/ output/ Append] as # file number Information are written into the file after open statement using write or print statement. The file has to be closed. This system is known as sequential file accessing. Random file access In this file access system the records can be accessed at random. The syntax of the open statement is Open filename for [Random] as #file number len = record length Binary file access In this file access system, which helps to keep the file, size small. The syntax of the open statement is Open filename for Binary as # file number Retrieval system

Page 57

Visual Programming
The records that are stored inside the file is retrieved for process by another techniques. The read statement is used to read from the file or otherwise the Input statement helps to read the information from the file. In Object oriented Technology the FileSystemObject is used for reading, and writing into the file. 2.2.6 Simultaneous multiplatform development Mixed language programming is the process of building programs in which the source code is written in two or more languages. Compaq Visual Fortran can be used with other 32-bit versions of Microsoft languages like Visual C++, VisualBasic, and MASM(Microsoftassembler). Mixed language development is especially easy in Combination with Microsoft Visual C++ 6. All minor versions of Compaq Visual Fortran Version 6 use the same Microsoft DeveloperStudio IDE that is used with VisualC++ 6. Having a common IDE with MicrosoftVisual C++ enables you to edit,debug,compile,and link Fortran and C/C++ modules transparently. Fortran object Modules may be linked directly with your C/C++ program. It is also possible to create Fortran DLLs and use MFC In VisualC++6 to create "wrappers" for the DLLs. OLE objects can also be created in this manner. 2.2.7 Interoperability COM Interoperability in Visual Basic and Visual C# When you want to use COM objects and .NET objects in the same application, you need to address the differences in how the objects exist in memory. A .NET object is located in managed memory the memory controlled by the common language runtime and may be moved by the runtime as needed. A COM object is located in unmanaged memory and is not expected to move to another memory location. Visual Studio and the .NET Framework provide tools to control the interaction of these managed and unmanaged components. For more information about managed code, see Common Language Runtime. In addition to using COM objects in .NET applications, you may also want to continue to develop COM objects using Visual Basic .NET or Visual C# .NET. The links on this page provide information about the concepts and implementation details for interoperating between COM and .NET objects. 2.2.8 Form Design

Page 58

Visual Programming
In visual basic, the form is a container for all the controls that makes up the user interface. When a visual basic application is executed, each window it displays on the desktop is a Form. The form is the only object that can have menus attached and form is the top-level object in visual basic application, and every application starts with the form. Appearance of Forms The main characteristic of a form is the title bar on which the forms caption is displayed. On the left hand side the of the form is the control menu icon. Clicking this icon opens the control menu. Right hand side of the title consists of three buttons. Minimize, Maximize and Close Button as shown below:

Start-up Form A typical application has more than a single form. When an application starts the main form is loaded. Specifying which form is to be loaded, by setting the start-up object in the project properties window can control form. Selecting project properties option under project menu can set this.

Page 59

Visual Programming

Project Properties Properties under Form object are: 1. Border Style : The variety of borders are: (i) None : no border is shown . In addition to this maximize, minimize, close & title bar are hidden. (ii) Fixed Single : A single pixel width border is shown. (iii) Sizable : Default setting (iv) Fixed Double : Double pixel width border is shown (v) Fixed Tool Window : Used for tool bars that might be floating in workspace. Only title box and close box are visible. (vi) Sizable Tool Window : same as fixed tool window but borders are resizable. 2. Caption : Title for window is given which appears below the forms icon when form is minimized. 3. Control Box : Shows the control box when upper-left corner/icon of the window are clicked. 4. Icon: Specifies icon for the window in upper-left corner of the window. 5. Mouse Pointer : Type of mouse pointer appears when its moved on a particular area of the object at run-time. 6. Max Button : Indicates whether this button should be shown or not. 7. MDI Child : Specifies if this window must be shown within a Multiple Document interface window. 8. Min Button : Indicates whether this button must be shown or not. 9. Moveable : when set to false , window cant be moved. 10. Start Up Position: Instead of writing code to position window, one can pick a starting position from the drop-down menu. The choices are : Page 60

Visual Programming
a. Manual : any position in the layout window. b. Center owner: form is centered inside another form. c. Center Screen : form is centered in users screen. d. Windows Default : allows the window to decide for the forms position. Window State : The state of window (max, min, normal) is specified 2.2.9 Overview ] Visual Basic is an event driven program that uses events and more over it uses the GUI programming . Visual Basic has evolved from the original BASIC language and now contains several hundred statements, functions, and keywords many of which relate directly to the Windows GUI. It falls in to the class known Rapid Application Development or RAD tools. It is object based with set of debugging tools. All the components such as Forms, Controls and other visible parts of the programs are objects. In addition there are hidden objects, which is present in the computer memory. It provides gradual transition from procedural to event-driven programming. Once the event processor detects an event, the code corresponding to that event is executed. Program control is then returned to the event processor. Visual Basic IDE provides an ideal platform for application development. 2.2.10 Programming fundamentals This unit introduces the essential components of the Visual Basic language. After creating the interface for the application using forms and controls, the code that defines the application's behavior must be written. As with any modern programming language, Visual Basic supports a number of common programming constructs and language elements. Programming Statements in VB Some of the statements in VB are discussed below: AppActivate Statement Activates an application window. Syntax AppActivate title[, wait] Beep Statement Sounds a tone through the computer's speaker. Syntax Beep Call Statement Transfers control to a Sub procedure, Function procedure, or dynamic-link library (DLL) procedure. Syntax [Call] name [argumentlist]

Page 61

Visual Programming
Close Statement Concludes input/output (I/O) to a file opened using the Open statement. Syntax Close [filenumberlist] The optional filenumberlist argument can be one or more file numbers using the following syntax, where filenumber is any valid file number: [[#]filenumber] [, [#]filenumber] . . . Const Statement Declares constants for use in place of literal values. Syntax [Public | Private] Const constname [As type] = expression Date Statement Sets the current system date. Syntax Date = date Declare Statement Used at module level to declare references to external procedures in a dynamiclink library (DLL). Syntax 1 [Public | Private] Declare Sub name Lib "libname" [Alias "aliasname"] [([arglist])] Syntax 2 [Public | Private] Declare Function name Lib "libname" [Alias "aliasname"] [([arglist])] [As type] The arglist argument has the following syntax and parts: [Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type] Deftype Statements Used at module level to set the default data type for variables, arguments passed to procedures, and the return type for Function and Property Get procedures whose names start with the specified characters. Syntax DefBool letterrange[, letterrange] . . . DefByte letterrange[, letterrange] . . . DefInt letterrange[, letterrange] . . . DefLng letterrange[, letterrange] . . . DefCur letterrange[, letterrange] . . . DefSng letterrange[, letterrange] . . . DefDbl letterrange[, letterrange] . . .

Page 62

Visual Programming
DefDec letterrange[, letterrange] . . . DefDate letterrange[, letterrange] . . . DefStr letterrange[, letterrange] . . . DefObj letterrange[, letterrange] . . . DefVar letterrange[, letterrange] . . . For example, in the following program fragment, Message is a string variable: DefStr A-Q ... Message = "Out of stack space." Dim Statement Declares variables and allocates storage space. Syntax Dim [WithEvents] varname[([subscripts])] [As [New] type] [, [WithEvents] varname[([subscripts])] [As [New] type]] . . . End Statement Ends a procedure or block. Syntax End End Function End If End Property End Select End Sub End Type End With Enum Statement Declares a type for an enumeration. Syntax [Public | Private] Enum name membername [= constantexpression] membername [= constantexpression] ... End Enum Erase Statement Reinitializes the elements of fixed-size arrays and releases dynamic-array storage space. Syntax Erase arraylist The required arraylist argument is one or more comma-delimited array variables to be erased.

Page 63

Visual Programming
Error Statement Simulates the occurrence of an error. Syntax Error errornumber The required errornumber can be any valid error number. Event Statement Declares a user-defined event. Syntax [Public] Event procedurename [(arglist)] Exit Statement Exits a block of DoLoop, For...Next, Function, Sub, or Property code. Syntax Exit Do Exit For Exit Function Exit Property Exit Sub Function Statement Declares the name, arguments, and code that form the body of a Function procedure. Syntax [Public | Private | Friend] [Static] Function name [(arglist)] [As type] [statements] [name=expression] [ExitFunction] [statements] [name = expression] End Function The arglist argument has the following syntax and parts: [Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type] [= defaultvalue] f variables in the same expression. GoSub...Return Statement Branches to and returns from a subroutine within a procedure. Syntax GoSub ... line ... Return The line argument can be any line label or line number.

line

Page 64

Visual Programming
GoTo Statement Branches unconditionally to a specified line within a procedure. Syntax GoTo line The required line argument can be any line label or line number. Implements Statement Specifies an interface or class that will be implemented in the class module in which it appears. Syntax Implements [InterfaceName | Class] The required InterfaceName or Class is the name of an interface or class in a type library whose methods will be implemented by the corresponding methods in the Visual Basic class. Let Statement Assigns the value of an expression to a variable or property. Syntax [Let] varname = expression Mid Statement Replaces a specified number of characters in a Variant (String) variable with characters from another string. Syntax Mid(stringvar, start[, length]) = string On Error Statement Enables an error-handling routine and specifies the location of the routine within a procedure; can also be used to disable an error-handling routine. Syntax On Error GoTo line On Error Resume Next On Error GoTo 0 On...GoSub, On...GoTo Statements Branch to one of several specified lines, depending on the value of an expression. Syntax On expression GoSub destinationlist On expression GoTo destinationlist Property Get Statement Declares the name, arguments, and code that form the body of a Property procedure, which gets the value of a property. Syntax

Page 65

Visual Programming
[Public | Private | Friend] [Static] Property Get name [(arglist)] [As type] [statements] [name = expression] [Exit Property] [statements] [name = expression] End Property The arglist argument has the following syntax and parts: [Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type] [= defaultvalue] Property Let Statement Declares the name, arguments, and code that form the body of a Property Let procedure, which assigns a value to a property. Syntax [Public | Private | Friend] [Static] Property Let name ([arglist,] value) [statements] [Exit Property] [statements] End Property The arglist argument has the following syntax and parts: [Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type] [= defaultvalue] Property Set Statement Declares the name, arguments, and code that form the body of a Property procedure, which sets a reference to an object. Syntax [Public | Private | Friend] [Static] Property Set name ([arglist,] reference) [statements] [Exit Property] [statements] End Property The arglist argument has the following syntax and parts: [Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type] [= defaultvalue] Public Statement Used at module level to declare public variables and allocate storage space. Syntax Public [WithEvents] varname[([subscripts])] [As [New] type] [,[WithEvents] varname[([subscripts])] [As [New] type]] . . .

Page 66

Visual Programming
Private Statement Used at module level to declare private variables and allocate storage space. Syntax Private [WithEvents] varname[([subscripts])] [As [New] type] [,[WithEvents] varname[([subscripts])] [As [New] type]] . . . RaiseEvent Statement Fires an event declared at module level within a class, form, or document. Syntax RaiseEvent eventname [(argumentlist)] The required eventname is the name of an event declared within the module and follows Basic variable naming conventions. ReDim Statement Used at procedure level to reallocate storage space for dynamic array variables. Syntax ReDim [Preserve] varname(subscripts) [As type] [, varname(subscripts) [As type]] . . . Rem Statement Used to include explanatory remarks in a program. Syntax Rem comment You can also use the following syntax: ' comment The optional comment arhgument is the text of any comment you want to include. A space is required between the Rem keyword and comment. Resume Statement Resumes execution after an error-handling routine is finished. Syntax Resume [0]h Resume Next Resume line Set Statement Assigns an object reference to a variable or property. Syntax Set objectvar = {[New] objectexpression | Nothing} Static Statement Used at procedure level to declare variables and allocate storage space. Variables declared with the Static statement retain their values as long as the code is running. Syntax

Page 67

Visual Programming
Static varname[([subscripts])] [As [New] type] [, varname[([subscripts])] [As [New] type]] . . . Stop Statement Suspends execution. Syntax Stop Sub Statement Declares the name, arguments, and code that form the body of a Sub procedure. Syntax [Private | Public | Friend] [Static] Sub name [(arglist)] [statements] [Exit Sub] [statements] End Sub The arglist argument has the following syntax and parts: [Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type] [= defaultvalue] Type Statement Used at module level to define a user-defined data type containing one or more elements. Syntax [Private | Public] Type varname elementname [([subscripts])] As type [elementname [([subscripts])] As type] ... End Type Unload Statement Unloads a form or control from memory. Syntax Unload object The object placeholder is the name of a Form object or control array element to unload. Control Structures Control structures allow controlling the flow of the program's execution. If left unchecked by control-flow statements, a program's logic will flow through statements from left to right, and top to bottom.

Page 68

Visual Programming
a. Decision Structures Visual Basic procedures can test conditions and then, depending on the results of that test, perform different operations. The decision structures that Visual Basic supports include: If...Then If...Then...Else Select Case b. Loop Structures Loop structures allow you to execute one or more lines of code repetitively. The loop structures that Visual Basic supports include: Do...Loop For...Next For Each...Next While Wend Programming in Visual Basic involves two different activities, such as Form Designing and Coding. The form designing helps the Visual Basic Application to be created by adding up tools to the form. These tools are otherwise known as objects. These objects are referred in the programming with the help of events. The auto quick info and Auto list members help the programmers in the Visual Basic graphics programming. Programmer must follow the naming convention while using objects. The first three letters of the object must follow naming convention of the object and it has to be given in lower case ex., lst, cbo, chk, opt, txt etc., 2.2.11 VBX controls Microsoft uses this terminology to refer to any control, which exists as a separate file whose extension is .vbx or .ocx. To use an ActiveX control in the VB program, the control must be registered in the Windows Registry. Usually, the OCX control installation software handles the registration (such as VB does to register the controls it provides). If there is a have a control, which has not been registered by other software, then it can be registered using the free program provided by Microsoft. The program, REGSVR32, comes with all version of Windows and is usually found in the Windows folder. To use it, simply type in: REGSVR32 control.ocx where the "control.ocx" is the filename of the control that is to be registered. To add the custom control into the form : Right click the toolbox Page 69

Visual Programming
Select Components from the pop-up menu. List of Active X Controls are : Rich Text Box Control Tabstrip control Slider control Progress Bar control StatusBar Control Toolbar control Imagelist Control ImageCombo Control ListView Control Treeview Control 2.2.12 Graphics application Image List Controls The Image List control allows to add images to the program, which can be used in the other Common Controls (Toolbar, TreeView, ListView etc). To add the ImageList control to the Visual Basic project, click Project Components check the box for Microsoft Windows Common Controls x.x where x is the version of Visual Basic. Image Combo Controls Image Combo control is similar to Image List control with the main difference is that Image Combo control is visible at runtime where as Image List control is not visible at runtime. Another difference is that in an Image List control one has to add images at design time where as in an Image Combo control one can add images at runtime time. Status Bar A status bar control is a frame that consists of several panels, which inform the user about the status of an application. The control can hold upto 16 frames. It can be placed at the top or bottom or sides of an application. Properties of Status Bar Style : The style of the status bar may be either Normal or simple. Mouse Pointer : The user can select type of mouse pointer from the given list. Panels : One can either insert/remove panels for a status bar and can also give key value, tool tip text , tags , index. Index should always start with one.

Page 70

Visual Programming
Alignment : The panel can be aligned to the left, center or right. Picture : we can also give pictures to panels. The Slider Control The slider control is similar to the scrollbar control. The slider control icon does not appear in the toolbox by default. To use the control in a project right-click the toolbox or select components in the project menu. On the components dialog box, check Microsoft windows common controls 6.0. This will add a number of common controls to the toolbox, including the slider control. As same like scrollbar control it has similar properties of Small Change and Large Change are available. Small change is the smallest increment by which the slider value can change. 2.2.13 Animation In visual Basic animation is a process which can be handled by the timer control mostly and apart from that there are a few activeX control which helps in animation such as Windows common control 2.5.0(sp2) is one such insertable control which helps in running the .AVI files. These animation gives a liveliness to the application. It helps users to get engaged with the visual effects. The timer control to some extent helps in animation Animation using Timer in VB private if label1.visible=false elseif label1.visible=true end end sub private timer1.interval=200 timer1_timer end sub 2.2.14 Interfacing It provides the media that helps to connect the files with other system. The interface for animation control is the insertable ActiveX control Windows common Control 2.5.0 (SP2) . This interface brings about the object with which animation is possible. Similarly the FSO (FileSystemObject) acts as an interface for the object oriented file access controls. The other interfaces like ADO, DAO and RDO are the sub label1.visible=true label1.visible=false timer1_timer() then then if sub form1_load()

Page 71

Visual Programming
interfaces that help in interacting with the databases at the back end with that of Visual Basic programming. Visual Basic provides the tools to allow combining objects from different sources. Custom solutions can be built by combining the most powerful features of Visual Basic and applications that support Automation (formerly known as OLE Automation). From printing work to maintenance work all need to have some interface in Visual Basic and these interface are flexible and developments are going on in adding more flexibility in this area. 2.2.15 File System Controls The majority of Windows applications handle files. There are three file system controls in visual basic. They are DriveList box, file List Box, and Directory List Box. One can select the desired file by selecting a drive from the DriveListBox, a directory from the DirectoryListBox and a file from the FileListBox The form design is shown below:

2.2.16 Data Control The Data control comes embedded into Visual Basic, just like the text box. It allows to quickly and easily create a program for creating and using databases. A form is created with all the required fields from an existing database either using the Data Form wizard, or manually. The basic steps, required to create a program, that will show the records in an Access database, are given below: Create a new project Add a DataControl to the form.

Set the name property to datatitles Page 72

Visual Programming
Set the Text property to Titles. click the ... (3 dots) next to the DatabaseName property. Locate the file and click open. This specifies the database where the control will get its information from. Select the table from which the control gets the fields from - click the arrow next to the RecordSource property, and select Titles Database Application with Data Control (DBGrid Control) As developing any other application, here too objects should be created and their properties must be set. Object Form Data Property Caption Caption DatabaseName RecordSource Datasource Value DBGrid Sample Students Table student.mdb studentsdtls Data1(Name of the Data Control)

DBGrid

The Form will look as shown in the fig.

Form Design Now if the application is run the databound grid control will get populated from the table automatically and will appear as shown in figure.

Page 73

Visual Programming

Populated Data Bound Grid control This running application will enable the user to manipulate data interactively. Some of the notable properties of the DBGrid control are given below: AllowAddNew: Enables or disables interactive record addition AllowArrows: Enables or disables use of arrow keys for grid navigation AllowDelete: Enables or disables interactive record deletion AllowUpdate: Enables or disables record updatability ColumnHeaders: Turns column heading on or off RowDividerStyle: Selects style for row divider lines Database without using Data control A record is another example of a data structure. The difference between an array and a record is that the record is able to store different types of related data. Consider a suitable data structure to store information on a bank customer. The bank might like to store information on the customer's name, balance, age & whether the customer is overdrawn. A record is an ideal data structure for holding the details on that customer. The customer's name would be stored as a string, while the balance could be stored as a currency variable, age as an integer and overdrawn in a Boolean variable - all differing variable types but within one record.

Page 74

Visual Programming
a. Defining (declaring) a record type The definition of the record is quite simple and is done with a user defined type. b. Declaring an Instance of the Record Type. The declaration of an instance of the type is declared, in the usual way, after the keyword DIM. A record is an example of a static data structure, and consequently, the four basic operations that can be carried out on such a structure are: Initialization Assignment Rearrangement Retrieval c. Forming a Table A table is an array whose elements is a structure record, and in this example will constitute a set of records for a group of customers. This is easily done by defining (declaring) a table type and variable of a table type. d. Defining (declaring) a table type and variable of a table type A table type is another example of a user-defined type. It is an array of records where the record is a user-defined type. It is straightforward to define. Thus, even without using Data Controls in VB, the database can be created, manipulated and stored. 2.2.17 Database applications DAO The Data access Object (DAO) is a collection of object classes that provide properties and methods for database programming. This model furnishes facilities for creating databases, defining tables, fields and indexes, establishing relations between tables, navigating and querying the database, and so on. DAO is the only data access technology that supports 16-bit operations. If an application must run within 16-bit environment, then DAO is the only choice. If the application must access both native Microsoft Jet and ODBC resources, DAO provides a consistent programming model.

Page 75

Visual Programming
The DAO Object Model In DAO object model, Microsoft Jet database engine translates operations on data access objects into physical operations on the database files, handling all the mechanics of interfacing with the different supported databases. The database engine is what actually reads, writes and modifies the database and handles all the housekeeping chores like indexing and security etc. DAO object model.
DB Engine Workspace Database TableDef Field Index Field QueryDef Field Parameter RecordSet Field Relation Field Error

RDO Concepts There are about two alternative methods for accessing database information using Visual Basic 6 the Remote Data Control (RDC) and the Remote Data Objects (RDOs). Both these alternative methods are designed for reading and updating data stored in relational database management systems (RDBMSs) that are external to Visual Basic and to the Microsoft Jet data engine. Although it is possible to use the standard data control and

Page 76

Visual Programming
Microsoft Jet data object collections to access data stored in RDBMS, the RDC and RDOs have properties and methods that make them better suited to manipulating data in remote systems. Object rdoColumn Description The RDO version of the Microsoft Jet Field object rdoConnection The RDO equivalent of the Microsoft Jet Database object rdoEngine The top-level data engine used to access remote data rdoEnvironment The RDO equivalent of the Microsoft Jet Workspace object rdoParameters A special collection of query parameters for the rdoQuery object rdoQuery The RDO version of the Microsoft Jet QueryDef object rdoResultset The RDO equivalent of the Microsoft Jet Recordset object rdoTable The RDO version of the Microsoft Jet Table object RDO programming objects. Most RDOs have a parallel in the Microsoft Jet DAO collections. 2.2.18 Report Generation A Data Project is a Standard Exe project which supports all the database tools supported by a normal project along with some additional controls such as Data Repeater control, Adodc, Data Grid control, MSHFlex Grid control, Data Combo control, Data List control. A Data Project contains a new Form and two ActiveX designers, which describes about the components design. It has mainly two designers namely, Data Environment ActiveX Designer Data Report ActiveX Designer The Data Environment Designer is used to connect to the required database and retrieve the desired records. The Data Report is used to design reports.

Page 77

Visual Programming
Data Report Data Report is mainly used to generate reports. It consists of different sections such as, Detail section, Page Header/Footer, Group Header/Footer etc. The Data Report has separate set of Toolbox controls called as RptControls. Normal toolbox controls do not work on a Data Report. Let us now have an example for Data Report. First double click the Data Report from the Project Explorer to open a Report sheet.

DataProject Window Here one has to get the group report that is report on department wise data and the total sum of the employees working in that department. In Page Header column place two RptLabels for Date and Time . One can select the required format of date & time by right clicking on the Page Header section. The Group Header/Footer can be inserted by right-clicking on any one of the sections. Page Footer is used to display the current page and total number of pages. In Group Header, place Department Number and the field names of child command (Emp_comm). In Detail section, place corresponding data fields of the Emp_comm by dragging the Emp_comm. Right click the group header section and select Insert control Function. This will add the Sum(unbound) function. Go to the Page Footer to get the current Page out of total number of pages. Come to the property sheet of the Data Report and give Data Source as Data Environment and Data Member as Command1(Dept_comm). Also change the properties of Function1(Sum) for which Data Member : Emp_comm and Data Field:sal Users can select the type of the function from the properties of Function1. The function selected here is 0-rpt func sum. Data Format can also be selected here.

Page 78

Visual Programming
Now select Project DataProject Properties and select DataReport1 and run the report. Data Environment Designer It consists of different connections, commands and recordsets. The Connection object is used to connect to the appropriate database using the OLE DB Provider and the Command object is to specify generally the database object type (Table, View, Synonym, or Stored Procedure). If a connection is not given user can add a connection by right clicking the Data Environment designer. The implementation of Data Environment design is given with the help of the following steps : Select the Data Environment object from the Data Project explorer.

Data Environment window Right click the connection object and from the shortcut menu. Select Properties option to open the Data Link Properties sheet. (Here the Provider tab is used to select the required driver between the database and the application. Most databases use Microsoft Jet 3.51 OLE DB Provider.)

Page 79

Visual Programming

Data Link Properties 4. Select the connection tab to select the database. 4. Give the required username and password (if any). Once the database is selected, test whether it is connected or not using the Test Connection button. If connected it gives successful connection.

Specifying database name in Data Link Properties

Page 80

Visual Programming

Conncetion testing for Data Link The Advanced tab is used to specify how the database is going to open, the different rights on the database such as Read, ReadWrite, Share Deny None, Share Deny Read etc. The All tab is used to display the different settings given for the previous tabs.

Selecting Data source for Data Link Click OK to return to the Data Environment Window.

Page 81

Visual Programming
Now add a command object to the connection1 and name it as Dept_comm. Right click the Dept_comm , to get the following command properties screen

Setting command In General tab, set the connection to Connection1. In the Database Object box, select Table and in the Object name from all the tables in the database. Select the department table and click Apply. Click OK to return to the Data Environment1 window. Now click the Form provided by default (frmDataEnv). Drag the Dept_comm and drop it on the screen

Page 82

Visual Programming 2.3 Revision points


o Visual Basic is called event-driven programming as the application does not determine the flow but the event caused by the user determines the flow of the application o File operations can be categorized in two ways: operations on files and operations on directories, or the newer term, folders. o In visual basic, the form is a container for all the controls that makes up the user interface. The form is the only object that can have menus attached and form is the top-level object in visual basic application, and every application starts with the form. o To use an ActiveX control in the VB program, the control must be registered in the Windows Registry o The Image List control allows to add images to the program, which can be used in the other Common Controls (Toolbar, TreeView, ListView etc). o The slider control is similar to the scrollbar control. The slider control icon does not appear in the toolbox by default. o Data Control allows to quickly and easily create a program for creating and using databases.

2.4 Intext Questions


1. Explain the Data control. 2. Explain the slider and status bar control. 3. Differentiate between ActiveX EXE and ActiveX DLL 4. What is OLE? Explain the properties of OLE? 5. Explain the Graphics applications.

2.5 Summary
Visual Basic is an ideal programming language. It is called event-driven programming as the application does not determine the flow but the events caused by the user determines the flow of the application Mainly computer professionals use the professional edition of Visual Basic. It includes full featured set of tools, includes ActiveX controls, Data Environment , ADO and the Dynamic HTML page designer. The working environment in Visual Basic is often referred to as the integrated development environment or IDE because it integrates many different functions such as design, editing , compiling and debugging within a common environment

Page 83

Visual Programming
The Data Environment Designer is used to connect to the required database and retrieve the desired records. The Connection object is used to connect to the appropriate database using the OLE DB Provider and the Command object is to specify generally the database object type Data Report is mainly used to generate reports. It consists of different sections such as, Detail section, Page Header/Footer, Group Header/Footer etc The Data Report has separate set of Toolbox controls called as RptControls. Normal toolbox controls do not work on a Data Report. ADO is the object-based interface that provides a logical set of objects that can be accessed from the code These objects present an interface in the form of properties and methods that can be queried and manipulated. The ADO data control presents a fast and easy way to create a bound form by providing built-in functions that define, navigate, display, add to, and update the records in a recordset. Copying File, Renaming File, Deleting File and Moving File are the basic file type operations using built in Visual Basic functions

2.6 Terminal Exercises


1. Explain Few Common Properties of the Controls? 2. What are all the Four special values in VISUAL BASIC? 3. Explain the properties of DAO control. 4. With examples explain the file operations.

2.7 Supplementary Material


W.L.George,J.G.Hagedorn, and J.E.Devaney.Parallel programming interoperable MPI. Dr.Dobbs Journal,(357):4953,February2004. with

2.8 Assignments
1. Develop an application in Visual Basic to help customer transaction in Banking.

2.9 Reference Books


Page 84

Visual Programming
Gary Cornell, Visual Basic 6 from the ground up, Tata McGraw Hill, 1999. Noeal Jerke, Visual Basic 6 The Complete Reference, Tata McGraw Hill, 1999. John W. Franchowian, David J.Helda, Visual Basic 6 Database Programming for SQL Server 7 & Oracle 8, IDG Book India (Pvt) Ltd, 2000. Siler and Spotts, Special Edition using Visual Basic 6, PHI, 2001.

2.10 Learning Activity * Learn and understand the various components and objects in Visual Basic
Programming. * Learn and understand the File System Controls in Visual Basic

2.11 Keywords
GUI Design Time Run Time Properties IDE IIS DHTML Methods Events RDO Recordset Debugging DAO : : : : : : : : : : : : Graphical User Interface Time of Developing Applications Execution Time Named Attributes of Controls Integrated Development Environment Internet Information Server Dynamic Hyper Text Markup Language Tasks performed by controls Action recognized by the controls Remote Data Object Keyword used to store all the records from table to a variable. This will help in inserting or modifying the records in the table. The process of locating and fixing bugs in your application is known as debugging. The Data access Object (DAO) is a collection of object classes that provide properties and methods for database programming. Page 85

Visual Programming

Page 86

You might also like