INTRODUCTION VB 6.0

INTRODUCTION
What is Visual Basic?

Visual Basic is a tool that is used by more number of developers than any other tool. Visual Basic has been the choice of developers for various good reasons. So many small and big companies use Visual Basic for developing various types of applications.  One of the key factors that contributed to the success of Visual Basic is its ease of use.

When Windows Programming (writing programs that run on Windows OS) was very tough and was confined only to a few people who were good in C and C++, Visual Basic hit the market and changed the way one would look at windows programming. Visual Basic made windows programming so simple, even a novice started writing one or two programs for windows in Visual Basic.

The overall approach to VB programming is:
1.   Create a user interface that is appropriate to the particular application at hand.
2.   Add a group of basic instructions to carry out the actions associated with each of the controls.
Visual Basic: It is an object oriented programming language or development system for creating applications that run under any of the Microsoft Windows environments.
·    It is the developers choice
·    Using VB so many variety of applications can be developed.
·    It is user friendly

Event and Event Procedures

·    The program’s response to an action taken by the user is referred to as an event.
·    The group of basic commands that brings about this response is called as an event procedure.

Object Related Concepts in VB

·    Forms: In visual basic, a window is called as a form. Each form includes a title bar at the top.
·    Controls: The icons with which the user interacts are called controls. The user activate a control to produce an event.
·    Objects: Forms and controls are referred to collectively as objects. Most objects are associated with events, objects may include their own unique event procedures. Objects are associated with their own properties & methods.
·    Properties: It defines their appearance or behaviour
·    Methods: Some objects also include special program statements called methods. It is the predefined action affecting the associated object.

Starting Visual Basic IDE

Visual Basic provides IDE (Integrated Development Environment), which provides developers all the tools they need to develop applications.

To start Visual Basic from Windows:

Click Start on the Task bar.
Select Programs.
Select Microsoft Visual Studio 6.0 and then Microsoft Visual Basic 6.0
The Visual Basic Environment
You can choose to start a new project, open an existing project or select a list of recently opened programs. A project is a collection of files that make up your application. There are various types of applications we could create, however, we shall concentrate on creating Standard EXE programs (EXE means executable program). Now, click on the Standard EXE icon to go into the actual VB programming environment.
The Visual Basic Environment consists of the:
·      A  Blank Form for you to design your application's interface.
·      The Project window, which displays the files that are created in your application.
·      The Properties window, which displays the properties of various, controls and objects that are created in your applications.
It also includes a Toolbox that consists of all the controls essential for developing a VB Application. Controls are tools such as text box, command button, label, combo box, picture box, image box, timer and other objects that can be dragged and drawn on a form to perform certain tasks according to the events associated with them. Additional objects can be added by clicking on the project item on the menu and click on components on the drop-down list, then select those controls you need to use in your program
Components of IDE:

VB’s IDE has a collection of components. Each component has a specific task. The following are VB IDE Components:

Menu Bar
Displays the commands you use to work with Visual Basic. Besides the standard File, Edit, View, Window, and Help menus, menus are provided to access functions specific to programming such as Project, Format, or Debug.

Context Menus
Contain shortcuts to frequently performed actions. To open a context menu, click the right mouse button on the object you're using. The specific list of shortcuts available from context menus depends on the part of the environment where you click the right mouse button. For example, the context menu displayed when you right click on the Toolbox lets you display the Components dialog box, hide the Toolbox, dock or undock the Toolbox, or add a custom tab to the Toolbox. Context menu is also called as popup menu.

Toolbars
Provide quick access to commonly used commands in the programming environment. You click a button on the toolbar once to carry out the action represented by that button. By default, the Standard toolbar is displayed when you start Visual Basic. Additional toolbars for editing, form design, and debugging can be toggled on or off from the Toolbars command on the View menu.
Toolbars can be docked beneath the menu bar or can "float" if you select the vertical bar on the left edge and drag it away from the menu bar.

Toolbox
Provides a set of tools that you use at design time to place controls on a form. In addition to the default toolbox layout, you can create your own custom layouts by selecting Add Tab from the context menu and adding controls to the resulting tab.

Project Explorer Window
Lists the forms, modules and other components of the current project. A project is a collection of files, which you use to build an application.

Properties Window
Lists the property settings for the selected form or control. A Property is a characteristic of an object, such as size, caption, or color.

Object Browser
Lists objects available for use in your project and gives you a quick way to navigate through your code. You can use the Object Browser to explore objects in Visual Basic and other applications, see what methods and properties are available for those objects, and paste code procedures into your application.

Form Designer
Serves as a window that you customize to design the interface of your application. You add controls, graphics, and pictures to a form to create the look you want. Each form in your application has its own form designer window.

Code Editor Window
Serves as an editor for entering application code. A separate code editor window is created for each form or code module in your application.  Code window contains two dropdown list boxes, one for the list of objects in the form and another for available events of the selected object.

Form Layout Window
The Form Layout window allows you to position the forms in your application using a small graphical representation of the screen.

Immediate, Locals, and Watch Windows
These additional windows are provided for use in debugging your application. They are only available when you are running your application within the IDE.

Environment Options
Visual Basic provides a great deal of flexibility, allowing you to configure the working environment to best suit your individual style. You can choose between a single or multiple document interface, and you can adjust the size and positioning of the various Integrated Development Environment (IDE) elements. Your layout will persist between sessions of Visual Basic.


FORM
 Properties
 Form layout window
Tool Box

 A Visual Basic application is developed in three steps:

Create the user interface
Change properties
Write code
In the first step, we lay down control on the form and arrange them in the way we want.
In the second step, we change properties of controls and form to required objects.
In the third step, we write code for events.

Creating user interface
Our first application needs only one control – command button. Select command button in Toolbox and drag it and drop it on the form at the required location. Here are the required steps.
Invoke Form designer by double clicking on Form in Project Explorer, if designer is not already displayed. (or)
Select the icon for command button in Toolbox. The background of the icon becomes gray.
Go to form. The moment you enter into the form the mouse pointer changes to cross hair (plus sign).
Place the cross hair at the bottom of the form and drag mousepointer  (means hold down the left button and move the mouse pointer). While you move mousepointer you see a gray rectangle.
Once you dragged from the required location to required location, release the mouse button.
Control appears at that location with the size that is same as the gray rectangle.

Changing properties
Once the required controls are placed on the form, we have to change the properties of the control to get the required look and behavior.
Each control has a collection of properties. Each property represents an attribute of the control. For example, Name property identifies the name used to reference the control in the code and so on.
To change the properties of control (and form), we have to use Properties Window, which allows you to change properties by displaying properties on left and values on the right.
The following are the steps required to change properties of command button and form.

Invoke Properties Window for command button by pressing F4 after selecting command button.
In Properties Window select Caption property and enter  “ &Exit “ (without quotes) on the right of it.
Select Name property and change it to cmdExit.
Then click anywhere on the form (to unselect command button) and press F4 to invoke Properties Window for Form.
Select Caption property and change it to First Visual Basic Application.
Select Name property and change it to frmFirst.

Writing Code
The final step is writing code for events. Just before we proceed further, let us understand the event to which we need to respond.
We need to respond to Click event of the form, as we want to display the name whenever user clicks on the form.
We need to respond to Click event of command button (cmdExit) as we have to terminate program when user clicks on the command button.
Here are the steps to write code for these two events.

Select form and press F7 to invoke code window.
-or-
Double click on the form to invoke code window.
Code window displays Load event on the right (as that is default event for form). Select Click event using the dropdown list and write code as shown in figure 1.6.


Double click on the command button to invoke code window. By default Click event is selected.  Write the following code.
Print is a statement that displays the given data on the form.

Saving Project
When you save a project, Visual Basic prompts you to enter filenames in which it has to save components, such as Form of the project and then the project.
Each component is save in a separate file and project is saved in a separate file.
Save the project using following steps.

Select File->Save Project 
Or
Click on Save Project icon in Toolbar.
When Visual Basic prompts you to enter filename for form, select directory in which you want to save the form file and enter filename. By default the name of the form will be the name of the file. The default extension is .FRM (form).
After entering file name Click on Save button to save form.
Then it prompts you to enter name of the file for project.
Enter a filename. Visual Basic adds extension .VBP (Visual Basic Project).
Click on Exit button to terminate application.

Test Run
Now, run the application using any of the following methods.

By pressing F5
By clicking on Start icon in Toolbar
By selecting Run menu and Start option.

VB FUNDAMENTALS

There are many types of data we come across in our daily life. For example, we need to handle data such as names, addresses, money, date, stock quotes, statistics and etc everyday. Similarly in Visual Basic, we are also going to deal with these kinds of data. However, to be more systematic, VB divides data into different types.

Types of Visual Basic Data Types

Numeric Data
Numeric data are data that consists of numbers, which can be computed mathematically with various standard operators such as add, minus, multiply, divide and so on. In Visual Basic, the numeric data are divided into 7 types,
Type               Storage           Range of Values
Byte                1 byte              0 to 255
Integer             2 bytes             -32,768 to 32,767
Long                4 bytes             -2,147,483,648 to 2,147,483,648
Single              4 bytes             -3.402823E+38 to -1.401298E-45 for negative values
1.401298E-45 to 3.402823E+38 for positive values.

Double                        8 bytes             -1.79769313486232e+308 to -4.94065645841247E-324 for
negative values

4.94065645841247E-324 to 1.79769313486232e+308 for positive values.
Currency         8 bytes             -922,337,203,685,477.5808 to 922,337,203,685,477.5807
Decimal           12 bytes           +/- 79,228,162,514,264,337,593,543,950,335 if no decimal
is use
+/- 7.9228162514264337593543950335 (28 decimal
places).
Non-numeric Data Types
Data Type                              Storage                       Range
String(fixed length)      Length of string           1 to 65,400 characters
String(variable length)  Length + 10 bytes        0 to 2 billion characters
Date                              8 bytes                          January 1, 100 to December 31, 9999
Boolean                        2 bytes                          True or False
Object                           4 bytes                          Any embedded object
Variant(numeric)          16 bytes                        Any value as large as Double
Variant(text)                 Length+22 bytes          Same as variable-length string
Managing Variables

Variables are like mail boxes in the post office. The contents of the variables changes every now and then, just like the mailboxes. In term of VB, variables are areas allocated by the computer memory to hold data. Like the mail boxes, each variable must be given a name. To name a variable in Visual Basic, you have to follow a set of rules.

Variable Names

The following are the rules when naming the variables in Visual Basic
·      It must be less than 255 characters
·      No spacing is allowed
·      It must not  begin with a number
·      Period is not permitted
Valid Name                                                Invalid Name
My_Car                                                       My.Car 
ThisYear                                                      1NewBoy
Long_Name_Can_beUSE                          He&HisFather                  *& is not acceptable
Declaring Variables
In Visual Basic, one needs to declare the zvariables before using them by assigning names and data types. They are normally declared in the general section of the codes' windows using the Dim statement.
The format  is as follows:

Dim variableName as DataType

Example:
Dim password As String
Dim yourName As String
Dim firstnum As Integer
Dim secondnum As Integer
Dim total As Integer
Dim doDate As Date

You may also combine them in one line , separating each variable with a comma, as follows:
Dim password As String,  yourName As String, firstnum As Integer,.............

If data type is not specified, VB will automatically declare the variable as a Variant.
For string declaration, there are two possible formats, one for the variable-length string and another for the fixed-length string. For the variable-length string, just use the same format as above. However, for the fixed-length string, you have to use the format as shown below:

Dim VariableName as String * n, where n defines the number of characters the string can hold.
Example:
Dim yourName as String * 10
yourName can holds no more than 10 Characters.  

Assigning Values to Variables

After declaring various variables using the Dim statements, we can assign values to those variables. The general format of an assignment is
Variable=Expression

The variable can be a declared variable or a control property value. The expression could be a mathematical expression, a number, a string, a Boolean value (true or false) and etc. The following are some examples:
firstNumber=100
secondNumber=firstNumber-99
userName="John Lyan"
userpass.Text = password
Label1.Visible = True
Command1.Visible = false
Label4.Caption = textbox1.Text
ThirdNumber = Val(usernum1.Text)
total = firstNumber + secondNumber+ThirdNumber  

Suffixes for Literals
Literals are values that you assign to a data. In some cases, we need to add a suffix behind a literal so that VB can handle the calculation more accurately. For example, we can use num=1.3089# for a Double type data. Some of the suffixes are displayed below
                        Suffix  Data Type                                          Data Types
                                    &                                                         Long
                                    !                                                           Single
                                    #                                                          Double
                                    @                                                        Currency
In addition, we need to enclose string literals within two quotations and date and time literals within two # sign. Strings can contain any characters, including numbers. The following are few examples:
memberName="Turban, John."
TelNumber="1800-900-888-777"
LastDay=#31-Dec-00#
ExpTime=#12:00 am#


Library Functions

Visual Basic contains numerous library functions that provide a quick and easy way to carry out many mathematical operations, manipulate strings, and perform various logical operations.
Function                                 Application                            Purpose
Abs                                          y=Abs(x)                                 return the absolute value of x
CDbl,Cint,Csng                      y=CInt(x)                                convert x to appropriate data
type
Chr                                          y=Chr(x)                                 return the numerical value of
x
Cos                                          y=Cos(x)                                 return the cosine of x
Date                                        y=Date                                                return the current system
date
Exp                                          y=Exp(x)                                 return the value of e to the x
power
Format                                     y=Format(x,”frmt str”)           return the value of x in a
format
Lcase                                       y=Lcase(x)                              return the lowercase
equivalent of x
Len                                          y=Len(x)                                 return the length of x
Log                                          y=Log(x)                                 return the log of x
mid                                          y=Mid(x,n1,n2)                       return the middle n2 chars of
the string x, beginning
with char number n1.
Rnd                                         y=Rnd                                     return a random number
Sqr                                           y=sqr(x)                                   return the sqrt of x
Str                                           y=str(x)                                   return a string whose chars
comprise the value of x
Ucase                                      y=Ucase(x)                              return the uppercase
equivalent of x
Val                                          y=val(x)                                   return a numeric value
corresponding
to the string x

OPERATORS
An operator is a symbol or a word that performs an operation. Depending upon the type of operation an operator performs, operators are classified as follows:

Category                        What it does?
Arithmetic Operators      Used to perform arithmetic operations such as addition,
                                        subtraction etc.
Relational Operators       Used in forming conditions used to compare values.
Logical Operators           Used to combine conditions or to negate condition
Assignment Operator      Used to assign a value to a variable
Concatenation Operator Used to concatenate ( join) two strings

Arithmetic Operators
The following are various arithmetic operators.

Operator    What it does?
+                 Addition
-                  Subtraction. This operator can also be used as unary operator. In this case, it
                    negates the sign of the number. For example, if variable A contains –10 then –A
                    will result in 10(positive 10).
/                   Division
*                  Multiplication
Mod            Modulus. Returns the remainder of the division.
\                   Integer Division. Returns only integer portion of the quotient.

Relational Operators
The following are the operators used to form conditions. The result of any expression using a relational operator will be either True or False.

Operator    Meaning
<                 Less than
>                 Greater than
<=               Less than or equal to
>=               Greater than or equal to
=                 Equal to
<>               Not equal to

Logical Operators
These operators are used to combine two relational operators. The following are the available logical operators.

Operator        Meaning
AND            Both the conditions must be true for the entire condition to be true.
OR               If either condition is true then the entire condition is true.
NOT             Reverses the result of the condition.
XOR              The entire condition is true only when either of the conditions is true. If
both the conditions are true or if both the conditions are false then entire condition is false.
EQV             The entire condition is true only when both the conditions are either true or
                     false.
IMP              The entire condition is true except when the first condition is true and the
                     second condition is false.


CONTROL STRUCTURES

Control Statements are used to control the flow of program's execution. Visual Basic supports control structures such as if... Then, if...Then ...Else, Select...Case, and Loop structures such as Do While...Loop, While...Wend, For...Next etc method.

If...Then selection structure
The If...Then selection structure performs an indicated action only when the condition is True; otherwise the action is skipped.
Syntax of the If...Then selection
If <condition> Then
statement
End If
e.g.: If average>75 Then
txtGrade.Text = "A"
End If

If...Then...Else selection structure
The If...Then...Else selection structure allows the programmer to specify that a different action is to be performed when the condition is True than when the condition is False.
Syntax of the If...Then...Else selection
If <condition > Then
statements
Else
statements
End If
e.g.: If average>50 Then
txtGrade.Text = "Pass"
Else
txtGrade.Text = "Fail"
End If

Nested If...Then...Else selection structure
Nested If...Then...Else selection structures test for multiple cases by placing If...Then...Else selection structures inside If...Then...Else structures.
Syntax of the Nested If...Then...Else selection structure
You can use Nested If either of the methods as shown above Method 1
If < condition 1 > Then
statements
ElseIf < condition 2 > Then
statements
ElseIf < condition 3 > Then
statements
Else
Statements
End If
Method 2
If < condition 1 > Then
statements
Else
 If < condition 2 > Then
statements
 Else
If < condition 3 > Then
statements
Else
Statements
End If
 End If
EndIf

e.g.: Assume you have to find the grade using nested if and display in a text box
If average > 75 Then
 txtGrade.Text = "A"
ElseIf average > 65 Then
 txtGrade.Text = "B"
ElseIf average > 55 Then
 txtGrade.text = "C"
ElseIf average > 45 Then
 txtGrade.Text = "S"
Else
 txtGrade.Text = "F"
End If

Select...Case selection structure
Select...Case structure is an alternative to If...Then...ElseIf for selectively executing a single block of statements from among multiple block of statements. Select...case is more convenient to use than the If...Else...End If. The following program block illustrate the working of Select...Case.
Syntax of the Select...Case selection structure
Select Case Index
Case 0
Statements
Case 1
Statements
End Select
e.g.: Assume you have to find the grade using select...case and display in the text box
Dim average as Integer
average = txtAverage.Text
Select Case average
Case 100 To 75
 txtGrade.Text ="A"
Case 74 To 65
 txtGrade.Text ="B"
Case 64 To 55
 txtGrade.Text ="C"
Case 54 To 45
 txtGrade.Text ="S"
Case 44 To 0
 txtGrade.Text ="F"
Case Else
MsgBox "Invalid average marks"
End Select

Looping
Visual Basic allows a procedure to be repeated as many times as long as the processor could support. This is generally called  looping .

Do Loop
The format are
a)   Do While condition
            Block of one or more VB statements
      Loop
b)   Do
            Block of one or more VB statements
      Loop While condition
c)    Do Until condition
              Block of one or more VB statements
       Loop
d)    Do
             Block of one or more VB statements
       Loop Until condition

Example
       Do while counter <=1000
             num.Text=counter
             counter =counter+1
       Loop
* The above example will keep on adding until counter >1000.

The above example can be rewritten as
        Do
               num.Text=counter
               counter=counter+1
       Loop until counter>1000
 
Looping with While-Wend
While-wend
The format are :
While logical expression
Executable statements
Wend
Ex;
While n<=0
            Print “hai”
Wend

For....Next Loop       
The format is:
For counter=startNumber to endNumber (Step increment)
    One or more VB statements
Next counter
Example:
(a)       For  counter=1 to 10
            display.Text=counter
            Next counter
(b)        For counter=1 to 1000 step 10
           counter=counter+1
            Next counter
(c)       For counter=1000 to 5 step -5
            counter=counter-10
           Next counter

NAME PROPERTY

Each control and form in a Visual Basic project has a name, which is used to refer to the object.
Whenever you access a control in the code, you use the name of the control. Name of the control is set using Name property of the control.
Caption property contains the text to be displayed to the user and Name property contains the name that is to be used in the code to refer to the control.
The name of the control is important because it is used even in the event procedures of the control.  The name of the event procedure is formed using the name of the control and the name of the event. For example, if name of the control is cmdQuit and event is Click, then the name of event procedure will be cmdQuit_Click.
While giving name to a control, we use a prefix to identify the type of the control. Giving prefix is purely a convention and not a rule in any way.  The following is the table shows the standard naming conventions followed in Visual Basic.

CONTROLS

The Control Properties
Before writing an event procedure for the control to response to a user's input, you have to set certain properties for the control to determine its appearance and how it will work with the event procedure. You can set the properties of the controls in the properties window or at runtime.

·      You should set the Caption Property of a control clearly so that a user knows what to do with that command. For example, in the calculator program, all the captions of the command buttons such as +, - , MC, MR are commonly found in an ordinary calculator, a user should have no problem in manipulating the buttons.
·      A lot of programmers like to use a meaningful name for the Name Property may be because it is easier for them to write and read the event procedure and easier to debug or modify the programs later. However, it is not a must to do that as long as you label your objects clearly and use comments in the program whenever you feel necessary. T
·      One more important property is whether the control is enabled or not.
·      Finally, you must also considering making the control visible or invisible at runtime, or when should it become visible or invisible.
3.2 Handling some of the common controls
3.2.1 The Text Box   
The text box is the standard control that is used to receive input from the user as well as to display the output. It can handle string (text) and numeric data but not images or pictures. String in a text box can be converted to a numeric data by using the function Val(text). The following example illustrates a simple program that processes the inputs from the user.
 Example 3.1
In this program, two text boxes are inserted into the form together with a few labels. The two text boxes are used to accept inputs from the user and one of the labels will be used to display the sum of two numbers that are entered into the two text boxes. Besides, a command button is also programmed to calculate the sum of the two numbers using the plus operator. The program use creates a variable sum to accept the summation of values from text box 1 and text box 2.The procedure to calculate and to display the output on the label is shown below.. 
Private Sub Command1_Click()
‘To add the values in text box 1 and text box 2
Sum = Val(Text1.Text) + Val(Text2.Text)
‘To display the answer on label 1
Label1.Caption = Sum
End Sub
 3.2.2 The Label    
The label is a very useful control for Visual Basic, as it is not only used to provide instructions and guides to the users, it can also be used to display outputs. One of its most important properties is Caption. Using the syntax label.Caption, it can display text and numeric data . You can change its caption in the properties window and also at runtime. 
 3.2.3 The Command Button 
The command button is a very important control as it is used to execute commands. It displays an illusion that the button is pressed when the user click on it. The most common event associated with the command button is the Click event, and the syntax for the procedure is
Private Sub Command1_Click ()
Statements
End Sub
3.2.4 The Picture Box 
The Picture Box is one of the controls that used to handle graphics. You can load a picture at design phase by clicking on the picture item in the properties window and select the picture from the selected folder. You can also load the picture at runtime using the LoadPicture method. For example, the statement will load the picture grape.gif into the picture box.
Picture1.Picture=LoadPicture ("C:\VB program\Images\grape.gif")
The image in the picture box is not resizable.
 3.2.5 The Image Box
The Image Box is another control that handles images and pictures. It functions almost identically to the picture box. However, there is one major difference, the image in an Image Box is stretchable, which means it can be resized. This feature is not available in the Picture Box. Similar to the Picture Box, it can also use the LoadPicture method to load the picture. For example, the statement loads the picture grape.gif into the image box.
Image1.Picture=LoadPicture ("C:\VB program\Images\grape.gif")
 3.2.6 The List Box
The function of the List Box is to present a list of items where the user can click and select the items from the list. In order to add items to the list, we can use the AddItem method. For example, if you wish to add a number of items to list box 1, you can key in the following statements
Example 3.2
Private Sub Form_Load ( )
List1.AddItem “Lesson1”
List1.AddItem “Lesson2”
List1.AddItem “Lesson3”
List1.AddItem “Lesson4”
End Sub
The items in the list box can be identified by the ListIndex property, the value of the ListIndex for the first item is 0, the second item has a ListIndex 1, and the second item has a ListIndex 2 and so on
3.2.7 The Combo Box 
The function of the Combo Box is also to present a list of items where the user can click and select the items from the list. However, the user needs to click on the small arrowhead on the right of the combo box to see the items which are presented in a drop-down list. In order to add items to the list, you can also use the AddItem method. For example, if you wish to add a number of items to Combo box 1, you can key in the following statements
Example 3.3
Private Sub Form_Load ( )
Combo1.AddItem “Item1”
Combo1.AddItem “Item2”
Combo1.AddItem “Item3”
Combo1.AddItem “Item4”
End Sub
 3.2.8 The Check Box
The Check Box control lets the user to select or unselect an option. When the Check Box is checked, its value is set to 1 and when it is unchecked, the value is set to 0.  You can include the statements Check1.Value=1 to mark the Check Box and Check1.Value=0 unmark the Check Box, and use them to initiate certain actions. For example, the program will change the background color of the form to red when the check box is unchecked and it will change to blue when the check box is checked.  You will learn about the conditional statement If….Then….Elesif in later lesson. VbRed and vbBlue are color constants and BackColor is the background color property of the form. 
Example 3.4
Private Sub Check1_Click ()
If Check1.Value = 0 Then
Form1.BackColor = vbRed
ElseIf Check1.Value = 1 Then
Form1.BackColor = vbBlue
End If
End Sub 
3.2.9 The Option Box
 The Option Box control also lets the user selects one of the choices. However, two or more Option Boxes must work together because as one of the Option Boxes is selected, the other Option Boxes will be unselected. In fact, only one Option Box can be selected at one time. When an option box is selected, its value is set to “True” and when it is unselected; its value is set to “False”. In the following example, the shape control is placed in the form together with six Option Boxes. When the user clicks on different option boxes, different shapes will appear. The values of the shape control are 0, 1, and 2,3,4,5 which will make it appear as a rectangle, a square, an oval shape, a rounded rectangle and a rounded square respectively.
 Example 3.5
Private Sub Option1_Click ( )
Shape1.Shape = 0
End Sub
Private Sub Option2_Click()
Shape1.Shape = 1
End Sub
Private Sub Option3_Click()
Shape1.Shape = 2
End Sub
Private Sub Option4_Click()
Shape1.Shape = 3
End Sub
Private Sub Option5_Click()
Shape1.Shape = 4
End Sub
Private Sub Option6_Click()
Shape1.Shape = 5
End Sub
 3.2.9 The Drive List Box
The Drive ListBox is used to display a list of drives available in your computer. When you place this control into the form and run the program, you will be able to select different drives from your computer.
 3.2.10 The Directory List Box
The Directory List Box is used to display the list of directories or folders in a selected drive. When you place this control into the form and run the program, you will be able to select different directories from a selected drive.
3.2.11 The File List Box
The File List Box is used to display the list of files in a selected directory or folder. When you place this control into the form and run the program, you will be able to a list of files in a selected directory.
You can coordinate the Drive List Box, the Directory List Box and the File List Box to search for the files you want.
MENUS

Menu is a list of items to perform a particular task when the user clicks it.

Types:

Drop-down menu:
          It represents a class of components in the user interface. It will descend from the menu heading when the user clicks on the menu heading. Dragging the mouse over one of the items will highlight the drop down menu items.

Pop-up Menu:
          A pop-up menu can appear anywhere within a form, usually in response to click the right mouse button.

So a Drop-down menu and a Pop-up menu can be created using a Menu Editor as shown below.

Creation of Drop-Down menu:

1.  Click on the menu editor button in the Toolbar or select from the Tools menu or form right click.
2.  Enter identifier for the caption and name for each menu item. Caption will appear in the large area at the bottom of the menu editor. But the name willn’t displayed when the application is running.

Menu components must be entered in the following order.
1.  Enter 1st menu heading
2.  Click on next->click on right button. Enter the corresponding menu items for the 1st menu.
3.  The second menu heading and so on.

Accessing a menu from the keyboard:

A keyboard access character can be def9ined for each menu item. This allows the user to view a drop-down menu by pressing Alt or Ctrl key for the menu heading and for items. To define an access character for items select function key or ctrl+key from the field short cut in menu editor.

Menu Enhancements

Check Box: assigned to a menu item, indicating the on-off status of the menu item. Selecting the box labeled checked will cause the menu item to be checked initially.
Enabled Box: It is the ability to deactivate a menu item by deselecting the enabled box.

Submenu:

A menu item may have a submenu. Submenu is a menu with a list of items which is adjacent to the parent menu item. The use of submenus allows menu selections to be arranged in a logical, hierarchical manner.

Creation of submenu:

Simply indent the submenu items beneath the parent menu item within the menu editor. A right-pointing arrow at its edge will identify each menu item having a submenu.

Pop-up Menus:
A pop-up menu can appear anywhere within a form, usually in response to click the right mouse button.

Creation of pop-up menu
It is created via the menu editor in the same manner as a drop-down menu except that the main menu item is not visible. An event procedure must be entered into the code editor. The general form of the event procedure is

Private sub form_mouseDown(Button as Integer, Shift as Inter, X as Single, Y as Single )
If button=vbrightbutton then
Popmenu  ………
End if
End sub
All of the components of this event procedure have a predefined meaning

DIALOG BOXES

It is used to exchange information between the program and the user. It is used to display information for the user

Features

·    It usually doesn’t have a menu
·      Cant be resized
·    Act as the main interface of the application
(it is used to acquire user inputs that required to execute a certain action or to display messages)

Types of Dialog Box

1.         Modal              2.         Modeless

Modal: It willn’t let the user program any action while it is on display. Ex:- file open dialog, print dialog
Modeless: It allows the user to continue working with the program even though they remain displayed on screen Ex:- find and replace

Steps to add dialog form are:
1.   Go  to ‘Project’ Menu
2.   Select ‘Add Form’ option
3.   Select ‘dialog’ icon the dialog box and click on ‘open’ button.

Classification of Dialog Boxes:

1. Common Dialog Boxes:  These provide the functionality required for actions such as opening, saving and printing a file. These dialogs are available in a ready-to-use format

Actions

1.   Opening a file
2.   Saving a file
3.   Printing

2. Custom Dialog Boxes: These are dialog boxes designed to meet the requirements of the application and are designed by the programmer
The user to suit the needs of the application creates custom dialogs

1.         Use the common dialog boxes where possible. It saves on coding time and maintains a consistent look among applications.
2.         To accept just a single input from the user, use the Input Box
3.         To display a message, use the message box customizes the message box by using appropriate buttons and icons.
4.         Use custom dialog boxes when u needs to accept multiple inputs from the user. Use appropriate controls.
5.         Use Modal dialog boxes when it is necessary that the user provide input for the application to continue.

Predefined Dialog Boxes:

Message Box: It is a dialog box that displays text and used to create error messages. It returns a positive integer whose value depends on the action taken by the user.
           
Input Box:  It is similar to the MsgBox. This function is primarily intended to display a dialog box that accepts an input string whereas the MsgBox function is primarily intended to show an output string.
           
MsgBox Function
This function generates a dialog box which displays a given output string one or more command buttons and returns a positive integer whose value depends  on the action taken by the user.

Syntax:
Integer_variable = MsgBox(String, Int_value, Title)
String:- Message displayed to user.
Int_value:- it defines the command buttons that appear within the box
Title:-which specifies the title of the message box. Default is the name of the project.

The following list is some integer values and resulting MsgBox Command buttons.
Integer-Value                         Resulting Command Buttons
0                                  OK
1                                  OK,Cancel
2                                  Abort,Retry,Ignore
3                                  Yes,No,Cancel
4                                  Yes,No
5                                  Retry,Cancel

The following is the list of command buttons and their corresponding return values.

Command Button                 Return Value
            Ok                               1
            Cancel                         2
            Abort                           3
            Retry                           4
            Ignore                          5
            Yes                              6
            No                               7

Input Box Function
This function also invokes a dialog box and meant for accessing input value from the user.
Syntax:-
Var_name=Input Box(Prompt, Title, Default_value)
Prompt:- string appears as prompt for input.
Title:- Title of the inputbox, default is project name.
Default_value:- ‘default value’ of the input box.

DEBUGGING AND EXECUTING A NEW PROJECT

Error: It refers to the difference between the actual output of a program to the correct output. It can also be called as a bug.

Debugging: Identifying and removing errors occurred during program execution is called Debugging.
Errors are of 2 Types:
1.   Syntactic Errors
2.   Logical Errors

Syntactic Errors

This type of errors occurs when Visual Basic Commands are written improperly. These are known as ‘Compilation Errors’. These errors are relatively easy to fix, since the VB indentifies the error and highlights the line with Red Color in the ‘Code Editor Window’.

Logical Errors

Errors may also occur during program execution. Many execution errors are caused by faculty program logic and are known as Logical Errors or Runtime Errors. In the ‘Code Editor Window’ the line containing error will be highlighted with ‘Yellow Color’.

Debugging Features

The VB Debugger contains features that can assist in locating the source of errors for second type of logical errors.
These features include ‘stepping through a program’, setting breakpoints( which causes the execution to be suspended) and defining watch values.
VB Debugging features can be accessed in 3 ways:
1.   Via the Debug Menu on the Menu Bar
2.   Via the Debug toolbar
3.   By using function keys.

Setting Break Point

Generally a ‘break point’ is placed just before the suspected source of error. This is mainly used to execute the program in a normal manner, until the break point is encountered.
To set the breakpoint place the cursor in the statement where the ‘breakpoint’ is to be set we can select any of the following methods to set breakpoint.
1.   Select ‘Toggle Break Point’ option from Debug menu.
2.   Click ‘Toggle Break Point’  icon on the Debug ToolBar.
3.   Press f9.
After setting the ‘breakpoint’ the statement will be highlighted and we can observe a dark circle on the left of the selected statement.

Removing Break Point

A break point set can be removed by invoking ‘Toggle Break Point’ option again.

Temporary Break Point

We can set a temporary break point by selecting ‘Run TO Cursor’ option from Debug Menu by placing cursor at one position. It will be removed automatically after executing program once.

Defining Watch Values

Watch values are current values of variables or expressions that are displayed in Watches window. VB Supports 3 types of watch values.
1.   Ordinary Watch Values
2.   Quick Watch Values
3.   Immediate Watch Values

Ordinary Watch Values

These types of watch values are generally preferable because they remain active as you step through a program on a line-by-line basis. These are displayed in a separate ‘Watches’ Window.

Invoking ‘Watches’ Window
Select ‘Watch Window’ option from View Menu.

Setting Watch Values to Watches Window
1.   Right Click in the watches window
2.   Select add watch option from popup menu
3.   Give details in the ‘add watch’ window.

Edit or Delete Watch Values
Watch values in the watches window can be edited or deleted using Edit Watch Window which can be invoked from Debug Menu

Quick Watch Values
If we want to know the current value of a variable or expression that has not been added to the watches window then we can use ‘Quick Watch’ window.

Invoking Quick Watch Window
1.   First select the variable or expression
2.   Now select ‘Quick Watch’ option from Debug Menu
3.   Then details will be given in Quick Watch window.

Immediate Watch Window
If we want to know the value of a variable or expression immediately then we can use Immediate Watch Window. Inside the window the variable or expression must be preceded by ?.

Invoking Immediate Watch Window
Select ‘Immediate Window’ option from view menu

Stepping through a program
It is nothing but line-by-line execution of the program and can be done from any place in the program. There are actually 3 different types of stepping. These options can be invoked from Debug Menu.
1.   Step Info: This results in line-by-line execution with in a procedure. This is the starting step of ‘Step though a program’.
2.   Step Over: This is used for moving from one line to another in the process of line-by-line execution.
3.   Step Out: This is used for coming out of line-by-line execution.

User-Induced Errors
User-induced errors occur when user make a mistake while executing the program. This type of errors can be expected and can be trapped also using ‘Error handlers’ in VB.

Error Handling
An ‘error handler’ is a series of statements intended to trap the error and then to provide appropriate remedial action. The nature of the remedial action depends on the type of error encountered. Possible remedial actions are of 3 types. They are
1.   User can reenter input data that will prevent the error from occurring
2.   The source of error can be corrected automatically.
3.   The error can simply be by passed.

On Error GoTo Statement
While writing an ‘Error Handler’ we must trap the error and then redirect the program logic to a special part of the program known as On Error GoTo Statement. This statement redirects the program logic to a remote statement when an error occurs and the remote statement includes a label that is specified with in the ‘On Error GoTo Statement’.
Ex:       Private Sub Procedure_name( )
            On Error GoTo Label
            ----
            Exit Sub
            Label:
            ---
            Resume
            End Sub
We can write resume statement in 3 manners
1.   Resume label is useful if user is reentering the input data
2.   Resume is useful if error is corrected automatically
3.   ‘Resume next’ is useful if we want to bypass the error containing statement.
Suppose no error is found then EXIT SUB is executed and it takes cursor out of the sub procedure.
Runtime Errors
Error Code                            Corresponding Error Message
3                                              Without go sub
5                                              Invalid Procedure call or argument    
6                                              Overflow
7                                              Out of Memory
9                                              Subscript out of range
11                                            Division by Zero
13                                            Type of mismatch
35                                            Sub, function or property not defined
61                                            Disk Full
68                                            Device unavailable
92                                            For loop not initialize

Stand Alone Executable Programme
Once a program has been debugged we can generate separate stand alone version. These stand alone programs are convenient because they can be executed independently of the VB. These can be easily be portable i.e., transporting from one computer to another.
Steps
1.   Go to file Menu
2.   Select the option – “make exe”

PROCEDURES
            Large projects divided into ‘modules’ for easy maintenance. VB supports several types of modules, each of which is stored as a separate file.
Ex:-     Form Modules
            Standard Modules
            Class Modules
Procedures
Large modules are decomposed into multiple procedures for several reasons. First, the use of procedures eliminates redundancy. Secondly, it enhances the clarity of a program and performing the operations like debugging, modification etc., are easier.
A procedure is  a self contained group of VB commands that can be accessed from any part of the program.
VB Supports 4 types of procedures.
1.   Sub-Procedure
2.   Function Procedure
3.   Event Procedure
4.   Property procedure

Sub-procedure:- a ‘Sub-Procedure’ perfroms a predefined action either by receiving or withouot receiving arguments. It does not return a value back to calling procedure. It can be also called as ‘Sub-routine’.
Syntax:           Scope sub procedure_name(args)
In the above procedure definition, the scope can be either private or public.

Passing arguments to a sub-procedure
1.   By Value
2.   By Reference

By Value:-
While passing args to a procedure ‘By Value’ the arguments name within the procedure must be preceeded by the reserved word ‘ByVal’.
Syntax:- ByVal argument as Datatype
Ex:- Private Sub prime(ByVal n as Integer)

By Reference:-
While passing args to a procedure ‘by reference’ the srguments name within the procedure must be preceeded by the reserved word ‘ByRef’.
Syntax:-ByRef argument as datatype
Ex:-Private Sub prime(ByRef n as Integer)

Calling a Sub-Procedure
A sub-procedure can be called in 2 ways.
1.   By using ‘call’ statement.
Syntax: call procedure_name(args)
2.   Without using ‘call’ statement.
Syntax: procedure_name(args)

Function Procedure:
A function procedure is similar to a sub procedure with one important difference that it is intended to return a value. Each ‘function_name’ represents a data item and has a dataype associated with it. In the function definition, the ‘fun_name’ must be assigned a value, which acts as return value to calling function.

Syntax:
Scope function procedure_name(arguments) as Datatype
Procedure-name=value;
End function

Event Procedure:
An event procedure is a special type of sub-procedure. It ca n be accessed by a specific action like ‘clicking on an object rather than by the call statement. The particular action associated with ‘event-procedure’ is selected from upper-right dropdown menu within the code editor window. The object name and activating event collectively called as ‘event-procedure’.

Scope

Scope referes to the portion of a program in which a procedure definition is recognised.
·    A public procedure can be accessed from any module or from within a project.program.
·    A private procedure can be accessed only within the module or form in which it is defined

Accessing a public procedure
A public procedure can be accessed in the normal manner in  a form in which it is defined. If the procedure definiion is present in a different form then the procedure name must be preceeded by the form name to access it from other forms.

Form1                                                                          Form2
Public Sub textcls( )                                                    Private Sub Command1_Click( )
----------                                                                                    --------------------
End Sub                                                                      Call form1.textcls
Private Sub Command1_Click ( )                               End Sub
Call textcls
End Sub
ARRAYS

An array is a variable which contains table of similar items. Suppose we have to store the value of ten items. Instead of creating ten separate variables. We may create a single array having ten elements. It is a linear collection of similar elements.

Array Declaration
Scope array_name(subscript_upperlimit) as Datatype
Ex:      Dim/Private/Public  a(10) as Integer
Even we can specify the lower and upper limits of an array in the declaration.
Ex:      Dim a(1 To 10) as integer
Ex: Dim Arr(3) as Integer
In the above statement the number 3 inside the paranthesis is the index number of the array. The index number of an array starts from 0 and is used to refer to the elements of an array.

2-D array Declarations
Syntax: array_name(subscripts1-upperlimit, subscripts2-upperlimit) as datatype
Ex: Dim a (10,2) as integer
Dim a(1 To 10, 1 To 2) as Integer.

Dynamic Array
It is an array whose sizes can be changed at various places within a program. Dynamic array name is followed by empty pair of parenthesis.
Syntax: Scope array_name() as datatype      
Ex:      Dim a() as Integer

Specification of array size
Dynamic array size can be specified during execution of program using ‘Redim’ Statement
Ex: Redim a(10)
When a dynamic array is redimensioned the previous values of the array will be lost. They will be set to zero if it is integer array otherwise, to null if it is a string.

Preserve Keyword
To retain the previous values when the array is resized, we use ‘preserve’ keyword’ in the Redim Statement.
Syntax: Redim Preserve array_name(upperlimit)




Control Arrays

Multiple control of the same type can be grouped into an array, such a group is known as a ‘control array’.
#          Control array elements may share a common event procedure.
#          Control array elements are distinguished from each other using index.
#          Control array are created at design time.
#          Additional control array elements can also be added and later deleted at runtime.
#          All control array elements will share common name but indexes are different.

Creation of a Control Array
A control array can be created by placing a control within the form design window and assigning a value of 0 to its index property. Then copy and paste control, it results a new control within the  same name in the upper left control of the form design window.

Addition of a new control array element
Once a control array element has been created an addition element can be added during runtime, using the Load statement i.e.,
Syntax:           load Control_name(index)

Deletion of control array element at runtime
An element added at runtime can later be deleted, using unload statement
Syntax:unload controlarray_element(index)
Syntax:           For each index in array_name
            ----
            Next
            For Each I in a
            ----
            Next

DATA FILES

A file is orderly, self-contained collection of information. Any type of information can be stored within a file.  A file may contain the instructions that comprise a VB program it may consists of data values is commonly known as Data File.

Data File Characteristics:
VB recognizes 3 different types of data files.
1.   Sequential files
2.   Random Access Files
3.   Binary Files
Sequential files are created by a text editor or word processor or by a VB program.

Random access files are organized into fixed-length records. Any record can be accessed directly by specifying the corresponding record number or record location.

Binary files store information as a continuous sequence of bytes. Such files appear unintelligible when printed or displayed on a computer screen, but their contents can be read into or written out of a computer faster than other file types.

Accessing and Saving a file in Visual Basic: (Common Dialog Control)

VB includes special tools for opening an existing file, and for saving a new file or an existing file that has been modified.
These tools are included in a group of “Common Dialog Objects” that must be added to the ToolBox before any of these tools can be accessed. To do so select components from the project menu then click on the controls tab and check the box labeled “Microsoft Common Dialog Control” once the Common Dialog control has been activated, icon will be appeared in the toolbox.

The Common Dialog Control does not appear within the form when the project is being executed.

The Common Dialog Control allows an application to easily access existing files or save new files through its Common Dialog boxes.

To access an existing file, simple add a following statement at the appropriate place.
Common Dialog1.showopen

When this statement is encountered during program execution, a dialog box will appear. The user may then use this dialog box to access a file within the currently active folder or another folder.

The type of files can be specified within the program by assigning an appropriate string to common dialog1. filter property
CommonDialog1.filter = “Text files(*.txt)/*.txt”

This statement displays only text files when we open a dialog box. Similarly to save a file with a specified name add a statement such as
CommonDialog1.showsave

When the showsave statement is encountered a dialog box will appear. The user may than use this dialog box to save a file within the currently active folder or some other folder.

Similarly to print a file : CommonDialog1.showprint

Processing a Data File

To process a data file the following three tasks must be carried out.
·    Open a data file
·    Process the file, as required by the application
·    Close the file
Opening the data file associates a file number with a named data file.

It also specifies certain information about the data file, such as the mode, the access type, the restrictions. Processing the data file generally involves reading the data items, modifying the data items, displaying the data items, and writing the modified data items.
Closing the data file is a formality that simply deactivates the conditions that  were specified when the file was opened.

Sequential Data Files

In a sequential data file the data can be stored sequentially as plain text. The text is organized into individual lines; each line of text can contain both numeric constants and strings in any combination. When opening a sequential file, the open statement is generally written in one three ways, depending on whether the file is an input file, an output file or an append file.

The three possibilities are
Open filename for Input As #n
Open filename for Output As #n
Open filename for Append As #n

Where  n refers to the channel number
Data items are usually read from a sequential data file via the Input # statement. This statement is written in
general terms as : Input #n, data items
Where n refers to the channel number and data items refers to the list of input data items, separated by commas. The input data items are typically variables, array elements, control properties, etc
Similarly data items are usually written to a sequential data file via he print # statement.
General term is : print #n, data items
Where the data items can be constants, variables, expressions, array elements, control properties etc.
There are other ways to enter and write data that are convenient in certain situations.
i.e., Line Input #n data item
it enters an entire line of text as a single data item.
Similarly the write statement is very useful when generating a text file from information entered from the keyboard.
General Form: write #n, data items

RANDOM ACCESS (DIRECT) DATA FILES

Random access data files consist of a collection of fixed length records, each of which is assigned a unique record number.
Once a random access file has been opened, referencing its record number can access an individual record
The open statement is written as

Open filename for random as #n len=record length
Or
Open filename as #n len=record length

Random is the default file type
The record length must be large enough to accommodate each of the fixed length data items that will be stored within the random access data file.
The record length may be written as an integer constant or an expression.
The library function len returns the length of the record.
Data items are read from a random access data file, one record at a time, via the get # statement.
General Form: Get #n, record number, data item
Or simply: get #n, data item
Data items are written to a random access data file, one record at a time, via the put# statement
General form: put #n, record number, data item
Or simply:put #n, data item

Binary Files
Binary files contain information expressed as a stream of consecutive, unformatted bytes. A binary file may represent a graphic, a sound file or compiled code.
To open a binary file, we use the open statement in the following manner
Open filename for Binary As #n
Where filename represents the filename and n represents the data channel number.
Information is read from a binary file. We use the Get # statement to read a binary file.
i.e., Get #n, first byte, data item
where first byte is a positive integer that represents the number of the first byte read. The surrounding commas must be present if first byte is committed.
i.e., Get #n, data item
information is written to a binary file in the same manner, using the Put # statement.
i.e., Put #n, first byte, data item

where first byte is a positive integer that represents the number of the first byte written. The surrounding commas must be present if first byte is omitted.
i.e., Put#n,  , data item 

No comments:

INTRODUCTION VB 6.0

INTRODUCTION
What is Visual Basic?

Visual Basic is a tool that is used by more number of developers than any other tool. Visual Basic has been the choice of developers for various good reasons. So many small and big companies use Visual Basic for developing various types of applications.  One of the key factors that contributed to the success of Visual Basic is its ease of use.

When Windows Programming (writing programs that run on Windows OS) was very tough and was confined only to a few people who were good in C and C++, Visual Basic hit the market and changed the way one would look at windows programming. Visual Basic made windows programming so simple, even a novice started writing one or two programs for windows in Visual Basic.

The overall approach to VB programming is:
1.   Create a user interface that is appropriate to the particular application at hand.
2.   Add a group of basic instructions to carry out the actions associated with each of the controls.
Visual Basic: It is an object oriented programming language or development system for creating applications that run under any of the Microsoft Windows environments.
·    It is the developers choice
·    Using VB so many variety of applications can be developed.
·    It is user friendly

Event and Event Procedures

·    The program’s response to an action taken by the user is referred to as an event.
·    The group of basic commands that brings about this response is called as an event procedure.

Object Related Concepts in VB

·    Forms: In visual basic, a window is called as a form. Each form includes a title bar at the top.
·    Controls: The icons with which the user interacts are called controls. The user activate a control to produce an event.
·    Objects: Forms and controls are referred to collectively as objects. Most objects are associated with events, objects may include their own unique event procedures. Objects are associated with their own properties & methods.
·    Properties: It defines their appearance or behaviour
·    Methods: Some objects also include special program statements called methods. It is the predefined action affecting the associated object.

Starting Visual Basic IDE

Visual Basic provides IDE (Integrated Development Environment), which provides developers all the tools they need to develop applications.

To start Visual Basic from Windows:

Click Start on the Task bar.
Select Programs.
Select Microsoft Visual Studio 6.0 and then Microsoft Visual Basic 6.0
The Visual Basic Environment
You can choose to start a new project, open an existing project or select a list of recently opened programs. A project is a collection of files that make up your application. There are various types of applications we could create, however, we shall concentrate on creating Standard EXE programs (EXE means executable program). Now, click on the Standard EXE icon to go into the actual VB programming environment.
The Visual Basic Environment consists of the:
·      A  Blank Form for you to design your application's interface.
·      The Project window, which displays the files that are created in your application.
·      The Properties window, which displays the properties of various, controls and objects that are created in your applications.
It also includes a Toolbox that consists of all the controls essential for developing a VB Application. Controls are tools such as text box, command button, label, combo box, picture box, image box, timer and other objects that can be dragged and drawn on a form to perform certain tasks according to the events associated with them. Additional objects can be added by clicking on the project item on the menu and click on components on the drop-down list, then select those controls you need to use in your program
Components of IDE:

VB’s IDE has a collection of components. Each component has a specific task. The following are VB IDE Components:

Menu Bar
Displays the commands you use to work with Visual Basic. Besides the standard File, Edit, View, Window, and Help menus, menus are provided to access functions specific to programming such as Project, Format, or Debug.

Context Menus
Contain shortcuts to frequently performed actions. To open a context menu, click the right mouse button on the object you're using. The specific list of shortcuts available from context menus depends on the part of the environment where you click the right mouse button. For example, the context menu displayed when you right click on the Toolbox lets you display the Components dialog box, hide the Toolbox, dock or undock the Toolbox, or add a custom tab to the Toolbox. Context menu is also called as popup menu.

Toolbars
Provide quick access to commonly used commands in the programming environment. You click a button on the toolbar once to carry out the action represented by that button. By default, the Standard toolbar is displayed when you start Visual Basic. Additional toolbars for editing, form design, and debugging can be toggled on or off from the Toolbars command on the View menu.
Toolbars can be docked beneath the menu bar or can "float" if you select the vertical bar on the left edge and drag it away from the menu bar.

Toolbox
Provides a set of tools that you use at design time to place controls on a form. In addition to the default toolbox layout, you can create your own custom layouts by selecting Add Tab from the context menu and adding controls to the resulting tab.

Project Explorer Window
Lists the forms, modules and other components of the current project. A project is a collection of files, which you use to build an application.

Properties Window
Lists the property settings for the selected form or control. A Property is a characteristic of an object, such as size, caption, or color.

Object Browser
Lists objects available for use in your project and gives you a quick way to navigate through your code. You can use the Object Browser to explore objects in Visual Basic and other applications, see what methods and properties are available for those objects, and paste code procedures into your application.

Form Designer
Serves as a window that you customize to design the interface of your application. You add controls, graphics, and pictures to a form to create the look you want. Each form in your application has its own form designer window.

Code Editor Window
Serves as an editor for entering application code. A separate code editor window is created for each form or code module in your application.  Code window contains two dropdown list boxes, one for the list of objects in the form and another for available events of the selected object.

Form Layout Window
The Form Layout window allows you to position the forms in your application using a small graphical representation of the screen.

Immediate, Locals, and Watch Windows
These additional windows are provided for use in debugging your application. They are only available when you are running your application within the IDE.

Environment Options
Visual Basic provides a great deal of flexibility, allowing you to configure the working environment to best suit your individual style. You can choose between a single or multiple document interface, and you can adjust the size and positioning of the various Integrated Development Environment (IDE) elements. Your layout will persist between sessions of Visual Basic.


FORM
 Properties
 Form layout window
Tool Box

 A Visual Basic application is developed in three steps:

Create the user interface
Change properties
Write code
In the first step, we lay down control on the form and arrange them in the way we want.
In the second step, we change properties of controls and form to required objects.
In the third step, we write code for events.

Creating user interface
Our first application needs only one control – command button. Select command button in Toolbox and drag it and drop it on the form at the required location. Here are the required steps.
Invoke Form designer by double clicking on Form in Project Explorer, if designer is not already displayed. (or)
Select the icon for command button in Toolbox. The background of the icon becomes gray.
Go to form. The moment you enter into the form the mouse pointer changes to cross hair (plus sign).
Place the cross hair at the bottom of the form and drag mousepointer  (means hold down the left button and move the mouse pointer). While you move mousepointer you see a gray rectangle.
Once you dragged from the required location to required location, release the mouse button.
Control appears at that location with the size that is same as the gray rectangle.

Changing properties
Once the required controls are placed on the form, we have to change the properties of the control to get the required look and behavior.
Each control has a collection of properties. Each property represents an attribute of the control. For example, Name property identifies the name used to reference the control in the code and so on.
To change the properties of control (and form), we have to use Properties Window, which allows you to change properties by displaying properties on left and values on the right.
The following are the steps required to change properties of command button and form.

Invoke Properties Window for command button by pressing F4 after selecting command button.
In Properties Window select Caption property and enter  “ &Exit “ (without quotes) on the right of it.
Select Name property and change it to cmdExit.
Then click anywhere on the form (to unselect command button) and press F4 to invoke Properties Window for Form.
Select Caption property and change it to First Visual Basic Application.
Select Name property and change it to frmFirst.

Writing Code
The final step is writing code for events. Just before we proceed further, let us understand the event to which we need to respond.
We need to respond to Click event of the form, as we want to display the name whenever user clicks on the form.
We need to respond to Click event of command button (cmdExit) as we have to terminate program when user clicks on the command button.
Here are the steps to write code for these two events.

Select form and press F7 to invoke code window.
-or-
Double click on the form to invoke code window.
Code window displays Load event on the right (as that is default event for form). Select Click event using the dropdown list and write code as shown in figure 1.6.


Double click on the command button to invoke code window. By default Click event is selected.  Write the following code.
Print is a statement that displays the given data on the form.

Saving Project
When you save a project, Visual Basic prompts you to enter filenames in which it has to save components, such as Form of the project and then the project.
Each component is save in a separate file and project is saved in a separate file.
Save the project using following steps.

Select File->Save Project 
Or
Click on Save Project icon in Toolbar.
When Visual Basic prompts you to enter filename for form, select directory in which you want to save the form file and enter filename. By default the name of the form will be the name of the file. The default extension is .FRM (form).
After entering file name Click on Save button to save form.
Then it prompts you to enter name of the file for project.
Enter a filename. Visual Basic adds extension .VBP (Visual Basic Project).
Click on Exit button to terminate application.

Test Run
Now, run the application using any of the following methods.

By pressing F5
By clicking on Start icon in Toolbar
By selecting Run menu and Start option.

VB FUNDAMENTALS

There are many types of data we come across in our daily life. For example, we need to handle data such as names, addresses, money, date, stock quotes, statistics and etc everyday. Similarly in Visual Basic, we are also going to deal with these kinds of data. However, to be more systematic, VB divides data into different types.

Types of Visual Basic Data Types

Numeric Data
Numeric data are data that consists of numbers, which can be computed mathematically with various standard operators such as add, minus, multiply, divide and so on. In Visual Basic, the numeric data are divided into 7 types,
Type               Storage           Range of Values
Byte                1 byte              0 to 255
Integer             2 bytes             -32,768 to 32,767
Long                4 bytes             -2,147,483,648 to 2,147,483,648
Single              4 bytes             -3.402823E+38 to -1.401298E-45 for negative values
1.401298E-45 to 3.402823E+38 for positive values.

Double                        8 bytes             -1.79769313486232e+308 to -4.94065645841247E-324 for
negative values

4.94065645841247E-324 to 1.79769313486232e+308 for positive values.
Currency         8 bytes             -922,337,203,685,477.5808 to 922,337,203,685,477.5807
Decimal           12 bytes           +/- 79,228,162,514,264,337,593,543,950,335 if no decimal
is use
+/- 7.9228162514264337593543950335 (28 decimal
places).
Non-numeric Data Types
Data Type                              Storage                       Range
String(fixed length)      Length of string           1 to 65,400 characters
String(variable length)  Length + 10 bytes        0 to 2 billion characters
Date                              8 bytes                          January 1, 100 to December 31, 9999
Boolean                        2 bytes                          True or False
Object                           4 bytes                          Any embedded object
Variant(numeric)          16 bytes                        Any value as large as Double
Variant(text)                 Length+22 bytes          Same as variable-length string
Managing Variables

Variables are like mail boxes in the post office. The contents of the variables changes every now and then, just like the mailboxes. In term of VB, variables are areas allocated by the computer memory to hold data. Like the mail boxes, each variable must be given a name. To name a variable in Visual Basic, you have to follow a set of rules.

Variable Names

The following are the rules when naming the variables in Visual Basic
·      It must be less than 255 characters
·      No spacing is allowed
·      It must not  begin with a number
·      Period is not permitted
Valid Name                                                Invalid Name
My_Car                                                       My.Car 
ThisYear                                                      1NewBoy
Long_Name_Can_beUSE                          He&HisFather                  *& is not acceptable
Declaring Variables
In Visual Basic, one needs to declare the zvariables before using them by assigning names and data types. They are normally declared in the general section of the codes' windows using the Dim statement.
The format  is as follows:

Dim variableName as DataType

Example:
Dim password As String
Dim yourName As String
Dim firstnum As Integer
Dim secondnum As Integer
Dim total As Integer
Dim doDate As Date

You may also combine them in one line , separating each variable with a comma, as follows:
Dim password As String,  yourName As String, firstnum As Integer,.............

If data type is not specified, VB will automatically declare the variable as a Variant.
For string declaration, there are two possible formats, one for the variable-length string and another for the fixed-length string. For the variable-length string, just use the same format as above. However, for the fixed-length string, you have to use the format as shown below:

Dim VariableName as String * n, where n defines the number of characters the string can hold.
Example:
Dim yourName as String * 10
yourName can holds no more than 10 Characters.  

Assigning Values to Variables

After declaring various variables using the Dim statements, we can assign values to those variables. The general format of an assignment is
Variable=Expression

The variable can be a declared variable or a control property value. The expression could be a mathematical expression, a number, a string, a Boolean value (true or false) and etc. The following are some examples:
firstNumber=100
secondNumber=firstNumber-99
userName="John Lyan"
userpass.Text = password
Label1.Visible = True
Command1.Visible = false
Label4.Caption = textbox1.Text
ThirdNumber = Val(usernum1.Text)
total = firstNumber + secondNumber+ThirdNumber  

Suffixes for Literals
Literals are values that you assign to a data. In some cases, we need to add a suffix behind a literal so that VB can handle the calculation more accurately. For example, we can use num=1.3089# for a Double type data. Some of the suffixes are displayed below
                        Suffix  Data Type                                          Data Types
                                    &                                                         Long
                                    !                                                           Single
                                    #                                                          Double
                                    @                                                        Currency
In addition, we need to enclose string literals within two quotations and date and time literals within two # sign. Strings can contain any characters, including numbers. The following are few examples:
memberName="Turban, John."
TelNumber="1800-900-888-777"
LastDay=#31-Dec-00#
ExpTime=#12:00 am#


Library Functions

Visual Basic contains numerous library functions that provide a quick and easy way to carry out many mathematical operations, manipulate strings, and perform various logical operations.
Function                                 Application                            Purpose
Abs                                          y=Abs(x)                                 return the absolute value of x
CDbl,Cint,Csng                      y=CInt(x)                                convert x to appropriate data
type
Chr                                          y=Chr(x)                                 return the numerical value of
x
Cos                                          y=Cos(x)                                 return the cosine of x
Date                                        y=Date                                                return the current system
date
Exp                                          y=Exp(x)                                 return the value of e to the x
power
Format                                     y=Format(x,”frmt str”)           return the value of x in a
format
Lcase                                       y=Lcase(x)                              return the lowercase
equivalent of x
Len                                          y=Len(x)                                 return the length of x
Log                                          y=Log(x)                                 return the log of x
mid                                          y=Mid(x,n1,n2)                       return the middle n2 chars of
the string x, beginning
with char number n1.
Rnd                                         y=Rnd                                     return a random number
Sqr                                           y=sqr(x)                                   return the sqrt of x
Str                                           y=str(x)                                   return a string whose chars
comprise the value of x
Ucase                                      y=Ucase(x)                              return the uppercase
equivalent of x
Val                                          y=val(x)                                   return a numeric value
corresponding
to the string x

OPERATORS
An operator is a symbol or a word that performs an operation. Depending upon the type of operation an operator performs, operators are classified as follows:

Category                        What it does?
Arithmetic Operators      Used to perform arithmetic operations such as addition,
                                        subtraction etc.
Relational Operators       Used in forming conditions used to compare values.
Logical Operators           Used to combine conditions or to negate condition
Assignment Operator      Used to assign a value to a variable
Concatenation Operator Used to concatenate ( join) two strings

Arithmetic Operators
The following are various arithmetic operators.

Operator    What it does?
+                 Addition
-                  Subtraction. This operator can also be used as unary operator. In this case, it
                    negates the sign of the number. For example, if variable A contains –10 then –A
                    will result in 10(positive 10).
/                   Division
*                  Multiplication
Mod            Modulus. Returns the remainder of the division.
\                   Integer Division. Returns only integer portion of the quotient.

Relational Operators
The following are the operators used to form conditions. The result of any expression using a relational operator will be either True or False.

Operator    Meaning
<                 Less than
>                 Greater than
<=               Less than or equal to
>=               Greater than or equal to
=                 Equal to
<>               Not equal to

Logical Operators
These operators are used to combine two relational operators. The following are the available logical operators.

Operator        Meaning
AND            Both the conditions must be true for the entire condition to be true.
OR               If either condition is true then the entire condition is true.
NOT             Reverses the result of the condition.
XOR              The entire condition is true only when either of the conditions is true. If
both the conditions are true or if both the conditions are false then entire condition is false.
EQV             The entire condition is true only when both the conditions are either true or
                     false.
IMP              The entire condition is true except when the first condition is true and the
                     second condition is false.


CONTROL STRUCTURES

Control Statements are used to control the flow of program's execution. Visual Basic supports control structures such as if... Then, if...Then ...Else, Select...Case, and Loop structures such as Do While...Loop, While...Wend, For...Next etc method.

If...Then selection structure
The If...Then selection structure performs an indicated action only when the condition is True; otherwise the action is skipped.
Syntax of the If...Then selection
If <condition> Then
statement
End If
e.g.: If average>75 Then
txtGrade.Text = "A"
End If

If...Then...Else selection structure
The If...Then...Else selection structure allows the programmer to specify that a different action is to be performed when the condition is True than when the condition is False.
Syntax of the If...Then...Else selection
If <condition > Then
statements
Else
statements
End If
e.g.: If average>50 Then
txtGrade.Text = "Pass"
Else
txtGrade.Text = "Fail"
End If

Nested If...Then...Else selection structure
Nested If...Then...Else selection structures test for multiple cases by placing If...Then...Else selection structures inside If...Then...Else structures.
Syntax of the Nested If...Then...Else selection structure
You can use Nested If either of the methods as shown above Method 1
If < condition 1 > Then
statements
ElseIf < condition 2 > Then
statements
ElseIf < condition 3 > Then
statements
Else
Statements
End If
Method 2
If < condition 1 > Then
statements
Else
 If < condition 2 > Then
statements
 Else
If < condition 3 > Then
statements
Else
Statements
End If
 End If
EndIf

e.g.: Assume you have to find the grade using nested if and display in a text box
If average > 75 Then
 txtGrade.Text = "A"
ElseIf average > 65 Then
 txtGrade.Text = "B"
ElseIf average > 55 Then
 txtGrade.text = "C"
ElseIf average > 45 Then
 txtGrade.Text = "S"
Else
 txtGrade.Text = "F"
End If

Select...Case selection structure
Select...Case structure is an alternative to If...Then...ElseIf for selectively executing a single block of statements from among multiple block of statements. Select...case is more convenient to use than the If...Else...End If. The following program block illustrate the working of Select...Case.
Syntax of the Select...Case selection structure
Select Case Index
Case 0
Statements
Case 1
Statements
End Select
e.g.: Assume you have to find the grade using select...case and display in the text box
Dim average as Integer
average = txtAverage.Text
Select Case average
Case 100 To 75
 txtGrade.Text ="A"
Case 74 To 65
 txtGrade.Text ="B"
Case 64 To 55
 txtGrade.Text ="C"
Case 54 To 45
 txtGrade.Text ="S"
Case 44 To 0
 txtGrade.Text ="F"
Case Else
MsgBox "Invalid average marks"
End Select

Looping
Visual Basic allows a procedure to be repeated as many times as long as the processor could support. This is generally called  looping .

Do Loop
The format are
a)   Do While condition
            Block of one or more VB statements
      Loop
b)   Do
            Block of one or more VB statements
      Loop While condition
c)    Do Until condition
              Block of one or more VB statements
       Loop
d)    Do
             Block of one or more VB statements
       Loop Until condition

Example
       Do while counter <=1000
             num.Text=counter
             counter =counter+1
       Loop
* The above example will keep on adding until counter >1000.

The above example can be rewritten as
        Do
               num.Text=counter
               counter=counter+1
       Loop until counter>1000
 
Looping with While-Wend
While-wend
The format are :
While logical expression
Executable statements
Wend
Ex;
While n<=0
            Print “hai”
Wend

For....Next Loop       
The format is:
For counter=startNumber to endNumber (Step increment)
    One or more VB statements
Next counter
Example:
(a)       For  counter=1 to 10
            display.Text=counter
            Next counter
(b)        For counter=1 to 1000 step 10
           counter=counter+1
            Next counter
(c)       For counter=1000 to 5 step -5
            counter=counter-10
           Next counter

NAME PROPERTY

Each control and form in a Visual Basic project has a name, which is used to refer to the object.
Whenever you access a control in the code, you use the name of the control. Name of the control is set using Name property of the control.
Caption property contains the text to be displayed to the user and Name property contains the name that is to be used in the code to refer to the control.
The name of the control is important because it is used even in the event procedures of the control.  The name of the event procedure is formed using the name of the control and the name of the event. For example, if name of the control is cmdQuit and event is Click, then the name of event procedure will be cmdQuit_Click.
While giving name to a control, we use a prefix to identify the type of the control. Giving prefix is purely a convention and not a rule in any way.  The following is the table shows the standard naming conventions followed in Visual Basic.

CONTROLS

The Control Properties
Before writing an event procedure for the control to response to a user's input, you have to set certain properties for the control to determine its appearance and how it will work with the event procedure. You can set the properties of the controls in the properties window or at runtime.

·      You should set the Caption Property of a control clearly so that a user knows what to do with that command. For example, in the calculator program, all the captions of the command buttons such as +, - , MC, MR are commonly found in an ordinary calculator, a user should have no problem in manipulating the buttons.
·      A lot of programmers like to use a meaningful name for the Name Property may be because it is easier for them to write and read the event procedure and easier to debug or modify the programs later. However, it is not a must to do that as long as you label your objects clearly and use comments in the program whenever you feel necessary. T
·      One more important property is whether the control is enabled or not.
·      Finally, you must also considering making the control visible or invisible at runtime, or when should it become visible or invisible.
3.2 Handling some of the common controls
3.2.1 The Text Box   
The text box is the standard control that is used to receive input from the user as well as to display the output. It can handle string (text) and numeric data but not images or pictures. String in a text box can be converted to a numeric data by using the function Val(text). The following example illustrates a simple program that processes the inputs from the user.
 Example 3.1
In this program, two text boxes are inserted into the form together with a few labels. The two text boxes are used to accept inputs from the user and one of the labels will be used to display the sum of two numbers that are entered into the two text boxes. Besides, a command button is also programmed to calculate the sum of the two numbers using the plus operator. The program use creates a variable sum to accept the summation of values from text box 1 and text box 2.The procedure to calculate and to display the output on the label is shown below.. 
Private Sub Command1_Click()
‘To add the values in text box 1 and text box 2
Sum = Val(Text1.Text) + Val(Text2.Text)
‘To display the answer on label 1
Label1.Caption = Sum
End Sub
 3.2.2 The Label    
The label is a very useful control for Visual Basic, as it is not only used to provide instructions and guides to the users, it can also be used to display outputs. One of its most important properties is Caption. Using the syntax label.Caption, it can display text and numeric data . You can change its caption in the properties window and also at runtime. 
 3.2.3 The Command Button 
The command button is a very important control as it is used to execute commands. It displays an illusion that the button is pressed when the user click on it. The most common event associated with the command button is the Click event, and the syntax for the procedure is
Private Sub Command1_Click ()
Statements
End Sub
3.2.4 The Picture Box 
The Picture Box is one of the controls that used to handle graphics. You can load a picture at design phase by clicking on the picture item in the properties window and select the picture from the selected folder. You can also load the picture at runtime using the LoadPicture method. For example, the statement will load the picture grape.gif into the picture box.
Picture1.Picture=LoadPicture ("C:\VB program\Images\grape.gif")
The image in the picture box is not resizable.
 3.2.5 The Image Box
The Image Box is another control that handles images and pictures. It functions almost identically to the picture box. However, there is one major difference, the image in an Image Box is stretchable, which means it can be resized. This feature is not available in the Picture Box. Similar to the Picture Box, it can also use the LoadPicture method to load the picture. For example, the statement loads the picture grape.gif into the image box.
Image1.Picture=LoadPicture ("C:\VB program\Images\grape.gif")
 3.2.6 The List Box
The function of the List Box is to present a list of items where the user can click and select the items from the list. In order to add items to the list, we can use the AddItem method. For example, if you wish to add a number of items to list box 1, you can key in the following statements
Example 3.2
Private Sub Form_Load ( )
List1.AddItem “Lesson1”
List1.AddItem “Lesson2”
List1.AddItem “Lesson3”
List1.AddItem “Lesson4”
End Sub
The items in the list box can be identified by the ListIndex property, the value of the ListIndex for the first item is 0, the second item has a ListIndex 1, and the second item has a ListIndex 2 and so on
3.2.7 The Combo Box 
The function of the Combo Box is also to present a list of items where the user can click and select the items from the list. However, the user needs to click on the small arrowhead on the right of the combo box to see the items which are presented in a drop-down list. In order to add items to the list, you can also use the AddItem method. For example, if you wish to add a number of items to Combo box 1, you can key in the following statements
Example 3.3
Private Sub Form_Load ( )
Combo1.AddItem “Item1”
Combo1.AddItem “Item2”
Combo1.AddItem “Item3”
Combo1.AddItem “Item4”
End Sub
 3.2.8 The Check Box
The Check Box control lets the user to select or unselect an option. When the Check Box is checked, its value is set to 1 and when it is unchecked, the value is set to 0.  You can include the statements Check1.Value=1 to mark the Check Box and Check1.Value=0 unmark the Check Box, and use them to initiate certain actions. For example, the program will change the background color of the form to red when the check box is unchecked and it will change to blue when the check box is checked.  You will learn about the conditional statement If….Then….Elesif in later lesson. VbRed and vbBlue are color constants and BackColor is the background color property of the form. 
Example 3.4
Private Sub Check1_Click ()
If Check1.Value = 0 Then
Form1.BackColor = vbRed
ElseIf Check1.Value = 1 Then
Form1.BackColor = vbBlue
End If
End Sub 
3.2.9 The Option Box
 The Option Box control also lets the user selects one of the choices. However, two or more Option Boxes must work together because as one of the Option Boxes is selected, the other Option Boxes will be unselected. In fact, only one Option Box can be selected at one time. When an option box is selected, its value is set to “True” and when it is unselected; its value is set to “False”. In the following example, the shape control is placed in the form together with six Option Boxes. When the user clicks on different option boxes, different shapes will appear. The values of the shape control are 0, 1, and 2,3,4,5 which will make it appear as a rectangle, a square, an oval shape, a rounded rectangle and a rounded square respectively.
 Example 3.5
Private Sub Option1_Click ( )
Shape1.Shape = 0
End Sub
Private Sub Option2_Click()
Shape1.Shape = 1
End Sub
Private Sub Option3_Click()
Shape1.Shape = 2
End Sub
Private Sub Option4_Click()
Shape1.Shape = 3
End Sub
Private Sub Option5_Click()
Shape1.Shape = 4
End Sub
Private Sub Option6_Click()
Shape1.Shape = 5
End Sub
 3.2.9 The Drive List Box
The Drive ListBox is used to display a list of drives available in your computer. When you place this control into the form and run the program, you will be able to select different drives from your computer.
 3.2.10 The Directory List Box
The Directory List Box is used to display the list of directories or folders in a selected drive. When you place this control into the form and run the program, you will be able to select different directories from a selected drive.
3.2.11 The File List Box
The File List Box is used to display the list of files in a selected directory or folder. When you place this control into the form and run the program, you will be able to a list of files in a selected directory.
You can coordinate the Drive List Box, the Directory List Box and the File List Box to search for the files you want.
MENUS

Menu is a list of items to perform a particular task when the user clicks it.

Types:

Drop-down menu:
          It represents a class of components in the user interface. It will descend from the menu heading when the user clicks on the menu heading. Dragging the mouse over one of the items will highlight the drop down menu items.

Pop-up Menu:
          A pop-up menu can appear anywhere within a form, usually in response to click the right mouse button.

So a Drop-down menu and a Pop-up menu can be created using a Menu Editor as shown below.

Creation of Drop-Down menu:

1.  Click on the menu editor button in the Toolbar or select from the Tools menu or form right click.
2.  Enter identifier for the caption and name for each menu item. Caption will appear in the large area at the bottom of the menu editor. But the name willn’t displayed when the application is running.

Menu components must be entered in the following order.
1.  Enter 1st menu heading
2.  Click on next->click on right button. Enter the corresponding menu items for the 1st menu.
3.  The second menu heading and so on.

Accessing a menu from the keyboard:

A keyboard access character can be def9ined for each menu item. This allows the user to view a drop-down menu by pressing Alt or Ctrl key for the menu heading and for items. To define an access character for items select function key or ctrl+key from the field short cut in menu editor.

Menu Enhancements

Check Box: assigned to a menu item, indicating the on-off status of the menu item. Selecting the box labeled checked will cause the menu item to be checked initially.
Enabled Box: It is the ability to deactivate a menu item by deselecting the enabled box.

Submenu:

A menu item may have a submenu. Submenu is a menu with a list of items which is adjacent to the parent menu item. The use of submenus allows menu selections to be arranged in a logical, hierarchical manner.

Creation of submenu:

Simply indent the submenu items beneath the parent menu item within the menu editor. A right-pointing arrow at its edge will identify each menu item having a submenu.

Pop-up Menus:
A pop-up menu can appear anywhere within a form, usually in response to click the right mouse button.

Creation of pop-up menu
It is created via the menu editor in the same manner as a drop-down menu except that the main menu item is not visible. An event procedure must be entered into the code editor. The general form of the event procedure is

Private sub form_mouseDown(Button as Integer, Shift as Inter, X as Single, Y as Single )
If button=vbrightbutton then
Popmenu  ………
End if
End sub
All of the components of this event procedure have a predefined meaning

DIALOG BOXES

It is used to exchange information between the program and the user. It is used to display information for the user

Features

·    It usually doesn’t have a menu
·      Cant be resized
·    Act as the main interface of the application
(it is used to acquire user inputs that required to execute a certain action or to display messages)

Types of Dialog Box

1.         Modal              2.         Modeless

Modal: It willn’t let the user program any action while it is on display. Ex:- file open dialog, print dialog
Modeless: It allows the user to continue working with the program even though they remain displayed on screen Ex:- find and replace

Steps to add dialog form are:
1.   Go  to ‘Project’ Menu
2.   Select ‘Add Form’ option
3.   Select ‘dialog’ icon the dialog box and click on ‘open’ button.

Classification of Dialog Boxes:

1. Common Dialog Boxes:  These provide the functionality required for actions such as opening, saving and printing a file. These dialogs are available in a ready-to-use format

Actions

1.   Opening a file
2.   Saving a file
3.   Printing

2. Custom Dialog Boxes: These are dialog boxes designed to meet the requirements of the application and are designed by the programmer
The user to suit the needs of the application creates custom dialogs

1.         Use the common dialog boxes where possible. It saves on coding time and maintains a consistent look among applications.
2.         To accept just a single input from the user, use the Input Box
3.         To display a message, use the message box customizes the message box by using appropriate buttons and icons.
4.         Use custom dialog boxes when u needs to accept multiple inputs from the user. Use appropriate controls.
5.         Use Modal dialog boxes when it is necessary that the user provide input for the application to continue.

Predefined Dialog Boxes:

Message Box: It is a dialog box that displays text and used to create error messages. It returns a positive integer whose value depends on the action taken by the user.
           
Input Box:  It is similar to the MsgBox. This function is primarily intended to display a dialog box that accepts an input string whereas the MsgBox function is primarily intended to show an output string.
           
MsgBox Function
This function generates a dialog box which displays a given output string one or more command buttons and returns a positive integer whose value depends  on the action taken by the user.

Syntax:
Integer_variable = MsgBox(String, Int_value, Title)
String:- Message displayed to user.
Int_value:- it defines the command buttons that appear within the box
Title:-which specifies the title of the message box. Default is the name of the project.

The following list is some integer values and resulting MsgBox Command buttons.
Integer-Value                         Resulting Command Buttons
0                                  OK
1                                  OK,Cancel
2                                  Abort,Retry,Ignore
3                                  Yes,No,Cancel
4                                  Yes,No
5                                  Retry,Cancel

The following is the list of command buttons and their corresponding return values.

Command Button                 Return Value
            Ok                               1
            Cancel                         2
            Abort                           3
            Retry                           4
            Ignore                          5
            Yes                              6
            No                               7

Input Box Function
This function also invokes a dialog box and meant for accessing input value from the user.
Syntax:-
Var_name=Input Box(Prompt, Title, Default_value)
Prompt:- string appears as prompt for input.
Title:- Title of the inputbox, default is project name.
Default_value:- ‘default value’ of the input box.

DEBUGGING AND EXECUTING A NEW PROJECT

Error: It refers to the difference between the actual output of a program to the correct output. It can also be called as a bug.

Debugging: Identifying and removing errors occurred during program execution is called Debugging.
Errors are of 2 Types:
1.   Syntactic Errors
2.   Logical Errors

Syntactic Errors

This type of errors occurs when Visual Basic Commands are written improperly. These are known as ‘Compilation Errors’. These errors are relatively easy to fix, since the VB indentifies the error and highlights the line with Red Color in the ‘Code Editor Window’.

Logical Errors

Errors may also occur during program execution. Many execution errors are caused by faculty program logic and are known as Logical Errors or Runtime Errors. In the ‘Code Editor Window’ the line containing error will be highlighted with ‘Yellow Color’.

Debugging Features

The VB Debugger contains features that can assist in locating the source of errors for second type of logical errors.
These features include ‘stepping through a program’, setting breakpoints( which causes the execution to be suspended) and defining watch values.
VB Debugging features can be accessed in 3 ways:
1.   Via the Debug Menu on the Menu Bar
2.   Via the Debug toolbar
3.   By using function keys.

Setting Break Point

Generally a ‘break point’ is placed just before the suspected source of error. This is mainly used to execute the program in a normal manner, until the break point is encountered.
To set the breakpoint place the cursor in the statement where the ‘breakpoint’ is to be set we can select any of the following methods to set breakpoint.
1.   Select ‘Toggle Break Point’ option from Debug menu.
2.   Click ‘Toggle Break Point’  icon on the Debug ToolBar.
3.   Press f9.
After setting the ‘breakpoint’ the statement will be highlighted and we can observe a dark circle on the left of the selected statement.

Removing Break Point

A break point set can be removed by invoking ‘Toggle Break Point’ option again.

Temporary Break Point

We can set a temporary break point by selecting ‘Run TO Cursor’ option from Debug Menu by placing cursor at one position. It will be removed automatically after executing program once.

Defining Watch Values

Watch values are current values of variables or expressions that are displayed in Watches window. VB Supports 3 types of watch values.
1.   Ordinary Watch Values
2.   Quick Watch Values
3.   Immediate Watch Values

Ordinary Watch Values

These types of watch values are generally preferable because they remain active as you step through a program on a line-by-line basis. These are displayed in a separate ‘Watches’ Window.

Invoking ‘Watches’ Window
Select ‘Watch Window’ option from View Menu.

Setting Watch Values to Watches Window
1.   Right Click in the watches window
2.   Select add watch option from popup menu
3.   Give details in the ‘add watch’ window.

Edit or Delete Watch Values
Watch values in the watches window can be edited or deleted using Edit Watch Window which can be invoked from Debug Menu

Quick Watch Values
If we want to know the current value of a variable or expression that has not been added to the watches window then we can use ‘Quick Watch’ window.

Invoking Quick Watch Window
1.   First select the variable or expression
2.   Now select ‘Quick Watch’ option from Debug Menu
3.   Then details will be given in Quick Watch window.

Immediate Watch Window
If we want to know the value of a variable or expression immediately then we can use Immediate Watch Window. Inside the window the variable or expression must be preceded by ?.

Invoking Immediate Watch Window
Select ‘Immediate Window’ option from view menu

Stepping through a program
It is nothing but line-by-line execution of the program and can be done from any place in the program. There are actually 3 different types of stepping. These options can be invoked from Debug Menu.
1.   Step Info: This results in line-by-line execution with in a procedure. This is the starting step of ‘Step though a program’.
2.   Step Over: This is used for moving from one line to another in the process of line-by-line execution.
3.   Step Out: This is used for coming out of line-by-line execution.

User-Induced Errors
User-induced errors occur when user make a mistake while executing the program. This type of errors can be expected and can be trapped also using ‘Error handlers’ in VB.

Error Handling
An ‘error handler’ is a series of statements intended to trap the error and then to provide appropriate remedial action. The nature of the remedial action depends on the type of error encountered. Possible remedial actions are of 3 types. They are
1.   User can reenter input data that will prevent the error from occurring
2.   The source of error can be corrected automatically.
3.   The error can simply be by passed.

On Error GoTo Statement
While writing an ‘Error Handler’ we must trap the error and then redirect the program logic to a special part of the program known as On Error GoTo Statement. This statement redirects the program logic to a remote statement when an error occurs and the remote statement includes a label that is specified with in the ‘On Error GoTo Statement’.
Ex:       Private Sub Procedure_name( )
            On Error GoTo Label
            ----
            Exit Sub
            Label:
            ---
            Resume
            End Sub
We can write resume statement in 3 manners
1.   Resume label is useful if user is reentering the input data
2.   Resume is useful if error is corrected automatically
3.   ‘Resume next’ is useful if we want to bypass the error containing statement.
Suppose no error is found then EXIT SUB is executed and it takes cursor out of the sub procedure.
Runtime Errors
Error Code                            Corresponding Error Message
3                                              Without go sub
5                                              Invalid Procedure call or argument    
6                                              Overflow
7                                              Out of Memory
9                                              Subscript out of range
11                                            Division by Zero
13                                            Type of mismatch
35                                            Sub, function or property not defined
61                                            Disk Full
68                                            Device unavailable
92                                            For loop not initialize

Stand Alone Executable Programme
Once a program has been debugged we can generate separate stand alone version. These stand alone programs are convenient because they can be executed independently of the VB. These can be easily be portable i.e., transporting from one computer to another.
Steps
1.   Go to file Menu
2.   Select the option – “make exe”

PROCEDURES
            Large projects divided into ‘modules’ for easy maintenance. VB supports several types of modules, each of which is stored as a separate file.
Ex:-     Form Modules
            Standard Modules
            Class Modules
Procedures
Large modules are decomposed into multiple procedures for several reasons. First, the use of procedures eliminates redundancy. Secondly, it enhances the clarity of a program and performing the operations like debugging, modification etc., are easier.
A procedure is  a self contained group of VB commands that can be accessed from any part of the program.
VB Supports 4 types of procedures.
1.   Sub-Procedure
2.   Function Procedure
3.   Event Procedure
4.   Property procedure

Sub-procedure:- a ‘Sub-Procedure’ perfroms a predefined action either by receiving or withouot receiving arguments. It does not return a value back to calling procedure. It can be also called as ‘Sub-routine’.
Syntax:           Scope sub procedure_name(args)
In the above procedure definition, the scope can be either private or public.

Passing arguments to a sub-procedure
1.   By Value
2.   By Reference

By Value:-
While passing args to a procedure ‘By Value’ the arguments name within the procedure must be preceeded by the reserved word ‘ByVal’.
Syntax:- ByVal argument as Datatype
Ex:- Private Sub prime(ByVal n as Integer)

By Reference:-
While passing args to a procedure ‘by reference’ the srguments name within the procedure must be preceeded by the reserved word ‘ByRef’.
Syntax:-ByRef argument as datatype
Ex:-Private Sub prime(ByRef n as Integer)

Calling a Sub-Procedure
A sub-procedure can be called in 2 ways.
1.   By using ‘call’ statement.
Syntax: call procedure_name(args)
2.   Without using ‘call’ statement.
Syntax: procedure_name(args)

Function Procedure:
A function procedure is similar to a sub procedure with one important difference that it is intended to return a value. Each ‘function_name’ represents a data item and has a dataype associated with it. In the function definition, the ‘fun_name’ must be assigned a value, which acts as return value to calling function.

Syntax:
Scope function procedure_name(arguments) as Datatype
Procedure-name=value;
End function

Event Procedure:
An event procedure is a special type of sub-procedure. It ca n be accessed by a specific action like ‘clicking on an object rather than by the call statement. The particular action associated with ‘event-procedure’ is selected from upper-right dropdown menu within the code editor window. The object name and activating event collectively called as ‘event-procedure’.

Scope

Scope referes to the portion of a program in which a procedure definition is recognised.
·    A public procedure can be accessed from any module or from within a project.program.
·    A private procedure can be accessed only within the module or form in which it is defined

Accessing a public procedure
A public procedure can be accessed in the normal manner in  a form in which it is defined. If the procedure definiion is present in a different form then the procedure name must be preceeded by the form name to access it from other forms.

Form1                                                                          Form2
Public Sub textcls( )                                                    Private Sub Command1_Click( )
----------                                                                                    --------------------
End Sub                                                                      Call form1.textcls
Private Sub Command1_Click ( )                               End Sub
Call textcls
End Sub
ARRAYS

An array is a variable which contains table of similar items. Suppose we have to store the value of ten items. Instead of creating ten separate variables. We may create a single array having ten elements. It is a linear collection of similar elements.

Array Declaration
Scope array_name(subscript_upperlimit) as Datatype
Ex:      Dim/Private/Public  a(10) as Integer
Even we can specify the lower and upper limits of an array in the declaration.
Ex:      Dim a(1 To 10) as integer
Ex: Dim Arr(3) as Integer
In the above statement the number 3 inside the paranthesis is the index number of the array. The index number of an array starts from 0 and is used to refer to the elements of an array.

2-D array Declarations
Syntax: array_name(subscripts1-upperlimit, subscripts2-upperlimit) as datatype
Ex: Dim a (10,2) as integer
Dim a(1 To 10, 1 To 2) as Integer.

Dynamic Array
It is an array whose sizes can be changed at various places within a program. Dynamic array name is followed by empty pair of parenthesis.
Syntax: Scope array_name() as datatype      
Ex:      Dim a() as Integer

Specification of array size
Dynamic array size can be specified during execution of program using ‘Redim’ Statement
Ex: Redim a(10)
When a dynamic array is redimensioned the previous values of the array will be lost. They will be set to zero if it is integer array otherwise, to null if it is a string.

Preserve Keyword
To retain the previous values when the array is resized, we use ‘preserve’ keyword’ in the Redim Statement.
Syntax: Redim Preserve array_name(upperlimit)




Control Arrays

Multiple control of the same type can be grouped into an array, such a group is known as a ‘control array’.
#          Control array elements may share a common event procedure.
#          Control array elements are distinguished from each other using index.
#          Control array are created at design time.
#          Additional control array elements can also be added and later deleted at runtime.
#          All control array elements will share common name but indexes are different.

Creation of a Control Array
A control array can be created by placing a control within the form design window and assigning a value of 0 to its index property. Then copy and paste control, it results a new control within the  same name in the upper left control of the form design window.

Addition of a new control array element
Once a control array element has been created an addition element can be added during runtime, using the Load statement i.e.,
Syntax:           load Control_name(index)

Deletion of control array element at runtime
An element added at runtime can later be deleted, using unload statement
Syntax:unload controlarray_element(index)
Syntax:           For each index in array_name
            ----
            Next
            For Each I in a
            ----
            Next

DATA FILES

A file is orderly, self-contained collection of information. Any type of information can be stored within a file.  A file may contain the instructions that comprise a VB program it may consists of data values is commonly known as Data File.

Data File Characteristics:
VB recognizes 3 different types of data files.
1.   Sequential files
2.   Random Access Files
3.   Binary Files
Sequential files are created by a text editor or word processor or by a VB program.

Random access files are organized into fixed-length records. Any record can be accessed directly by specifying the corresponding record number or record location.

Binary files store information as a continuous sequence of bytes. Such files appear unintelligible when printed or displayed on a computer screen, but their contents can be read into or written out of a computer faster than other file types.

Accessing and Saving a file in Visual Basic: (Common Dialog Control)

VB includes special tools for opening an existing file, and for saving a new file or an existing file that has been modified.
These tools are included in a group of “Common Dialog Objects” that must be added to the ToolBox before any of these tools can be accessed. To do so select components from the project menu then click on the controls tab and check the box labeled “Microsoft Common Dialog Control” once the Common Dialog control has been activated, icon will be appeared in the toolbox.

The Common Dialog Control does not appear within the form when the project is being executed.

The Common Dialog Control allows an application to easily access existing files or save new files through its Common Dialog boxes.

To access an existing file, simple add a following statement at the appropriate place.
Common Dialog1.showopen

When this statement is encountered during program execution, a dialog box will appear. The user may then use this dialog box to access a file within the currently active folder or another folder.

The type of files can be specified within the program by assigning an appropriate string to common dialog1. filter property
CommonDialog1.filter = “Text files(*.txt)/*.txt”

This statement displays only text files when we open a dialog box. Similarly to save a file with a specified name add a statement such as
CommonDialog1.showsave

When the showsave statement is encountered a dialog box will appear. The user may than use this dialog box to save a file within the currently active folder or some other folder.

Similarly to print a file : CommonDialog1.showprint

Processing a Data File

To process a data file the following three tasks must be carried out.
·    Open a data file
·    Process the file, as required by the application
·    Close the file
Opening the data file associates a file number with a named data file.

It also specifies certain information about the data file, such as the mode, the access type, the restrictions. Processing the data file generally involves reading the data items, modifying the data items, displaying the data items, and writing the modified data items.
Closing the data file is a formality that simply deactivates the conditions that  were specified when the file was opened.

Sequential Data Files

In a sequential data file the data can be stored sequentially as plain text. The text is organized into individual lines; each line of text can contain both numeric constants and strings in any combination. When opening a sequential file, the open statement is generally written in one three ways, depending on whether the file is an input file, an output file or an append file.

The three possibilities are
Open filename for Input As #n
Open filename for Output As #n
Open filename for Append As #n

Where  n refers to the channel number
Data items are usually read from a sequential data file via the Input # statement. This statement is written in
general terms as : Input #n, data items
Where n refers to the channel number and data items refers to the list of input data items, separated by commas. The input data items are typically variables, array elements, control properties, etc
Similarly data items are usually written to a sequential data file via he print # statement.
General term is : print #n, data items
Where the data items can be constants, variables, expressions, array elements, control properties etc.
There are other ways to enter and write data that are convenient in certain situations.
i.e., Line Input #n data item
it enters an entire line of text as a single data item.
Similarly the write statement is very useful when generating a text file from information entered from the keyboard.
General Form: write #n, data items

RANDOM ACCESS (DIRECT) DATA FILES

Random access data files consist of a collection of fixed length records, each of which is assigned a unique record number.
Once a random access file has been opened, referencing its record number can access an individual record
The open statement is written as

Open filename for random as #n len=record length
Or
Open filename as #n len=record length

Random is the default file type
The record length must be large enough to accommodate each of the fixed length data items that will be stored within the random access data file.
The record length may be written as an integer constant or an expression.
The library function len returns the length of the record.
Data items are read from a random access data file, one record at a time, via the get # statement.
General Form: Get #n, record number, data item
Or simply: get #n, data item
Data items are written to a random access data file, one record at a time, via the put# statement
General form: put #n, record number, data item
Or simply:put #n, data item

Binary Files
Binary files contain information expressed as a stream of consecutive, unformatted bytes. A binary file may represent a graphic, a sound file or compiled code.
To open a binary file, we use the open statement in the following manner
Open filename for Binary As #n
Where filename represents the filename and n represents the data channel number.
Information is read from a binary file. We use the Get # statement to read a binary file.
i.e., Get #n, first byte, data item
where first byte is a positive integer that represents the number of the first byte read. The surrounding commas must be present if first byte is committed.
i.e., Get #n, data item
information is written to a binary file in the same manner, using the Put # statement.
i.e., Put #n, first byte, data item

where first byte is a positive integer that represents the number of the first byte written. The surrounding commas must be present if first byte is omitted.
i.e., Put#n,  , data item 

No comments: