<<

Biyani's Think Tank Concept based notes (MSC -IT (III Sem)

Dhanesh Gupta Anju Bhatt Lecturer Deptt. of Information Technology Biyani Girls College, Jaipur

2

Published by : Think Tanks Biyani Group of Colleges

Concept & Copyright : Biyani Shikshan Samiti Sector-3, Vidhyadhar Nagar, Jaipur-302 023 (Rajasthan) Ph : 0141-2338371, 2338591-95 Fax : 0141-2338007 E- : [email protected] Website :www.gurukpo.com; www.biyanicolleges.org

First Edition : 2012

While every effort is taken to avoid errors or omissions in this Publication, any mistake or omission that may have crept in is not intentional. It may be taken note of that neither the publisher nor the author will be responsible for any damage or loss of any kind arising to

anyone in any manner on account of such errors and omissions.

Leaser Type Setted by : Biyani College Printing Department

(Visual Basic) 3

Preface

I am glad to present this book, especially designed to serve the needs of the students. The book has been written keeping in mind the general weakness in understanding the fundamental concepts of the topics. The book is self- explanatory and adopts the “Teach Yourself” style. It is based on question- answer pattern. The language of book is quite easy and understandable based on scientific approach. Any further improvement in the contents of the book by making corrections, omission and inclusion is keen to be achieved based on suggestions from the readers for which the author shall be obliged. I acknowledge special thanks to Mr. Rajeev Biyani, Chairman & Dr. Sanjay Biyani, Director (Acad.) Biyani Group of Colleges, who are the backbones and main concept provider and also have been constant source of motivation throughout this Endeavour. They played an active role in coordinating the various stages of this Endeavour and spearheaded the publishing work. I look forward to receiving valuable suggestions from professors of various educational institutions, other faculty members and students for improvement of the quality of the book. The reader may feel free to send in their comments and suggestions to the under mentioned address.

Author

4

Chapter-1

Integrated Development Environment

Q.1 What is an IDE? Ans.: Visual Basic is not only a language. It’s an Integrated Development Environment in which you can develop, run, test and debug your applications. The types of project that you can create in Visual Basic are as follows : (i) Standard EXE : These are the typical applications that you develop with previous versions of Visual Basic. (ii) ActiveX EXE, ActiveX DLL : These types of projects are available with the Professional edition. ActiveX components are OLE automation servers. (iii) ActiveX Control : This type of project is also a feature of the Professional edition. We use it to develop your own ActiveX controls. (iv) ActiveX Document EXE, ActiveX Document DLL : ActiveX documents are in essence Visual Basic applications that can run in the environment of the container that supports hyper-linking. (v) VB Application Wizard, VB Wizard Manager : The Application Wizard takes you through the steps of setting up the skeleton of a new application. The Wizard Manager lets you build your own wizard. (vi) Data Project : It’s identical to the Standard EXE project type, but it automatically adds the controls that are used in accessing databases to the Toolbox.

(Visual Basic) 5

(vii) DHTML Application : VB6 allows you to build Dynamic HTML pages that can be displayed in the browser’s window on a client computer. (viii) IIS Application : VB6 allows you to build applications that run on the Web and interact with clients over the Internet with the Internet Information Server. (ix) Addin : You can create your own add-ins for the VB IDE. These are special commands you can add to Visual Basic’s menus. (x) VB Enterprise Edition Controls : It simply creates a new Standard EXE project and loads all the tools of the Enterprise Edition of Visual Basic. Q2 What is visual ? Explain characteristics and features.

Ans Visual Basic (VB) is a third-generation event-driven programming language and integrated development environment (IDE) from for its COM programming model first released in 1991. Visual Basic is designed to be relatively easy to learn and use. Visual Basic was derived from BASIC and enables the rapid application development (RAD) of graphical (GUI) applications, access to databases using Data Access Objects, Remote Data Objects, or ActiveX Data Objects, and creation of ActiveX controls and objects. Scripting languages such as VBA and VBScript are syntactically similar to Visual Basic, but perform differently.

A can put together an application using the components provided with Visual Basic itself. Programs written in Visual Basic can also use the Windows API, but doing so requires external function declarations. Though the program has received criticism for its perceived faults, from version 3 Visual Basic was a runaway commercial success,[4] and many companies offered third party controls greatly extending its functionality.

The final release was version 6 in 1998. Microsoft's extended support ended in March 2008 and the designated successor was Visual Basic .NET (now known simply as Visual Basic).

6

Language features Like the BASIC programming language, Visual Basic was designed to be easily learned and used by beginner . The language not only allows programmers to create simple GUI applications, but can also develop complex applications. Programming in VB is a combination of visually arranging components or controls on a form, specifying attributes and actions of those components, and writing additional lines of code for more functionality. Since default attributes and actions are defined for the components, a simple program can be created without the programmer having to write many lines of code. Performance problems were experienced by earlier versions, but with faster computers and native code compilation this has become less of an issue.

Although programs can be compiled into native code executables from version 5 onwards, they still require the presence of runtime libraries of approximately 1 MB in size. This runtime is included by default in Windows 2000 and later, but for earlier versions of Windows like 95/98/NT it must be distributed together with the executable.

Forms are created using drag-and-drop techniques. A tool is used to place controls (e.g., text boxes, buttons, etc.) on the form (window). Controls have attributes and event handlers associated with them. Default values are provided when the control is created, but may be changed by the programmer. Many attribute values can be modified during run time based on user actions or changes in the environment, providing a dynamic application. For example, code can be inserted into the form resize event handler to reposition a control so that it remains centered on the form, expands to fill up the form, etc. By inserting code into the event handler for a keypress in a text box, the program can automatically translate the case of the text being entered, or even prevent certain characters from being inserted.

Visual Basic can create executables (EXE files), ActiveX controls, or DLL files, but is primarily used to develop Windows applications and to interface database systems. Dialog boxes with less functionality can be used to provide pop-up capabilities. Controls provide the basic functionality of the application, while programmers can insert additional

(Visual Basic) 7 logic within the appropriate event handlers. For example, a drop-down combination box will automatically display its list and allow the user to select any element. An event handler is called when an item is selected, which can then execute additional code created by the programmer to perform some action based on which element was selected, such as populating a related list.

Alternatively, a Visual Basic component can have no user interface, and instead provide ActiveX objects to other programs via (COM). This allows for server-side processing or an add-in module.

The runtime recovers unused memory using reference counting which depends on variables passing out of scope or being set to "Nothing", resulting in the very common problem of memory leaks. There is a large library of utility objects, and the language provides basic object oriented support. Unlike many other programming languages, Visual Basic is generally not case sensitive, although it will transform keywords into a standard case configuration and force the case of variable names to conform to the case of the entry within the symbol table. String comparisons are case sensitive by default.

The Visual Basic compiler is shared with other Visual Studio languages (C, C++), but restrictions in the IDE do not allow the creation of some targets (Windows model DLLs) and threading models.

Characteristics

Visual Basic has the following traits which differ from C-derived languages:

Statements tend to be terminated with keywords such as "End If", instead of using "{}"s to group statements. Multiple variable assignment is not possible. A = B = C does not imply that the values of A, B and C are equal. The boolean result of "Is B = C?" is stored in A. The result stored in A would therefore be either false or true.

8

Boolean constant True has numeric value −1.[5] This is because the Boolean data type is stored as a 16-bit signed integer. In this construct −1 evaluates to 16 binary 1s (the Boolean value True), and 0 as 16 0s (the Boolean value False). This is apparent when performing a Not operation on a 16 bit signed integer value 0 which will return the integer value −1, in other words True = Not False. This inherent functionality becomes especially useful when performing logical operations on the individual bits of an integer such as And, Or, Xor and Not.[6] This definition of True is also consistent with BASIC since the early 1970s Microsoft BASIC implementation and is also related to the characteristics of CPU instructions at the time. Logical and bitwise operators are unified. This is unlike some C- derived languages (such as Perl), which have separate logical and bitwise operators. This again is a traditional feature of BASIC. Variable array base. Arrays are declared by specifying the upper and lower bounds in a way similar to Pascal and Fortran. It is also possible to use the Option Base statement to set the default lower bound. Use of the Option Base statement can lead to confusion when reading Visual Basic code and is best avoided by always explicitly specifying the lower bound of the array. This lower bound is not limited to 0 or 1, because it can also be set by declaration. In this way, both the lower and upper bounds are programmable. In more subscript-limited languages, the lower bound of the array is not variable. This uncommon trait does exist in Visual Basic .NET but not in VBScript.

Q.3 Explain the elements of the User Interface? Ans.: The user interface is what appears in the application’s window when it runs. It consists of various elements with which the user can interact and control the application. The first element of the user interface is the Form. (i) Picture Box : This control is used to display images, and the images are set with Picture property (ii) Label : This control displays text on a Form that the user can’t edit. (iii) Text Box : It displays text that the user can edit.

(Visual Basic) 9

(iv) Frame : It is used to draw boxes on the Form and to group other elements. (v) Command Button : It is the most common element of the Windows interface. It represents an action that is carried out when the user clicks the button. (vi) Check Box : It presents one or more choices that the user can select. (vii) Option Button : Also called as radio buttons, appear in groups, and the user can choose only one of them. (viii) Combo Box : It is similar to the List Box control, but it contains a text Edit field. The user can choose an item from the list or enter in the Edit field. (ix) List Box : It contains a list of options from which the user can choose one or more. The user can scroll the list to locate an item. (x) The Horizontal and Vertical Scroll Bars : The user specify a magnitude by scrolling the control’s button between its minimum and maximum value. (xi) Timer : It is used to perform tasks at regular intervals. (xii) Controls : These controls are used to add file- handling capabilities to your application (xiii) Image : It is similar to the Picture Box control in that it can display images, but it supports only a few features of the Picture Box control and requires fewer resources. (xiv) Data : It provides point and click access to data stored in data- bases. (xv) OLE : It is a window you can place on your Form to host documents from other applications, such as or Excel.

10

Q.3 What are the common properties of the Controls? Ans.: The following properties apply to most of the objects : Name : It sets the name of the control, through which you can access the control’s properties and methods. Appearance : It can be 0 for a flat look or 1 for a 3-D look. Back Color : It sets the background color on which text is displayed or graphics are drawn. Fore Color : It sets the foreground color Font : It sets the face, attribute, and size of the font used for the text on the control. Caption : It sets the text that is displayed on many controls that don’t accept input, for example, the text on a Label control, the caption of a Command Button control. Text : It sets the text that is displayed on the controls that accept user input, for example, the TextBox control. Width & Height : These properties set the control’s dimensions. Left & Top : These properties set the coordinates of the control’s upper-left corner, expressed in the units of the container. Enabled : By default, this property’s value is True, which means that the control can get the focus. Visible : Set this property to False to make a control invisible.

□ □ □

(Visual Basic) 11

Chapter-2

Basic Programming Concepts

Q.1 How variables are declared in Visual Basic? Ans.: Variables are used to store values during a program’s execution. So, variables are place values in which you can leave values and recall them at will. (a) Declaring Variables : In most programming languages, variables must be declared in advance for the compiler. Explicit Declarations : To declare a variable, use the Dim statement followed by the variable’s name and type as follows : o Dim Meters as Integer o Dim Names as String Implicit Declarations : When Visual Basic meets an undeclared variable name, it creates a new variable on the spot and uses it. The new variable’s type is variant, the generic data type that can accommodate all other data types. Dim var1, var2 var1=”Thank you” var2=43.23 The var1 variable is a string variable, and var2 is a numeric one.

12

(b) Types of Variables : Visual Basic recognizes the following six types of variables : Numeric : The different numeric data types provided are : (a) Integers

(b) Single, or floating point numbers with limited precision (c) Double, or floating point numbers with extreme precision String : This data type stores only text and string variables are declared with the String type. Boolean : This data type stores True/False values.

Date : Date and time values are double-precision numbers: the integer part represents the date and the fractional part represents the time. Object : An object variable refers to one of Visual Basic’s many objects, and you can use an object variable to access the actual object. Variant : This is the most flexible data type because it can accommodate all other types.

Q.2 What is the Variable’s Scope and Lifetime of a Variable? Ans.: A Variable’s Scope : The scope of a variable is the section of the application that can see and manipulate the variable. If a variable is declared within a procedure, only the code in the specific procedure has access to that variable. When the variable’s scope is limited to a procedure it’s called local.

(Visual Basic) 13 e.g. Private Sub Command1_Click() Dim i as Integer Dim Sum as Integer

For i=0 to 100 Step 2 Sum = Sum +i Next MsgBox “ The Sum is “& Sum End Sub

A variable whose value is available to all procedures within the same Form or Module are called Form-wide or Module-wide and can be accessed from within all procedures in a component. In some situations the entire application must access a certain variable. Such variable must be declared as Public. Lifetime of a Variable : It is the period for which they retain their value. Variables declared as Public exist for the lifetime of the application. Local variables, declared within procedures with the Dim or Private statement, live as long as the procedure.

You can force a local variable to preserve its value between procedure calls with the Static keyword. The advantage of using static variables is that they help you minimize the number of total variables in the application. Variables declared in a Form outside any procedure take effect when the Form is loaded and cease to exist when the Form is unloaded. If the Form is loaded again, its variables are initialized, as if it’s being loaded for the first time.

14

Q.3 What are constants? Ans.: Some variables don’t change value during the execution of program. These are constants that appear many times in your code. The constants are preferred for two reasons : Constants don’t change value Constants are processed faster than variables The general form to declare a constant is as follows : Const constantname [As type] =value The As type part of the declaration is optional. If you omit it, the constant’s type is determined by the value you assign to it. Constants also have a scope and can be Public or Private. e.g. Public Const pi as Double =3.14159265358979 Visual Basic uses constants extensively to define the various arguments of its methods and the settings of the various control properties. □ □ □

(Visual Basic) 15

Chapter-3

Procedural Programming

Q.1 Explain Objects and Modules? What are the types of Modules in VB? Ans.: Objects : Objects are the real world entities. , companies, employees, fan and ledger entries are all types of objects. In object- oriented terms, the word object is used to describe one specific thing like a car. Objects have an identity and this identity is defined with properties. A car has its name, model, cost and color. Objects also do things. E.g. the car accelerates, races etc. The things an object can do are called its behaviours. Objects can be anything that exists in real world. They can be conceptual things, such as engineering process or payroll. These conceptual things are not tangible but are conceptual. The same object-oriented concepts apply regardless of whether the object is based on the real world, on a concept, or on the implementation. Modules: Modules are collection of code and data that function something like objects in objects oriented programming, but without defining OOP characteristics like inheritance, polymorphism etc. The concept behind modules is to enclose procedures and data in a way that hides them from the rest of the program. The two main types of procedures used in VB : Event and General : In VB event procedures are invoked in response to keyboard, mouse or system action. Your code can also explicitly invoke

16

event procedures. The maximum number of events a control can have is fixed. Event procedures are stored in a form module and are private by default. A general procedure is not executed unless explicitly invoked. You can create a general procedure either by choosing the procedure from the insert menu or by typing the procedure heading Sub followed by the procedure name on a blank line. Event and general procedures are further classified as : Sub & Function.

Q.2 What are Procedures? OR What are Subroutines and Functions? Ans.: The code you write won’t be a monolithic listing. It will be made up of small segments called procedures and you will work on one procedure at a time. This is called modularized approach of programming. It permeates the Visual Basic language even the longest applications are written by breaking them into small, well defined tasks. Each task is performed by a separate procedure that is written and tested separately from the others. Procedures are useful for implementing repeated tasks. The two types of procedures are subroutines and functions—the building blocks of your application. Subroutines : A subroutine is a block of statements that carries out a well- defined task. The subroutine begins with Sub and name of subroutine and its execution stops when EndSub statement is reached, and control returns to the calling program. It is possible to exit a Subroutine prematurely with the Exit statement. Functions : A function is similar to a subroutine, but a function returns a result. Subroutines perform a task and don’t report anything to the calling program; functions commonly carry out calculations and report the result. The statements that make up a function are placed in a pair of Function/End Function statements. Because the function must report the result to the calling program, it must have a return type.

□ □ □

(Visual Basic) 17

Chapter-5

Branching and Looping Constructs

Q.1 What are the Branching Statements in Visual Basic? OR What are the different conditional constructs in Visual Basic? Ans.: An application needs a built-in capability to test conditions and take a different course of action depending on the outcome of the test. Visual Basic provides three control flow, or decision, structures : If……Then : The If….Then structure tests the condition specified, and if it’s True, executes the statement(s) that follow. The If structure can have a single-line or a multiple-line syntax. The general form is : If condition Then statement If……Then……Else : A variation of the If……Then statement is the If……Then……Else statement, which executes one block of statements if the condition is True and another if the condition is False. The syntax of the If… Then….Else statement is as follows: If condition Then statement block-1 Else statement block-2 End If

18

Select Case : The Select Case structure compares one expression to different values. The advantage of the Select Case statement over multiple If…..Then…..Else statements is that it makes the code easier to read and maintain. The Select Case structure tests a single expression, which is evaluated once at the top of the structure. The result of the test is then compared with several values, and if it matches one of them, the corresponding block of statements is executed. The syntax is : Select Case expression Case value1 Statement block-1 Case value2 Statement block-2 . . . Case Else Statement block End Select

Q.2 Explain different Looping Constructs in VB? OR What are the different types of Do……Loop? Ans.: Loop statements allow you to execute one or more lines of code repetitively. Visual Basic supports the following loop statements:

(Visual Basic) 19

Do……Loop : The Do……Loop executes a block of statements for as long as a condition is True. Visual Basic evaluates an expression, and if it’s True, the statements are executed. If the expression is False, the program continues and the statement following the loop is executed. There are two variations of the Do……Loop statement. A loop can be executed either while the condition is True or until the condition becomes True. These two variations use the keywords While and Until to specify how long the statements are executed. To execute a block of statements while a condition is true, use the following syntax : Do While condition statement block Loop To execute a block of statements until the condition becomes True, use the following syntax : Do Until condition statement block Loop Another variation of the Do loop executes the statements first and evaluates the condition after each execution. This Do…Loop has the following syntax : Do statements Loop While condition or Do statements Loop Until condition For…..Next : The For…….Next loop is one of the oldest loop structures in programming languages. Unlike the Do….loop, the For …..Next loop

20

requires that you know how many times the statements in the loop will be executed. The For…Next loop uses a variable(it’s called the loop’s counter) that increases or decreases in value during each repetition of the loop. The For…..Next loop has the following syntax : For counter=start to end[Step increment] statements Next[counter] The keywords in the square brackets are optional. The arguments counter, start, end and increment are all numeric. The loop is executed as many times as required for the counter to reach the end value. While ………Wend : The while……wend loop executes a block of statements while a condition is True. The while…..wend loop has the following syntax : While condition statement - block Wend If condition is true, all statements are executed and when the Wend statement is reached, control is returned to the While statement which evaluates condition again. If condition is still True, the process is repeated. If condition is False, the program resumes with the statement following the Wend statement.

Q.3 What is the use of ‘Exit’ statement? Ans.: The Exit statement allows you to exit prematurely from a block of statements in a control structure from a loop, or even from a procedure. Suppose you have a For…….Next loop that calculates the square root of negative numbers can't be calculated ( the Sqr() function generates a runtime error,) you might want to halt the operation if the array contains a

(Visual Basic) 21 invalid value. To exit the loop prematurely, use the Exit For statement as follows : For i=0 to UBound(nArray()) If nArray(i)<0 then Exit For nArray(i)=Sqr(nArray(i)) Next If a negative element is found in this loop, the program exits the loop and continues with the statement following the Next statement. There are similar Exit statements for the Do loop (Exit Do), as well as for functions and subroutines (Exit Function and Exit Subroutine).

□ □ □

22

Chapter-3

Array Declaration

Q.1 How Arrays are declared and initialized in Visual Basic? OR Explain different types of Arrays? Ans.: A standard structure for storing data in any programming language is an array. Whereas individual variables can hold single entities, such as a number, date, or string, arrays can hold sets of related data. An array has a name, as does a variable, and the values stored in it can be accessed by an index. Declaring Arrays : Single Dimensional Array—Used to store long sequences of one dimensional data. Unlike simple variables, arrays must be declared with the Dim statement followed by the name of the array and the maximum number of elements it can hold in parantheses, e.g. Dim Sal(15) Multidimensional Array—To store the data in a tabular or matrix form, we need two dimensional array and to store sequences of multidimensional data we need multidimensional array. In two dimensional array, first index represent the row and the second represents the column. e.g. Dim Board(5,5) As Integer

(Visual Basic) 23

Dynamic Arrays : Sometimes you may not know how large to make an array. Instead of making it large enough to hold the maximum number of data, you can declare a dynamic array. The size of a dynamic array can vary during the course of the program. To create a dynamic array, declare it as usual with the Dim statement, but don’t specify its dimensions : Dim DynArray() Later in the program, when you know how many elements you want to store in the array, use the ReDim statement to redimension the array, this time with its actual size. ReDim DynArr(UserCount) Here UserCount is a user-entered value. The ReDim statement can only appear in a procedure. □ □ □

24

Chapter-6

Forms

Q.1 What are Forms in Visual Basic? OR Explain how working of Forms is being implemented? Ans.: In Visual Basic the form is the container for all the controls that make up the user interface. When a Visual Basic application is executing, each window it displays on the Desktop is a Form. Forms have a built-in functionality that is always available without any programming effort on your part. You can move a form around, resize it, and even cover it with other Forms. You do so with the mouse, with the keyboard, or through the Control menu. Appearance of Forms : The main characteristic of a Form is the title bar on which the form’s caption is displayed. On the left end of the title bar is the Control Menu . Clicking this icon opens the Control menu. On the right side of the title bar are three buttons: Minimize, Maximize and Close. The Start-Up Form : A typical application has more than a single Form. When an application starts, the main Form is loaded. You can control which Form is initially loaded by setting the start-up object in the Project Properties window. Project -> Project Properties Loading, Showing, and Hiding Forms : The possible states of a Form are:

(Visual Basic) 25

Not loaded : The Form lives on a disk file and doesn’t take up any resources. Loaded but not Shown : The Form is loaded into memory, takes up the required resources, and is ready to be displayed. Loaded and Shown : The Form is shown, and the user can interact with it. To load and unload Forms, use the Load and Unload statements. The Load statement has the following syntax : Load formName and the Unload statement has this syntax: Unload formName To show a Form, you use the Show method. If the Form is loaded but invisible, the Show method brings the specified Form on top of every other window on the Desktop. If the Form isn’t loaded, the Show method loads it and then displays it. The Show method has the following syntax : formName.Show mode The optional argument mode determines whether the Form will be modal or modeless. It can have one of the following values : 0-Modeless (default) 1-Modal Modeless Forms interact with the user, and they allow the user to switch to any other Form of the application. If your application uses many Forms, you may want to hide some of them to make room on the Desktop for others. To hide Form, use the Form’s Hide method whose syntax is : Form.Hide To hide a form from within its own code, use the statement : Me.Hide

26 □ □ □

Chapter-7

Programming Methodologies and Controls available in VB

Q.1 What are Global and Public Variables? Ans.: The simplest method for two Forms to communicate with each other is via global variables. These variables are declared in the application’s Module with the Global or Public keyword. If the following declarations appear in a Module, then they can be accessed from any place in the application’s code : o Global Num as Integer o Public Data as Double A Form’s code however can’t access variables declared in another Form directly. It’s also possible to access a variable declared in one Form from within another, as long as one of these Forms “exposes” the variable by declaring it as Public.

Q.2 What are Activate and Deactivate Events? Ans.: When more than one Form is displayed, the user can switch from one to the other with the mouse or by pressing Alt+Tab. Each time a Form is activated, the Activate event takes place. The Forms application uses the

(Visual Basic) 27

Activate event to set the Form’s caption to a message indicating that this is the current Form : Private Sub Form_Activate() Form2.Caption= “Form2 Activated” End Sub Likewise, when a Form is activated, the previously active Form receives the Deactivate event, which the application uses to change the Form’s caption : Private Sub Form_Deactivate() Form2.Caption= “Form2 Inactive” End Sub

Q.3 What are ActiveX Controls? Ans.: This type of project is a feature of the professional edition. Active X control is used to develop own Active X controls. Active X control such as a Text Box or command button control is a basic element of the user interface. An Active X control, like a built in control, is an object that place on a form to enable or enhance a user’s interaction with an application. ActiveX controls usually have an OCX extension. Remote Data Service can use Active X controls to display recordest data on a client web page. The controls are of the followings types: (i) Text Box (ii) List Box (iii) Combo Box (iv) Scroll Bar (v) Timer (vi) Drive List Box

28

(vii) Status Bar (viii) TreeVview (ix) Check Box (x) Image List

Q.4 What is a Text Box Control? OR What are the most important characteristics of a Text Box Control? Ans.: The textbox is the primary mechanism for displaying and entering text and is one of the most common elements of the Windows user interface. The TextBox control is a small text editor that provides all the basic text- editing facilities: inserting and selecting text, scrolling the text if it doesn’t fit in the control’s area, and even exchanging text with other applications through the Clipboard. Basic Properties : Some of the properties that determine the appearance and, to some degree, the functionality of the Text Box control which can be set through the Properties window are as follows : Multi Line : This property determines whether the Text Box control will hold a single line or multiple lines of text. By default, the control holds a single line of text. Scroll Bars : This property controls the attachment of scrollbars to the Text Box control if the text exceeds the control’s dimensions. Single line textboxes can have a horizontal scroll bar so that the user can view any part of a long line of text. Multi-line textboxes can have a horizontal or a vertical scroll bar or both. Max Length : This property determines the number of characters the TextBox control will accept. Its default value is zero, which means the text may be of length, up to the control’s capacity limit.

(Visual Basic) 29

Text : The most important property of the Text Box control is the Text property, which holds the control’s text. This property is also available at design time so that you can assign some initial text to the control. At runtime, use this property to extract the text entered by the user or to replace the existing text by assigning a new value to the Text property. Password Char : Available at design time, the Password Char property turns the characters typed into any character you specify. If you don’t want to display the actual characters typed by the user, use this property to define the character to appear in place of each character the user types.

Q.5 Explain the basic properties of List Box and Combo Box Controls? Ans.: The List Box and Combo Box controls present lists of choices for the user to select. The List Box control occupies a user-specified amount of space on the Form and is populated with a list of items; the user can select one or more with the mouse. The Combo Box control also contains multiple items but occupies less space on the screen. The Combo Box control is an expandable List Box : the user can expand it to make a selection and retract it after the selection is made. Basic Properties : The List Box and Combo Box controls provide a few properties that can be set only at design time. They determine the basic functionality of the control and can’t be changed at runtime. Some of those properties are as follows : Multi Select : This property determines how the user can select the list’s items and must be set at design time. The Multi Select property’s values determine whether the user can select multiple items and which method will be used for multiple selection. Sorted : Items can be inserted by the application into a List Box or Combo Box control, but inserting them in the proper place and maintaining some sort of organization can be quite a task for the programmer. If you want the items to be always sorted, set the control’s Sorted property to True.

30

Style : This property determines the appearance of the control. Its value can be 0 or 1. Q.6 How can we manipulate the items in the List Box Control? Ans.: To manipulate a List Box control from within your application, you should be able to : Add items to the list Remove items from the list Access individual items in the list Add Item : To add items to the list, use the Add Item method. Its syntax is follows : List1.AddItem item, index The item parameter is the string to be added to the list, and index is its order. The index argument is optional; if you omit it, the string is appended to the bottom of the list. Remove Item : To remove an item from the list, you must first find its position in the list, which you must then supply to the Remove Item method. The syntax of the method is as follows : List1.RemoveItem index The index parameter is the order of the item to be removed, and this time, it’s not optional. Clear : The Clear method removes all the items from the control. Its syntax is simple : List1.Clear List Count : This is the number of items in the List. The items in the list can be accessed with an Index value, which goes from 0 to ListCount-1. List() : This is an array that holds the list’s items. The element List(0) holds the first element of the list, List(1) holds the second item, and so on up to List(ListCount-1), which holds the last item.

(Visual Basic) 31

List Index : This is the index of the selected item in the List. If multiple items are selected, List Index is the index of the most recently selected item. Selected : This property is an array, similar to the List property, with elements that have a True or a False value, depending on the status of the corresponding list element.

Q.7 What are the File Controls that are used in Visual Basic? Ans.: Three of the controls on the Toolbox let you access the computer’s file system. They are the Drive List Box, Dir List Box, and File List Box controls which are the basic blocks for building dialog boxes that display the host computer’s file system. The file controls are described as follows : Drive List Box : Displays the names of the drives within and connected to the PC. The basic property of this control is the Drive property, which sets the drive to be initially selected in the control or returns the user’s selection. Dir List Box : Displays the folders of the current drive. The basic property of this control is the Path property, which is the name of the folder whose sub-folders are displayed in the control. File List Box : Displays the files of the current folder. That basic property of this control is also called Path, and it’s the path name of the folder whose files are displayed. The three File controls aren’t tied to one another. If you place all three of them on a Form, you’ll see the names of all the drives in the Drive List Box. Selecting a drive in the Drive List Box control, however, doesn’t affect the contents of the Dir List Box. To connect the File controls, you must assign the appropriate values to their basic properties. The following is the minimum code you must place in the Drive List Box control’s Change event: Private Sub Drive1.Change()

32

Dir1.Path=Drive1.Drive End Sub Q.8 What are the general Graphics Controls? Ans.: One of the most interesting and fun parts of a programming language, is its graphics elements. In general, graphics fall into two major categories: vector and bitmap. Vector graphics are images generated by graphics commands such as the Line and Circle commands. Bitmap graphics are images that can be displayed on various controls and processed on a pixel-by-pixel basis. You can place graphics on three controls : Form Picture Box Image Box The main difference in these three controls is that the Image Box control is designed specifically for displaying images and not for creating new images or manipulating them. The other two controls provide drawing methods that let you design graphics at runtime. The methods for loading graphics on the various controls are simpler than creating graphics from scratch. You can place graphics on controls at design time and runtime. To load a graphic on a control at design time, you assign its to the Picture property of the control in the Properties window. To load a graphic on a control at runtime, use the Load Picture method as follows : Form1.Picture=LoadPicture(filename) The filename variable is the name of the file containing the graphic. The Image property, which is a pointer to a structure in memory where the bits of the image are stored.

Q.9 What is MSFlexGrid control? Or How MSFlexGrid is one of the most useful control of Visual Basic?

(Visual Basic) 33

Ans.: One of the most impressive controls of Visual Basic is the MSFlexGrid control. The MSFlexGrid control provides all the basic functionality for building spreadsheet applications. The MSFlexGrid control is an extremely useful tool for displaying information in a tabular form. You can place it on your Forms to present nicely organized data to the user. Basic Properties : The address of a cell is given by its Row and Col properties, whose values start at 0. Row 0 is the fixed title row, and column 0 is the fixed title column. To address the first non-fixed cell in the grid, you would use the following statements: Grid.Row=1 Grid.Col=1 You can examine the contents with a statement like : CellValue=Grid.Text or set its contents with a statement like : Grid.Text=”Monday” The simplest way to address a cell on the grid is by means of the TextMatrix property, which has the following syntax: Grid.TextMatrix(row, col) Another property is Fixed Cols, Fixed Rows properties. The most common value for these two properties is 1, which translates into one fixed row and one fixed column. The fixed row and column contain titles that can be assigned with any of the methods mentioned earlier or with the help of the Format String property. The Format String property can be assigned a string variable that sets up the control’s column width, alignments, and fixed row and column text. The Format String property is made up of segments separated by pipe characters ( | ). The user can change the width of columns and height of rows at runtime by dragging the column and row separators with the mouse. To disable

34

row and/or column resizing, set the Allow User Resizing property to one of the following values: Constant Value Resizing flexResizeNone 0 User can’t resize the cells flexResizeColumns 1 User can resize columns only flexResizeRows 2 User can resize rows only flexResizeBoth 3 User can resize columns and rows You can easily add data processing capabilities to the application. Inserting formulas won’t be easy, but you can calculate the average of a range of cells or normalize them. You can add functionality for displaying or entering data etc.

Q.9 What is a Multiple Document Interface? OR How we can create an MDI Application? Ans.: The Multiple Document Interface (MDI) was designed to simplify the exchange of information among documents all under the same roof. With an MDI application, you can maintain multiple open windows, but not multiple copies of the application. Data exchange is easier when you can view and compare many documents simultaneously. The main form, or MDI Form, is not duplicated, but its acts as a container for all other windows, and it’s called the parent window. The windows in which the individual documents are displayed are called child windows. Child windows, however, exist independently of the parent window. Most of the popular text editors are MDI applications too. Applications that implement an MDI interface can open multiple documents of the same type and use a common menu structure that applies to all open documents.

(Visual Basic) 35

An MDI application must have at least two Forms, the parent Form and one or more child Forms. The parent may not contain any controls. The parent Form can, and usually does, have its own menu. To create an MDI application, follow these steps : Start a new project and then choose Project-> Add MDI Form to add the parent Form. Set the Form’s caption to MDI Window. Choose Project-> Add Form to add a regular Form. Make this Form the child Form by setting its MDIChild property to True. To denote that this is a child Form, set its Caption property to MDIChild Form.

Q.10 Explain Windows API? Ans.: To do advanced programming, such as detecting mouse movements outside a Form, you need some additional functions. These functions are provided by the Win32 Application Programming Interface (API). All the Win32 API functions are available from within the Visual Basic environment. Many Windows applications use the API to some extent. The Win32 API consists of functions, structures, and messages that can be accessed to build Windows 95/98 and Windows NT applications. The four fundamental categories of the Windows API are : Windows Management (User) Graphics Device Interface (GDI) System Services (Kernel) Multimedia (MMSystem) The functions in these categories are implemented as DLLs (Dynamic Link Libraries) and can be called from any language. A DLL is loaded at runtime and it doesn’t need to be linked to your application. Actually, that’s where the name comes from: the contents of a DLL are linked to

36

your application dynamically at runtime, not at design time. Because the API functions are required for the proper operation of Windows itself, the DLLs are always available to your application. Windows Management provides the essential functions to build and manage your applications. All the basic input and output of the system goes through this layer of the Win32 API, including mouse and keyboard input and all processing of messages sent to your application. The Graphics Device Interface provides the functions you use to manage all supported graphical devices on your system, including the monitor and printer. In addition you can define fonts, pens, and brushes. Systems Services provides functions to access the resources of the computer and the . Multimedia functions allow you to play waveform audio, MIDI music, and digital video. □ □ □

(Visual Basic) 37

Chapter-8

Active X Components and Data Objects

Q.1 Explain the following terms : o ActiveX Components o ADO Ans.: ActiveX Components : An ActiveX component is a general term that encompasses three types of projects: ActiveX DLLs, ActiveX EXEs, and ActiveX controls. ActiveX controls are integrated into the Visual Basic IDE and they have a visible interface. While code components provide functionality similar to that of ActiveX controls, they aren’t as integrated with the development environment and they don’t have a visible interface. Another category of ActiveX components is the AcitveX document. ActiveX documents are applications that can be hosted in containers such as and the Office Binder. Code components are implemented in Visual Basic as Class Modules. A Class Module is a server, or an application that provides its services to client applications. When you create an object variable to access the properties and methods of a Class, you’re actually invoking an executable file(DLL or EXE) which runs in the background and waits to be contacted. Every time you set ore read a property value or call a method, this

38

executable activates, performs some actions, and optionally returns some results to your application. Servers cam be implemented as ActiveX EXE or ActiveX DLL components. The difference between the two lies in how the server is executed. An ActiveX DLL component is an in-process server. The DLL is loaded in the same address space as the executable that calls the server and runs on the same thread as the client. An ActiveX EXE component is a n out-of-process server that runs as a separate process. When a client application creates an object provided by an EXE server for the first time, the server starts running as a separate process. The benefit of DLLs is that they are faster. Out-of-process servers seem to be more efficient in resource allocation. ADO ( Active Data Objects) : Visual Basic supports several data access tools, with the Active Data Objects(ADO) being the most recent addition. Whereas the first Visual Basic data access tools (the Data Access objects) allowed programmers to access databases only, ADO can access all major databases and is Microsoft’s foundation for a universal technology for accessing all types of data in all environments. With ADO, your Visual Basic application sees three objects : A Connection object, which establishes a connection to the database, be it a local file or a remote SQL Server A Command object, which executes commands against the database A Record Set object, which holds the records retrieved from the database or the records to be updated on the database. Using the Active Data Objects : To use the Active Data Objects in an application, you must add a reference to the ADO Object library in the References dialog box. Follow these steps : (1) Open the Project menu. (2) Select Project-> References to open the References dialog box. (3) Check the Microsoft ActiveX Data Objects 2.0 Library option.

(Visual Basic) 39

After the ADO Library is added to a project, you can examine the objects it exposes and their members with the Object Browser. Establishing a Connection : To establish an explicit connection to a Data Source, declare a Connection variable with the statement: Dim ADOConn as new ADODB.Connection ADOConn.Open “DSN=AdvWorks;UID=xxx;PWD=xxx”

Q.2 Explain the following terms : (a) ADO (b) DAO Ans. : ADO : VB supports several data access tools, with the Active Data Objects(ADO). ADO can access all maj0or databases and is Microsoft’s foundation for a universal technology for accessing all types of data in all environments. I In VB applications have three objects with ADO : A Connection object, which establishes a connection to the database, be it a local file or a remote SQL Server A Command object, which executes commands against the database A Record Set object, which holds the records retrieved from the database or the records to be updated on the database. DAO : The Data Access Object is a structure of objects for accessing databases through code. All the functionality of the Data Control is also available to code, through the Data Access Object (DAO). The Data Control provides access to databases without any programming. One can set a few properties of the control and use regular controls such as textboxes to display the values of the fields in the database. This is the no- code approach to database programming, which is implemented in VB. □ □ □

40

Chapter 9 Menus

Q1. Explain the Menu Editor .

Menus can be attached only to Forms & we can design them with the Menu Editor. To use menu editor start a new Standard EXE project and when Form1 Appears in the design window, choose tools->menu editor to open the menu editor as shown in figure.

In Menu Editor window you can specify the structure of your menu by adding one command at a time.

Caption : This is the string that appears on the application’s menu bar.

Name : This is the name of the menu command. This property does not appear on the screen, but code uses it to a program the menu command.

(Visual Basic) 41

Index Field : Use the Index Field to create an array of menu commands. All the commands of the array have the same name and a unique index that differentiate them, just like array of controls.

Checked Field : Some menu commands acts as toggle & they are usually checked to indicate that they are on or unchecked to indicate that they are off.

Enabled Field : Some menu commands are not always available. This field is used to set menu command a enable control.

Visible Field : To remove a command temporarily from the menu,set the command’s visible property to false. Window Field : This option is used with MDI(Multiple Document Interface) application to maintain a list of all open windows.

Q2. What is Pop Up menu? How can we create a pop up menu.

Every windows application provides a context menu that a user can invoke by right clicking a Form or a control. This pop up menu is a regular menu but it is not anchored on the Form. It can be displayed anywhere on the Form.

Pop up menus are invoked with the PopUpMenu method. First, you create a menu as usual. Suppose we want to display Edit menu as a pop up menu then we have to add a line of code in control’s Mouse Up Event :

IF BUTTON+VBRIGHTBUTTON THEN POPUPMENU EditMenu

The PopUp menu method has the following syntax : popupMenu menuname, flags , x , y , boldcommand

42

Chapter-10

Object Oriented Programming

Q.1 What is an Object? An object is a self-contained piece of functionality that can be easily used, and re-used as the building blocks for a application. Objects consist of data variables and functions (called methods) that can be accessed and called on the object to perform tasks. These are collectively referred to as members. Q2 What is a Class? Much as a blueprint or architect's drawing defines what an item or a building will look like once it has been constructed, a class defines what an object will look like when it is created. It defines, for example, what the methods will do and what the member variables will be. Q3 Defining a Visual Basic Class Before an object can be instantiated we first need to define the class 'blueprint' for the object. In this chapter we will create a Bank Account class to demonstrate the concepts of Visual Basic object oriented programming. Begin by starting Visual Studio and creating a new Windows Application named vbObjects. Once the project opens, select the Project... menu and select Add class.... In the Add New Item dialog, name the new class file clsBankAccount.vb and click on the Add button. Visual Studio will now add a new tab to code area for the new class file containing the following class declaration: Public Class clsBankAccount End Class

(Visual Basic) 43

We have now defined a class. The next step is to add some functionality to the class. Q4 Creating Visual Basic Class Properties Class members or properties are essentially variables embedded into the class. Members can be Public or Private. Public members can be accessed from outside the object. Private members can only be accessed by methods contained in the class. This is the key to what is called data encapsulation. Object-oriented programming convention dictates that data should be encapsulated in the class and accessed and set only through the methods of the class (typically called getters and setters). We can now extend our BankAccount class to add member variables to hold the account name and number. True to the concept of data encapsulation we will be creating methods to access these values later, so will mark them as Private: Public Class clsBankAccount Private strAccountNumber As String Private strAccountName As String Private intBalance As Integer Private accountFee As Integer = 5 End Class

Now that we have defined the properties of our class, the next task is to define methods that will give us access to our data. Q5 Defining Class Methods Since we have declared our class data properties to be private, we need to provide methods which will give us access to those properties from our code. This is achieved using Get and Set methods. The syntax for get and Set methods is as follows: Public Property propertyName() As datatype Get

44

.... Code to return property value End Get Set(ByVal value As datatype ) .... Code to return property value End Get To demonstrate this we will add to our class to provide methods to get and set the account number and name. Note that after you type in the Public Property line of the declaration, Visual Studio automatically creates a template for the Get and Set methods, which should be filled in as follows: Public Class clsBankAccount Private strAccountNumber As String Private strAccountName As String Private intBalance As Integer Private accountFee As Integer = 5

Public Property AccountName() As String Get End Get Set(ByVal value As String)

End Set End Property

Public Property Balance() As Integer Get Return intBalance

(Visual Basic) 45

End Get Set(ByVal value As Integer) intBalance = value End Set End Property End Class Now that we have defined our getter and setter methods we can add our own method to perform a task. This is the same as writing a Visual Basic function. The purpose of our method will be to subtract the account fee from the current balance: Public Function subtractFee() As Integer intBalance = intBalance - intAccountFee Return intBalance End Function When called, the above function subtracts the account fee from the balance, assigns the new balance to the intBalance variable and returns the new total. Now that we have added some functionality to our class it is time to instantiate objects from this class blueprint.

46

Chapter-11 Automating

Q Explain Automating in VB? A Automate Microsoft office applications by using VBA, and when combined with VBScript they have a very powerful tool at their disposal.

Any Windows Programmer wanting to automate one of the Microsoft Office applications (such as Microsoft Word and ) has a very powerful tool at their finger tips - Visual Basic for Applications (VBA). If that programmer then combines VBA with VBScript then the automation of any office application becomes very easy; for example, a they may wish to:

populate cells in Microsoft Excel create Microsoft Word documents and fill them with text

All this can be achieved by running a single VBScript program.

Accessing a Microsoft Office Application

All Microsoft Office applications are accessed in the same way - by using the CreateObject method - this creates a new instance of the Microsoft application, for example Word:

Dim Word Set Word = CreateObject ("word.application") or Excel:

Dim Excel Set Excel = CreateObject ("excel.application")

However, how the applications are used are completely different.

(Visual Basic) 47

Making the Microsoft Application Visible

It's worth noting that VBA and VBScript will keep the Microsoft application invisible by default - this is useful for hiding complicated tasks from the user, but for the programmer it's more useful to be able to see what's going on while developing the application or testing it (and then to allow the user to see the end result). Fortunately it's just a matter of setting the application's visible property, for example: excel.visible = True or: word.visible = True

Obviously the visibility would be set at the start of the process for development and testing, but at the end for user visibility. However, that is where the similarity ends - the process of updating the cells in Excel is very different to the process of updating a Word document's body.

Automating Excel with VBA and VBScript

The first job for VBScript to do in Excel is to create a new workbook:

Dim workbook set workbook = excel.workbooks.add

And the next job is to access one of the document's worksheets:

Dim worksheet set worksheet = excel.Sheets(1) 'The first worksheet

Now each cell can be accessed individually:

Dim row, column column = 1 ' Column A row = 2 worksheet.Cells(row, column).Value = 21

48

It's worth noting that the value may contain numbers, text or formulae.

Automating Word with VBA and VBScript

Word works with documents rather than worksheets and so the process starts with creating a new document: word.documents.add

And word works with selections rather than cells:

Set Selection = Word.Selection Selection.Font.Underline = 1 Selection.Font.Size = 20 Selection.TypeText "Automating Word" Selection.TypeParagraph Selection.TypeParagraph

This code:

accesses the application's text selection underlines the text makes the text bigger (since this will be the title for the document) writes text to the document using the typetext method adds paragraph breaks with the typeparagraph method

And then, before carrying on, the underline can be turned off and the text made smaller:

Selection.Font.Underline = 0 Selection.Font.Size = 12

From there on paragraphs can be added required:

Selection.TypeText _ "Automation is an excellent way of creating reports." Selection.TypeParagraph Selection.TypeText _

(Visual Basic) 49

"Automation can save a lot of time and effort for the user." Selection.TypeParagraph

At the end of the process the developer will have a simple vbs application that creates a complete Word document from scratch.

Declaring Variables for the Script

As always enforce variable declaration: option explicit

Then declare the variables that are going to be used by the script: dim word 'the Word application dim doc 'the Word document dim selection 'text selection dim fs 'the File system dim work_dir 'the directory for storing files dim folder, folders 'used when creating the new file dim i, j 'indexes for arrays

The variables in VBScript are not defined with a specific data type - by default they are all of the data type variant, but once the variables have been declared they can be populated (if the values are known at this point): work_dir = "C:\vba\word\"

Once any required variables have been loaded with data the programmer can turn to any objects that they may need access to.

Creating Objects

The programmer gains access to any OLE (Object Linking and Embedding) compliant applications though the createobject method. In this case access a Word application and the file system are required: set word = createobject("word.application")

50 set fs = createobject("Scripting.FileSystemObject")

The next stage is to start making use of these objects in the vbs script.

Creating a New Word Document

Once the Word application object has been initiated then a new document can be created and written to - and the process is very simple:

use the add method to create a new document access the document selection (the text) use the typetext method to write to the document use the typeparagraph method to add a paragraph break

And so the code will be something like: set doc = word.documents.add set selection = word.selection selection.typetext "An Automated Word Report" selection.typeparagraph

A programmer can create a complete report just by adding more paragraphs - perhaps from data stored in a database. However, where ever the information comes from, the next stage is to save the document to a folder somewhere on the network.

Creating a New Directory

VBScript has no in-built method for creating a folder (or even checking that a folder exists); however, this is where the programmer can make use of the FileSystemObject (FSO) initiated at the start of the script. First the FSO is used to check if the directory exists: if not fs.folderexists(work_dir) then

If the folder does not exist then it must be created - however this cannot be done in a single stroke; for example, in the case of C:\vba\word\

(Visual Basic) 51

C: must be present before the vba folder can exist the vba folder must exist before the word folder can be created

So the directory tree must be created folder by folder - progressing from the top layer to the bottom creating folders as they are required: folders = split (work_dir, "\") for i = 0 to ubound(folders) - 1 folder = "" for j = 0 to i folder = folder & folders(j) & "\" next if not fs.folderexists(folder) then fs.createfolder folder end if next end if

Once the folders are in place the document may be saved.

Saving a Word Document

Saving a Word document is very easy - the programmer only needs the saveas method: doc.saveas(work_dir & "testdoc.doc")

And with that the new Word document has been created - it's now just a matter of a little housekeeping.

Ending the Script

If all of the code is saved to a file (for example create_report.vbs) then a user can run it by double-clicking on the file icon in Windows Explorer; however, they will see not output - and that's because VBA keeps the file invisible by default. The developer, therefore, has two choices at this point - they can:

make the document visible to the user

52

close the Word application

To make the file visible the programmer would need to add the code: word.visible = True

Or to close Microsoft Word: word.Quit

And the programmer will also want to fully unload the FSO and the Word application (to ensure no memory leakage occurs): set fs = nothing set word = nothing

At this point, regardless of the script ending, the user will have brand new Word document in the specified folder - without having to type in a single word themselves.

(Visual Basic) 53

Chapter-12

Error Handling Q What is Error Handling A Error handling enables the programmer to attempt to recover (i.e., continue executing) from infrequent fatal errors rather than letting them occur and suffering the consequences (such as loss of application data). If an error is severe and recovery is not possible, the program can be exited "gracefully"-all files can be closed and notification can be given that the program is terminating. The recovery code is called an error handler. Q What are the types of Error A Types of Error Programming errors are generally broken down into three types: Design- time, Runtime, and Logic errors.

1) A Design-time error is also known as a syntax error. These occur when the environment you're programming in doesn't understand your code. These are easy to track down in VB.NET, because you get a blue wiggly line pointing them out. If you try to run the programme, you'll get a dialogue box popping up telling you that there were Build errors. 2) Runtime errors are a lot harder to track down. As their name suggests, these errors occur when the programme is running. They happen when your programme tries to do something it shouldn't be doing. An example is trying to access a file that doesn't exist. Runtime errors usually cause your programme to crash. If and when that happens, you get the blame. After all, you're the programmer, and you should write code to trap runtime errors. If you're trying to open a database in a specific location, and the database has been moved, a Runtime error will occur. It's your job to predict a thing like this, and code accordingly. 3) Logic errors also occur when the programme is running. They happen when your code doesn't quite behave the way you thought it would. A classic example is creating an infinite loop of the type "Do While x is greater than 10". If x is always going to be greater than 10, then the loop has no way to exit, and just keeps going round and round. Logic errors

54

tend not to crash your programme. But they will ensure that it doesn't work properly.

On Error statements Visual Basic uses to handle errors. It tells how a program installs and removes error handlers, and it explains some of the error handling code.

Use On Error

A Visual Basic program uses the On Error statement to register error handling code. This statement can take one of three forms:

On Error GoTo 0 On Error Resume Next On Error GoTo line

These forms tell Visual Basic what it should do when the program encounters an error. The three forms are described in the following sections.

On Error GoTo 0

On Error GoTo 0 is relatively straightforward. It simply cancels any currently installed error handler assigned by a previous On Error GoTo line or On Error Resume Next. If the program encounters an error after this statement executes, it crashes.

On Error Resume Next

On Error Resume Next makes the program ignore errors. When it encounters an error, the program continues execution after the statement that caused the error. When a program uses On Error Resume Next, it should check the Err object after every operation that might cause an error. If the value Err.Number is nonzero, the operation caused an error and the program can take special action. The program should check Err.Number immediately after the statement in question. Certain other actions reset the Err object and remove the previous error information.

(Visual Basic) 55

Many programs use On Error Resume Next when they present a common dialog to the user. The CommonDialog control's CancelError property indicates whether the control should raise an error if the user cancels the dialog. The following code fragment shows how a program can use CancelError to decide whether to continue an action such as loading a file.

' Generate an error if the user cancels. dlgOpenFile.CancelError = True

' Ignore errors for now. On Error Resume Next

' Present the dialog. dlgOpenFile.ShowOpen

' See if there was an error. If Err.Number = cdlCancel Then ' The user canceled. Do nothing. Exit Sub ElseIf Err.Number <> 0 Then ' Unknown error. Take more action. : End If

' Resume normal error handling.

On Error GoTo 0

On Error GoTo Line

The On Error GoTo line statement registers a new error handler. If the program encounters an error, it passes control to the error handler beginning at the indicated line number or label. The error handler can then take appropriate action.

The following code shows a simple error handler that catches unexpected errors and describes them to the user.

56

Private Sub DoSomething() ' Install the error handler. On Error GoTo UnexpectedError

' Do stuff. :

' Do not pass through into the error handler code. Exit Sub

UnexpectedError: ' Describe the error to the user. MsgBox "Unexpected error" & _ Str$(Err.Number) & _ " in subroutine DoSomething." & _ vbCrLf & _ Err.Description Exit Sub

End Sub

(Visual Basic) 57 Glossary

Active Server Page (ASP) A Web-based application containing a combination of HTML, ActiveX components, and VBScript code. Active Server Pages can be used to dynamically provide different content for different users when viewed through each user's Web browser.

ActiveX A set of technologies based on Microsoft's Component Object Model (COM) for creating reusable binary objects.

ActiveX control An object that can be placed on a form so that users can interact with applications. ActiveX controls have events, properties, and methods and can be incorporated into other controls. ActiveX controls have an .ocx file extension. application One or more software components that do some action or provide some service, a compiled Visual Basic project. Other examples of applications include Microsoft Visual Basic and Microsoft Word. Also known as a program. array An indexed group of related data. Elements within an array must be of the same data type (such as all integers or all strings), and each element has a unique, sequential index number. bound control A data-aware control attached to a database through a Data control. At runtime, when users manipulate the Data control by changing from one row of the database to the next, the bound control changes to display the data found in the columns of the new row. If users change the data stored in a row, the new data is saved to the database when the users switch to a new row. breakpoint A specific line within a block of code where program execution automatically stops (during runtime). Breakpoints are user selectable. You can toggled them on and off during design time by pressing F9. browser An application used to browse content on the Web. Browsers, such as Microsoft Internet Explorer, can show HTML pages, Active Server Pages, and various other types of content.

58 call To transfer control of an application to a different procedure. Procedures are sometimes called with the Call keyword. child object An object contained within another object (its parent). See object. class A template used to create user-defined objects. A class defines an object's properties and methods. All instances created from the class use the properties and methods defined by the class. class module A module that defines a class. See module. compile To prepare code for execution. In Visual Basic, code can be compiled into either P-code (which results in faster compilation) or native code (which results in faster execution). The type of compilation can be selected from the Compile page of the Project Properties dialog box. constant A variable or object whose value doesn't change. control array An indexed group of similar controls that are of the same type and have the same name. Individual elements within the control array are identified by a unique index number. data member Private variable of a class. Data members are seen only by the class that defines them. data provider A data source that exposes information for data access, such as Microsoft Jet, Microsoft SQL, or Oracle. design time The time spent creating forms and writing functions during the creation of an application. Forms and functions can be altered only during design time. See runtime. designer An object or application that's used as a basis for creating more advanced objects or applications.

DLL The acronym for dynamic link library. An executable file containing a set of functions that other applications can call during runtime. DLLs generally don't

(Visual Basic) 59 have a graphical user interface; instead, they're usually accessed by applications without user intervention.

Document Object Model (DOM) A method for storing information so that a document can display its content in a variety of in-place views. dynamic A changing object or expression. early binding A technique that an application uses to access an object. In early binding, objects are defined from a specific class. Early binding is often faster than late binding because the application doesn't have to interrogate the object at runtime to determine the object's properties and methods. In Visual Basic, early binding enables the AutoComplete features to work correctly. element A single member of an array. Each element of an array is assigned a unique index value, which is used to locate and manipulate specific elements in an array. encapsulation The act of placing code or data in a location, such as a module or control, that's isolated from the rest of an application. Encapsulation hides both the implementation details and the internal complexity of an object but still enables the application to use functions contained within it. event A signal fired by the operating system in response to a user action. For example, when a user clicks (and holds down) a mouse button, a MouseDown event is sent by the operating system. The active application intercepts this signal and executes the code attached to the MouseDown event. event-driven programming A method of programming in which blocks of code are run as users do things or as events occur while a program is running. This varies from procedural programming, in which code blocks are contained within a module and called from other procedures. event procedure The place in a project where code is written to respond to an event. Event procedures are named by joining the object name with the event name, such as cmdButton_Click().

60 focus The state in which an object can receive input from the mouse or keyboard. At any given time, only one object can have focus; this object is usually highlighted with a different color and contains the text cursor, where appropriate. form The basis of an application's graphical user interface. Forms contain objects with which users manipulate data and otherwise control an application.

Form Designer A part of the Visual Basic 6 Integrated Development Environment. You use the Form Designer to create an application's graphical user interface by placing objects on forms during design time. At runtime, objects appear where they have been placed on the forms.

Form Layout window A part of the Visual Basic 6 Integrated Development Environment (MDI version only). The Form Layout window is used to position an application's forms during design time, visually rather than through code. At runtime, forms appear where they have been placed in the Form Layout window.

Get A Visual Basic keyword, the part of a Property procedure that gets the value of a property. graphical user interface (GUI) A set of forms and objects that enable users to view and manipulate data and otherwise control an application. A graphical user interface is the part of the application that sits between users and an application's underlying procedures. high-level language A computer language, such as Visual Basic, that can simplify coding by enabling programmers to write code with highly developed functions and keywords. See also low-level language.

IDE The acronym for Integrated Development Environment. The IDE includes all the tools necessary to create applications with Visual Basic 6, such as the Form Layout window and the Object Browser. inheritance The act of passing property values from a class to objects created by the class.

(Visual Basic) 61 input box A dialog, created with the InputBox() statement, that waits for users to enter text or click a button. When users close an input box, a string containing the contents of the text box is returned to the calling procedure. instance A single object created from a class. Also, a variable is an instance of a data type.

Internet Information Server (IIS) Microsoft's network file and application server. IIS is primarily used to support transmission of HTML pages using the HTTP protocol.

Internet service provider (ISP) A company that provides access to the Internet via a dial-up or direct connection. interpreted language A language, such as Visual Basic, which doesn't enable compilation to native code. When an application created with an interpreted language is run, the application's code is passed through an interpreter, which modifies the code into a form the computer can understand and execute. late binding A method of using an object by an application. In late binding, objects are defined as Object. Late binding is slower than early binding because the application must interrogate the object to determine its properties and methods.

Let A Visual Basic keyword. The part of a Property procedure that assigns a value to a property. Also used to assign a value to a variable, such as Let x = 10. low-level language A computer language, such as machine language, that requires a programmer to write code with less developed instructions so that the computer can directly understand. menu A list of user-selectable items within a program. Also, a control used to add menus to an application. menu bar The part of the Visual Basic IDE, located directly below the title bar, that lets you select functions and commands included with the application. By using the Menu Editor, you can add menu bars to applications created with Visual Basic.

62 message box A dialog, created with the MsgBox() function, that displays a message for users. Message boxes include one or more command buttons that enable users to clear the dialog or respond with an answer to a query. A message box returns an Integer value describing which button was selected. method A procedure, associated with a class, that manipulates an object. For example, one method of a command button is SetFocus, which moves the focus to the command button that invoked the method. module A block of code saved as a file with the extension .bas. Modules contain declarations and may or may not contain procedures. object A discrete combination of code and data, such as a ListBox or CommandButton, that can be manipulated. Objects contain properties and methods and are defined by a class.

Object Browser A part of the Visual Basic IDE, the Object Browser enables you to see all the objects (and all the properties, methods, and events of each object) available for use on the system. To access the Object Browser, press F2, choose object-oriented programming (OOP) A programming style and a type of programming language that involves the use of software modules called objects to encapsulate data and processing.

Option Explicit A Visual Basic keyword, the use of which forces each variable or expression in an application to be defined with a specific data type through the use of the Dim, Private, Public, ReDim, or Static keywords. Using Option Explicit can help reduce the likelihood of typographical errors when typing the names of existing variables. If Option Explicit isn't used, undefined variables are automatically defined as Variants. procedural language A programming language, such as Visual Basic, in which data is manipulated by calling procedures rather than proceeding line by line through all code contained in the application. project A set of forms and modules that make up an application while it's being developed into an application.

(Visual Basic) 63

Properties window A part of the Visual Basic IDE. This window enables you to view and modify all the properties of a given object during design time. It's not available during runtime. protocol A formal set of rules that enable two computers to communicate (such as the HTTP or FTP protocols) or a set of rules used to define an action such as argument passing or creation of an object from a class. See File Transfer Protocol (FTP) and Hypertext Transfer Protocol (HTTP). prototype An application that simulates the behavior of another, more fully developed application. Visual Basic is often used as a prototyping tool, for example, to quickly develop a possible graphical user interface (GUI) for an application before the application is developed.

Public A Visual Basic keyword. Variables defined with the Public keyword can be seen by any procedure of any module contained in the application. If a public variable is defined within a class module, the object name must be specified to use the variable. recursion The process of a procedure calling itself. relational database A database file in which records can include pointers to other tables that contain some of the information required to describe the record. Relational databases can be a more efficient means of storing information. For example, a relational database of music CDs would require only one field to describe the contact information for the artist's fan club. This field would hold a pointer to another table containing the fan club information for every artist in the database. Contrast with flat-file database. runtime The time when the code is actually running during the creation of an application. Forms and functions can't be altered during runtime. See design time. scope An attribute of a variable or procedure that determines which sections of which modules recognize it. There are three levels of scope: public, module, and procedure. Variables declared with the Public keyword can be accessed by any module, whereas variables declared within a specific module (with the Private keyword) can be used only within that module. Variables declared within a procedure can be used only in that procedure.

64 scrollbar A window element that enables users to view more available data when all available data can't be displayed within an object at one time. server-side components In a Web-based application, the portions of the application located on and run by the server.

Set A Visual Basic keyword. The part of a Property procedure that sets a reference to an object. standard EXE A traditional executable application. A standard EXE is a self- contained application that doesn't expose objects to the system for use by other objects or applications. static variable A variable, defined with the Static keyword, that maintains its value between calls to different procedures.

String An alphanumeric data type.

Sub A procedure, beginning with Sub subname() and ending with End Sub, that doesn't return a value to the calling procedure when it's complete. subscript The index value of an element in an array. syntax The specific method by which functions or lines of code are written. Important elements of syntax might include spelling, spacing, and punctuation. toolbar A collection of buttons, contained in a strip or in a dedicated window, that enable users to control an application.

ToolBox A part of the Visual Basic 6 Integrated Development Environment (IDE). The ToolBox contains the objects and controls available for use in an application; objects are dragged from the ToolBox and added to forms during design time. traverse To move through records in a database, elements in an array, or data contained within an object.

(Visual Basic) 65 typecasting Explicitly converting a variable or expression from one data type to another. user control A subobject of a control. User controls are properties or methods that can be added to an object.

VBA The acronym for Visual Basic for Applications. Similar to but a subset of the Visual Basic language. VBA is the programming language included with programs such as Access and Excel. In these programs, VBA can be used to create macros.

VBScript A scripting language, similar to but a subset of the Visual Basic language, especially suited to be embedded into HTML files because it must be interpreted by a Web browser. VBScript enables objects to be added to Web pages to accomplish such tasks as password authentication or surveys for data collection.

Visual Basic runtime DLL One of a set of files required to run an application developed in Visual Basic. Automatically installed with Visual Basic, the runtime DLLs must be copied to any machine on which an application is deployed. watch A variable whose value is tracked during runtime. When a watch is set, it appears in the Watch window (part of the IDE). Watches are updated whenever a breakpoint is reached; thus, changes to values can be seen by placing breakpoints at specific events. wizard An application, or part of an application, that helps users complete a difficult task. For example, Visual Basic's Data Form Wizard consists of multiple steps, each asking for specific information required to create and bind a form to a database.

66

Objective 1. MSDN stand for : (a) Microsoft Developer Network Library (b) Microsoft Source Domain Name (c) Microsoft Directory Name (d) None of the above ( ) 2. ADO stand for : (a) Active Data Object (b) Access Data Object (c) Activex Data Object (d) None of the above ( ) 3. Database tools are added automatically to the toolbox when project is developed under : (a) Standard EXE (b) Data project (c) DHTML applications (d) Database applications ( ) 4. The form caption appears in the : (a) Status bar (b) Menu bar (c) Title bar (d) None of the above ( ) 5. Which object is used in additem() method to add new item : (a) List box (b) Text box (c) Combo box (d) Both (a) and (c) ( ) 6. A control array is : (a) group of similar elements (b) group of similar control (c) group of controls that have same name (d) None of the above ( ) 7. The extension of control file is : (a) .vbp (b) .ocx (c) .vbx (d) both (b) and (c) ( ) 8. COM stand for : (a) Computer Object Model (b) Component Object Model

(Visual Basic) 67

(c) Control Oriented Model (d) None of the above ( ) 9. RDO stand for : (a) Real Data Object (b) Radio Data Object (c) Remote Data Object (d) None of the above ( ) 10. When the form is first placed in memory using load statement or show method, the event triggered : (a) Load (b) Show (c) Activate (d) None of the above ( ) 11. Mouse down event takes place when : (a) Press the mouse button (b) Click the left mouse button (c) Mouse is moved over a control (d) All of the above ( ) 12. Which window is used to display list of all forms and modules in the application : (a) Project Window (b) Form Layout Window (c) Properties Window (d) Main Window ( ) 13. Visual Basic is used to develop the applications : (a) Real time (b) Graphic user interface (c) Menu driven (d) None of the above ( ) 14. If variables are not implicitly or explicitly typed, they are assigned the type by default : (a) Character (b) Integer (c) Variant (d) None of the above ( ) 15. Which key event occurs when a key is pressed : (a) Key type (b) Key up (c) Key enter (d) Key press ( )

68

16. Which of the following is a file control : (a) Drive list box (b) Dirlist (c) File list box (d) All of the above ( ) 17. We can create object at : (a) Design time (b) Run time (c) Both (a) and (b) (d) None of the above ( ) 18. The save picture statement supports : (a) BMP (b) GIF (c) JPG (d) All of the above ( ) 19. OLE stand for : (a) Object Linking and Embedding (b) Object Layering and Embedding (c) Object Linking and Enclosing (d) None of the above ( ) 20. DLL stand for : (a) Dynamic Link Library (b) Data Link Library (c) Defined Library List (d) None of the above ( ) 21. Event-driven languages are: (a) FORTRAN based (b)Are used to write procedural languages (c) OOP (d) Designed to make programming GUI easy 22 IDE is: (a) Independent Development Enterprise (b) A development environment for machine language (c) A software project management tool (d) An Integrated Development Environment for Visual Basic 23 Which of the following is not part of the IDE: (a) Code editor window (b) Properties window (c) General window (d) Form layout window ( ) 24 The application name always appears in the: (a) Properties window (b) Title bar

(Visual Basic) 69

(c) Code window (d) Intermediate window ( ) 25 The color of a button is: (a) One of its properties (b) Not updateable (c) Defined in the project (d) Defined in the Intermediate window ( ) 26 Code is: (a) Updateable in the form editor (b) Instructions (c) Seldom used (d) An object ( ) 27 Controls are: (a) Code (b) Part of the menus (c) Rules (d) Objects ( ) 28 In the IDE, which of following is used to design the layout of an application? (a) Form Designer window (b) Project Explorer window (c) Context Menu (d) Form Layout window ( ) 29 The location of the form on the desktop during execution is determined by the: (a) Form Designer window (b) Project Explorer window (c) Context Menu (d) Form Layout window ( ) 30 The Object Browser: (a) Displays the command buttons and textboxes, etc. (b) Shows frequently used shortcuts as objects (c) Is a Context Menu (d) Displays the object libraries and their combinations of data and code ( ) 31 The location of the form on the desktop during execution is determined by the: (a) Form Designer window (b) Project Explorer window (c) Context Menu (d) Form Layout window ( ) 32 The first procedure-oriented language was: (a) FORTRAN (b) BASIC (c) COBOL (d) ADA ( ) 32 Object Oriented languages:

70

(a) Are procedural languages (b) Are task oriented (c) Are based on actions happening to objectsn (d) Are natural language techniques ( ) 33 Visual Basic projects are identified by a: (a) “.vbp” suffix (b) “.mak” suffix (c) “.vbg” suffix (d) All the above ( ) 34 Visual Basic forms are identified by a: (a) “.mak” suffix (b) “.frm” suffix (c) “.for” suffix (d) A special icon ( ) 35 To run an application in Visual Basic: (a) Use the Project Menu to select Run (b) Use the File Menu (c) Click on the start button (blue arrow) (d) None of the above 36 To exit Visual Basic: (a) Click Alt-Q (b) Use the File Menu to select Quit (c) Use the Window Menu to select Exit (d) Click on the diskette icon ( ) 37 The reference library of Visual Basic books is called: (a) MSDN Library (b) Help Library (c) Contents (d) Topic pane ( ) 38 Which are the standard prefixes for the Button and Combo box controls respectively? (a) btn and chb (b) btn and cbo (c) bto and chb (d) bto and cbo ( ) 39. An object is composed of: (a) properties. (b) methods. (c) events. (d) All of the above. ( ) 40. Which statement about objects is true? a.) One object is used to create one class. b.) One class is used to create one object.

(Visual Basic) 71

c.) One object can create many classes. d.) One class can create many objects. 41. Which is not a property of the Common control class? (a) Show (b) BackColor (c) Font (d) ForeColor ( ) 42. Which property determines whether a control is displayed to the user? (a) Hide (b) Show (c) Visible (d) Enabled ( ) 43. The CancelButton property belongs to which object? (a) Button (b) Form (c) Label (d) TextBox ( ) 44. In event-driven programming an event is generated by: (a) the system. (b) a user’s action (c) the program itself. (d) All of the above. ( ) 45 Which is a valid statement for declaring a variable? (a) Const Form As Integer (b) Const myForm As Integer (c) Dim Form As Integer (d) Dim myForm As Integer ( ) 46. Which TextBox method does not use the clipboard? (a) Clear (b) Copy (c) Cut (d) Paste ( ) 47. Which is not a valid Exit statement? (a) Exit Do (b) Exit For (c) Exit Form (d) Exit Select ( ) 48. An Exception is another name for a: (a) compile error (b) logic error (c) runtime error (d) superficial error ( ) 49. Which statement is used to identify an external procedure to visual basic? (a) Declare (b) Dim (c) Public (d) All of the above 50. The scope of a variable refers to: a.) the length of the variable.

72 b.) the name of the variable. c.) the accessibility of the variable. d.) the datatype of the variable.

1=A 2=A 3=B 4=D 5=D 6=C 7=B 8=B 9=C 10=C 11=D 12=A 13=B 14=C 15=D 16=D 17=B 18=D 19=A 20=A 21=D 22=D 23=C 24=B 25=A 26=B 27=D 28=A 29=D 30=D 31=D 32=C 33=D 34=B 35=C 36=A 37=A 38=B 39=E 40=D 41=A 42=C 43=B 44=D 45=D 46=A 47=C 48=C 49=A 50=C

(Visual Basic) 73 Bibliography

Books referred-

1. Petroutsos Evangelos : Mastering Visual Basic; BPB Publications;. 2. Norton's Peter: Guide to Visual Basic; Techmedia;. 3. Kurata Deborah : Doing Objects in Visual Basi; Techmedia; 4. Mastering database Programming with Visual Basic 6 by Petroutsos

Websites Referred http://www.techotopia.com/index.php/Visual_Basic_Essentials http://visualbasic.freetutes.com http://www.visualbasicbooks.com http://www.vbtutor.net/vb6/vbtutor.html